1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.devicepolicy;
18 
19 import static android.Manifest.permission.BIND_DEVICE_ADMIN;
20 import static android.Manifest.permission.LOCK_DEVICE;
21 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
22 import static android.Manifest.permission.MANAGE_DEFAULT_APPLICATIONS;
23 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT;
24 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACROSS_USERS;
25 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL;
26 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL;
27 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AIRPLANE_MODE;
28 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_APPS_CONTROL;
29 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_APP_RESTRICTIONS;
30 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AUDIO_OUTPUT;
31 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AUTOFILL;
32 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_BLUETOOTH;
33 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CALLS;
34 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CAMERA;
35 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CERTIFICATES;
36 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE;
37 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES;
38 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEFAULT_SMS;
39 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DISPLAY;
40 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FACTORY_RESET;
41 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FUN;
42 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INPUT_METHODS;
43 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES;
44 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_KEYGUARD;
45 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCALE;
46 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCATION;
47 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK;
48 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS;
49 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_TASK;
50 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MICROPHONE;
51 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MOBILE_NETWORK;
52 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MODIFY_USERS;
53 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MTE;
54 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION;
55 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY;
56 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PACKAGE_STATE;
57 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA;
58 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PRINTING;
59 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILES;
60 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILE_INTERACTION;
61 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESET_PASSWORD;
62 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS;
63 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS;
64 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUN_IN_BACKGROUND;
65 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SAFE_BOOT;
66 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CAPTURE;
67 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CONTENT;
68 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SECURITY_LOGGING;
69 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SMS;
70 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_STATUS_BAR;
71 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE;
72 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS;
73 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_UPDATES;
74 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_TIME;
75 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING;
76 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER;
77 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_VPN;
78 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WALLPAPER;
79 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIFI;
80 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WINDOWS;
81 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIPE_DATA;
82 import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
83 import static android.Manifest.permission.MASTER_CLEAR;
84 import static android.Manifest.permission.QUERY_ADMIN_POLICY;
85 import static android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY;
86 import static android.Manifest.permission.SET_TIME;
87 import static android.Manifest.permission.SET_TIME_ZONE;
88 import static android.accessibilityservice.AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
89 import static android.accounts.AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION;
90 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
91 import static android.app.AppOpsManager.MODE_ALLOWED;
92 import static android.app.AppOpsManager.MODE_DEFAULT;
93 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION;
94 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS;
95 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION;
96 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS;
97 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION;
98 import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_AFFILIATED;
99 import static android.app.admin.DeviceAdminInfo.USES_POLICY_FORCE_LOCK;
100 import static android.app.admin.DeviceAdminInfo.USES_POLICY_WIPE_DATA;
101 import static android.app.admin.DeviceAdminReceiver.ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED;
102 import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE;
103 import static android.app.admin.DevicePolicyIdentifiers.AUTO_TIMEZONE_POLICY;
104 import static android.app.admin.DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE;
105 import static android.app.admin.DevicePolicyManager.ACTION_DEVICE_FINANCING_STATE_CHANGED;
106 import static android.app.admin.DevicePolicyManager.ACTION_DEVICE_POLICY_RESOURCE_UPDATED;
107 import static android.app.admin.DevicePolicyManager.ACTION_MANAGED_PROFILE_PROVISIONED;
108 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE;
109 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE;
110 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
111 import static android.app.admin.DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED;
112 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
113 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
114 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
115 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_SELECTION;
116 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
117 import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE;
118 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
119 import static android.app.admin.DevicePolicyManager.DELEGATION_NETWORK_LOGGING;
120 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
121 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
122 import static android.app.admin.DevicePolicyManager.DELEGATION_SECURITY_LOGGING;
123 import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_DEFAULT;
124 import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_FINANCED;
125 import static android.app.admin.DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
126 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION;
127 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS;
128 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_HIBERNATION;
129 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_POWER_RESTRICTIONS;
130 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_SUSPENSION;
131 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE;
132 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_IDS;
133 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE;
134 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_DRAWABLE;
135 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_STRING;
136 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
137 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
138 import static android.app.admin.DevicePolicyManager.ID_TYPE_INDIVIDUAL_ATTESTATION;
139 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
140 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
141 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
142 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK;
143 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
144 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME;
145 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_KEYGUARD;
146 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS;
147 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
148 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO;
149 import static android.app.admin.DevicePolicyManager.NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
150 import static android.app.admin.DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
151 import static android.app.admin.DevicePolicyManager.OPERATION_SAFETY_REASON_NONE;
152 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
153 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_LOW;
154 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
155 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
156 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
157 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
158 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK;
159 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
160 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED;
161 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
162 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
163 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
164 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
165 import static android.app.admin.DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
166 import static android.app.admin.DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED;
167 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED;
168 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_EXPLICITLY;
169 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT;
170 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OFF;
171 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
172 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
173 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_UNKNOWN;
174 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
175 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR;
176 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
177 import static android.app.admin.DevicePolicyManager.STATE_USER_SETUP_FINALIZED;
178 import static android.app.admin.DevicePolicyManager.STATE_USER_UNMANAGED;
179 import static android.app.admin.DevicePolicyManager.STATUS_ACCOUNTS_NOT_EMPTY;
180 import static android.app.admin.DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE;
181 import static android.app.admin.DevicePolicyManager.STATUS_DEVICE_ADMIN_NOT_SUPPORTED;
182 import static android.app.admin.DevicePolicyManager.STATUS_HAS_DEVICE_OWNER;
183 import static android.app.admin.DevicePolicyManager.STATUS_HAS_PAIRED;
184 import static android.app.admin.DevicePolicyManager.STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED;
185 import static android.app.admin.DevicePolicyManager.STATUS_MANAGED_USERS_NOT_SUPPORTED;
186 import static android.app.admin.DevicePolicyManager.STATUS_NONSYSTEM_USER_EXISTS;
187 import static android.app.admin.DevicePolicyManager.STATUS_NOT_SYSTEM_USER;
188 import static android.app.admin.DevicePolicyManager.STATUS_OK;
189 import static android.app.admin.DevicePolicyManager.STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
190 import static android.app.admin.DevicePolicyManager.STATUS_SYSTEM_USER;
191 import static android.app.admin.DevicePolicyManager.STATUS_USER_HAS_PROFILE_OWNER;
192 import static android.app.admin.DevicePolicyManager.STATUS_USER_NOT_RUNNING;
193 import static android.app.admin.DevicePolicyManager.STATUS_USER_SETUP_COMPLETED;
194 import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
195 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
196 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
197 import static android.app.admin.DevicePolicyManager.WIPE_SILENTLY;
198 import static android.app.admin.DevicePolicyResources.Strings.Core.LOCATION_CHANGED_MESSAGE;
199 import static android.app.admin.DevicePolicyResources.Strings.Core.LOCATION_CHANGED_TITLE;
200 import static android.app.admin.DevicePolicyResources.Strings.Core.NETWORK_LOGGING_MESSAGE;
201 import static android.app.admin.DevicePolicyResources.Strings.Core.NETWORK_LOGGING_TITLE;
202 import static android.app.admin.DevicePolicyResources.Strings.Core.NOTIFICATION_WORK_PROFILE_CONTENT_DESCRIPTION;
203 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_MESSAGE;
204 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_SOON_MESSAGE;
205 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_TITLE;
206 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_TURN_ON_PROFILE;
207 import static android.app.admin.DevicePolicyResources.Strings.Core.PRINTING_DISABLED_NAMED_ADMIN;
208 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_FAILED_PASSWORD_ATTEMPTS_MESSAGE;
209 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_GENERIC_MESSAGE;
210 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_ORG_OWNED_MESSAGE;
211 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_TITLE;
212 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_BODY;
213 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_TITLE;
214 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_TURN_ON_BUTTON;
215 import static android.app.admin.ProvisioningException.ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED;
216 import static android.app.admin.ProvisioningException.ERROR_PRE_CONDITION_FAILED;
217 import static android.app.admin.ProvisioningException.ERROR_PROFILE_CREATION_FAILED;
218 import static android.app.admin.ProvisioningException.ERROR_REMOVE_NON_REQUIRED_APPS_FAILED;
219 import static android.app.admin.ProvisioningException.ERROR_SETTING_PROFILE_OWNER_FAILED;
220 import static android.app.admin.ProvisioningException.ERROR_SET_DEVICE_OWNER_FAILED;
221 import static android.app.admin.ProvisioningException.ERROR_STARTING_PROFILE_FAILED;
222 import static android.content.Intent.ACTION_MANAGED_PROFILE_AVAILABLE;
223 import static android.content.Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE;
224 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
225 import static android.content.pm.PackageManager.GET_META_DATA;
226 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
227 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
228 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
229 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
230 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT;
231 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE;
232 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING;
233 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK;
234 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
235 import static android.provider.DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER;
236 import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER;
237 import static android.provider.Settings.Secure.MANAGED_PROVISIONING_DPC_DOWNLOADED;
238 import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
239 import static android.provider.Telephony.Carriers.DPC_URI;
240 import static android.provider.Telephony.Carriers.ENFORCE_KEY;
241 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI;
242 import static android.provider.Telephony.Carriers.INVALID_APN_ID;
243 import static android.security.keystore.AttestationUtils.USE_INDIVIDUAL_ATTESTATION;
244 
245 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
246 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
247 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
248 import static com.android.server.SystemTimeZone.TIME_ZONE_CONFIDENCE_HIGH;
249 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
250 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER;
251 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER;
252 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
253 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_DEVICE_OWNER;
254 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER;
255 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;
256 
257 import android.Manifest;
258 import android.Manifest.permission;
259 import android.accessibilityservice.AccessibilityServiceInfo;
260 import android.accounts.Account;
261 import android.accounts.AccountManager;
262 import android.accounts.AuthenticatorException;
263 import android.accounts.OperationCanceledException;
264 import android.annotation.IntDef;
265 import android.annotation.NonNull;
266 import android.annotation.Nullable;
267 import android.annotation.UserIdInt;
268 import android.app.Activity;
269 import android.app.ActivityManager;
270 import android.app.ActivityManagerInternal;
271 import android.app.ActivityTaskManager;
272 import android.app.AlarmManager;
273 import android.app.AppGlobals;
274 import android.app.AppOpsManager;
275 import android.app.AppOpsManager.Mode;
276 import android.app.BroadcastOptions;
277 import android.app.IActivityManager;
278 import android.app.IActivityTaskManager;
279 import android.app.IApplicationThread;
280 import android.app.IServiceConnection;
281 import android.app.Notification;
282 import android.app.NotificationManager;
283 import android.app.PendingIntent;
284 import android.app.StatusBarManager;
285 import android.app.admin.AccountTypePolicyKey;
286 import android.app.admin.BooleanPolicyValue;
287 import android.app.admin.BundlePolicyValue;
288 import android.app.admin.ComponentNamePolicyValue;
289 import android.app.admin.DeviceAdminInfo;
290 import android.app.admin.DeviceAdminReceiver;
291 import android.app.admin.DevicePolicyCache;
292 import android.app.admin.DevicePolicyDrawableResource;
293 import android.app.admin.DevicePolicyEventLogger;
294 import android.app.admin.DevicePolicyManager;
295 import android.app.admin.DevicePolicyManager.DeviceOwnerType;
296 import android.app.admin.DevicePolicyManager.DevicePolicyOperation;
297 import android.app.admin.DevicePolicyManager.OperationSafetyReason;
298 import android.app.admin.DevicePolicyManager.PasswordComplexity;
299 import android.app.admin.DevicePolicyManager.PersonalAppsSuspensionReason;
300 import android.app.admin.DevicePolicyManagerInternal;
301 import android.app.admin.DevicePolicyManagerLiteInternal;
302 import android.app.admin.DevicePolicySafetyChecker;
303 import android.app.admin.DevicePolicyState;
304 import android.app.admin.DevicePolicyStringResource;
305 import android.app.admin.DeviceStateCache;
306 import android.app.admin.FactoryResetProtectionPolicy;
307 import android.app.admin.FullyManagedDeviceProvisioningParams;
308 import android.app.admin.IDevicePolicyManager;
309 import android.app.admin.IntegerPolicyValue;
310 import android.app.admin.IntentFilterPolicyKey;
311 import android.app.admin.LockTaskPolicy;
312 import android.app.admin.LongPolicyValue;
313 import android.app.admin.ManagedProfileProvisioningParams;
314 import android.app.admin.ManagedSubscriptionsPolicy;
315 import android.app.admin.NetworkEvent;
316 import android.app.admin.PackagePolicy;
317 import android.app.admin.ParcelableGranteeMap;
318 import android.app.admin.ParcelableResource;
319 import android.app.admin.PasswordMetrics;
320 import android.app.admin.PasswordPolicy;
321 import android.app.admin.PolicyKey;
322 import android.app.admin.PolicyValue;
323 import android.app.admin.PreferentialNetworkServiceConfig;
324 import android.app.admin.SecurityLog;
325 import android.app.admin.SecurityLog.SecurityEvent;
326 import android.app.admin.StartInstallingUpdateCallback;
327 import android.app.admin.StringSetPolicyValue;
328 import android.app.admin.SystemUpdateInfo;
329 import android.app.admin.SystemUpdatePolicy;
330 import android.app.admin.UnsafeStateException;
331 import android.app.admin.UserRestrictionPolicyKey;
332 import android.app.admin.WifiSsidPolicy;
333 import android.app.backup.IBackupManager;
334 import android.app.compat.CompatChanges;
335 import android.app.role.OnRoleHoldersChangedListener;
336 import android.app.role.RoleManager;
337 import android.app.trust.TrustManager;
338 import android.app.usage.UsageStatsManagerInternal;
339 import android.compat.annotation.ChangeId;
340 import android.compat.annotation.EnabledAfter;
341 import android.compat.annotation.EnabledSince;
342 import android.content.ActivityNotFoundException;
343 import android.content.BroadcastReceiver;
344 import android.content.ComponentName;
345 import android.content.ContentResolver;
346 import android.content.ContentValues;
347 import android.content.Context;
348 import android.content.IIntentReceiver;
349 import android.content.IIntentSender;
350 import android.content.Intent;
351 import android.content.IntentFilter;
352 import android.content.IntentSender;
353 import android.content.PermissionChecker;
354 import android.content.pm.ActivityInfo;
355 import android.content.pm.ApplicationInfo;
356 import android.content.pm.CrossProfileApps;
357 import android.content.pm.CrossProfileAppsInternal;
358 import android.content.pm.IPackageDataObserver;
359 import android.content.pm.IPackageManager;
360 import android.content.pm.PackageInfo;
361 import android.content.pm.PackageInstaller;
362 import android.content.pm.PackageManager;
363 import android.content.pm.PackageManager.NameNotFoundException;
364 import android.content.pm.PackageManagerInternal;
365 import android.content.pm.ParceledListSlice;
366 import android.content.pm.PermissionInfo;
367 import android.content.pm.ResolveInfo;
368 import android.content.pm.ServiceInfo;
369 import android.content.pm.Signature;
370 import android.content.pm.StringParceledListSlice;
371 import android.content.pm.UserInfo;
372 import android.content.pm.UserPackage;
373 import android.content.pm.parsing.FrameworkParsingPackageUtils;
374 import android.content.res.Resources;
375 import android.database.ContentObserver;
376 import android.database.Cursor;
377 import android.graphics.Bitmap;
378 import android.hardware.usb.UsbManager;
379 import android.location.Location;
380 import android.location.LocationManager;
381 import android.media.AudioManager;
382 import android.media.IAudioService;
383 import android.net.ConnectivityManager;
384 import android.net.ConnectivitySettingsManager;
385 import android.net.IIpConnectivityMetrics;
386 import android.net.ProfileNetworkPreference;
387 import android.net.ProxyInfo;
388 import android.net.Uri;
389 import android.net.VpnManager;
390 import android.net.metrics.IpConnectivityLog;
391 import android.net.wifi.WifiManager;
392 import android.os.AsyncTask;
393 import android.os.Binder;
394 import android.os.Build;
395 import android.os.Bundle;
396 import android.os.Handler;
397 import android.os.IBinder;
398 import android.os.Looper;
399 import android.os.ParcelFileDescriptor;
400 import android.os.PersistableBundle;
401 import android.os.PowerManager;
402 import android.os.PowerManagerInternal;
403 import android.os.Process;
404 import android.os.RemoteCallback;
405 import android.os.RemoteException;
406 import android.os.ResultReceiver;
407 import android.os.ServiceManager;
408 import android.os.ServiceSpecificException;
409 import android.os.ShellCallback;
410 import android.os.SystemClock;
411 import android.os.SystemProperties;
412 import android.os.UserHandle;
413 import android.os.UserManager;
414 import android.os.UserManager.EnforcingUser;
415 import android.os.UserManager.UserRestrictionSource;
416 import android.os.storage.StorageManager;
417 import android.permission.AdminPermissionControlParams;
418 import android.permission.IPermissionManager;
419 import android.permission.PermissionControllerManager;
420 import android.provider.CalendarContract;
421 import android.provider.ContactsContract.QuickContact;
422 import android.provider.ContactsInternal;
423 import android.provider.DeviceConfig;
424 import android.provider.Settings;
425 import android.provider.Settings.Global;
426 import android.provider.Telephony;
427 import android.security.AppUriAuthenticationPolicy;
428 import android.security.IKeyChainAliasCallback;
429 import android.security.IKeyChainService;
430 import android.security.KeyChain;
431 import android.security.KeyChain.KeyChainConnection;
432 import android.security.KeyStore;
433 import android.security.keymaster.KeymasterCertificateChain;
434 import android.security.keystore.AttestationUtils;
435 import android.security.keystore.KeyGenParameterSpec;
436 import android.security.keystore.ParcelableKeyGenParameterSpec;
437 import android.stats.devicepolicy.DevicePolicyEnums;
438 import android.telecom.TelecomManager;
439 import android.telephony.SubscriptionManager;
440 import android.telephony.TelephonyManager;
441 import android.telephony.data.ApnSetting;
442 import android.text.TextUtils;
443 import android.text.format.DateUtils;
444 import android.util.ArrayMap;
445 import android.util.ArraySet;
446 import android.util.AtomicFile;
447 import android.util.DebugUtils;
448 import android.util.IndentingPrintWriter;
449 import android.util.IntArray;
450 import android.util.Pair;
451 import android.util.Slog;
452 import android.util.SparseArray;
453 import android.util.Xml;
454 import android.view.IWindowManager;
455 import android.view.accessibility.AccessibilityManager;
456 import android.view.accessibility.IAccessibilityManager;
457 import android.view.inputmethod.InputMethodInfo;
458 
459 import com.android.internal.R;
460 import com.android.internal.annotations.GuardedBy;
461 import com.android.internal.annotations.VisibleForTesting;
462 import com.android.internal.app.LocalePicker;
463 import com.android.internal.infra.AndroidFuture;
464 import com.android.internal.logging.MetricsLogger;
465 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
466 import com.android.internal.net.NetworkUtilsInternal;
467 import com.android.internal.notification.SystemNotificationChannels;
468 import com.android.internal.os.BackgroundThread;
469 import com.android.internal.statusbar.IStatusBarService;
470 import com.android.internal.telephony.SmsApplication;
471 import com.android.internal.util.ArrayUtils;
472 import com.android.internal.util.DumpUtils;
473 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
474 import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
475 import com.android.internal.util.JournaledFile;
476 import com.android.internal.util.Preconditions;
477 import com.android.internal.util.StatLogger;
478 import com.android.internal.widget.LockPatternUtils;
479 import com.android.internal.widget.LockSettingsInternal;
480 import com.android.internal.widget.LockscreenCredential;
481 import com.android.internal.widget.PasswordValidationError;
482 import com.android.modules.utils.TypedXmlPullParser;
483 import com.android.modules.utils.TypedXmlSerializer;
484 import com.android.net.module.util.ProxyUtils;
485 import com.android.server.AlarmManagerInternal;
486 import com.android.server.LocalManagerRegistry;
487 import com.android.server.LocalServices;
488 import com.android.server.LockGuard;
489 import com.android.server.PersistentDataBlockManagerInternal;
490 import com.android.server.SystemServerInitThreadPool;
491 import com.android.server.SystemService;
492 import com.android.server.SystemServiceManager;
493 import com.android.server.devicepolicy.ActiveAdmin.TrustAgentInfo;
494 import com.android.server.inputmethod.InputMethodManagerInternal;
495 import com.android.server.net.NetworkPolicyManagerInternal;
496 import com.android.server.pm.DefaultCrossProfileIntentFilter;
497 import com.android.server.pm.DefaultCrossProfileIntentFiltersUtils;
498 import com.android.server.pm.PackageManagerLocal;
499 import com.android.server.pm.RestrictionsSet;
500 import com.android.server.pm.UserManagerInternal;
501 import com.android.server.pm.UserManagerInternal.UserRestrictionsListener;
502 import com.android.server.pm.UserRestrictionsUtils;
503 import com.android.server.pm.pkg.AndroidPackage;
504 import com.android.server.storage.DeviceStorageMonitorInternal;
505 import com.android.server.uri.NeededUriGrants;
506 import com.android.server.uri.UriGrantsManagerInternal;
507 import com.android.server.utils.Slogf;
508 import com.android.server.wm.ActivityTaskManagerInternal;
509 
510 import org.xmlpull.v1.XmlPullParserException;
511 
512 import java.io.ByteArrayInputStream;
513 import java.io.File;
514 import java.io.FileDescriptor;
515 import java.io.FileInputStream;
516 import java.io.FileOutputStream;
517 import java.io.IOException;
518 import java.io.PrintWriter;
519 import java.lang.reflect.Constructor;
520 import java.security.cert.CertificateException;
521 import java.security.cert.CertificateFactory;
522 import java.security.cert.X509Certificate;
523 import java.text.DateFormat;
524 import java.time.LocalDate;
525 import java.util.ArrayDeque;
526 import java.util.ArrayList;
527 import java.util.Arrays;
528 import java.util.Collection;
529 import java.util.Collections;
530 import java.util.Date;
531 import java.util.HashMap;
532 import java.util.HashSet;
533 import java.util.LinkedHashMap;
534 import java.util.List;
535 import java.util.Locale;
536 import java.util.Map;
537 import java.util.Objects;
538 import java.util.Queue;
539 import java.util.Set;
540 import java.util.concurrent.CompletableFuture;
541 import java.util.concurrent.ExecutionException;
542 import java.util.concurrent.Executor;
543 import java.util.concurrent.LinkedBlockingQueue;
544 import java.util.concurrent.ThreadPoolExecutor;
545 import java.util.concurrent.TimeUnit;
546 import java.util.concurrent.TimeoutException;
547 import java.util.function.Consumer;
548 import java.util.function.Function;
549 import java.util.function.Predicate;
550 import java.util.stream.Collectors;
551 
552 /**
553  * Implementation of the device policy APIs.
554  */
555 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
556 
557     protected static final String LOG_TAG = "DevicePolicyManager";
558 
559     private static final String ATTRIBUTION_TAG = "DevicePolicyManagerService";
560 
561     static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
562 
563     static final String DEVICE_POLICIES_XML = "device_policies.xml";
564 
565     static final String POLICIES_VERSION_XML = "device_policies_version";
566 
567     private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML =
568             "transfer-ownership-parameters.xml";
569 
570     private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle";
571 
572     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
573 
574     private static final int REQUEST_PROFILE_OFF_DEADLINE = 5572;
575 
576     // Binary XML serializer doesn't support longer strings
577     private static final int MAX_POLICY_STRING_LENGTH = 65535;
578     // FrameworkParsingPackageUtils#MAX_FILE_NAME_SIZE, Android packages are used in dir names.
579     private static final int MAX_PACKAGE_NAME_LENGTH = 223;
580 
581     private static final int MAX_PROFILE_NAME_LENGTH = 200;
582     private static final int MAX_LONG_SUPPORT_MESSAGE_LENGTH = 20000;
583     private static final int MAX_SHORT_SUPPORT_MESSAGE_LENGTH = 200;
584     private static final int MAX_ORG_NAME_LENGTH = 200;
585 
586     private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
587 
588     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
589     private static final long MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD = 3 * MS_PER_DAY;
590     /** When to warn the user about the approaching work profile off deadline: 1 day before */
591     private static final long MANAGED_PROFILE_OFF_WARNING_PERIOD = 1 * MS_PER_DAY;
592 
593     private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION =
594             "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
595 
596     /** Broadcast action invoked when the user taps a notification to turn the profile on. */
597     @VisibleForTesting
598     static final String ACTION_TURN_PROFILE_ON_NOTIFICATION =
599             "com.android.server.ACTION_TURN_PROFILE_ON_NOTIFICATION";
600 
601     /** Broadcast action for tracking managed profile maximum time off. */
602     @VisibleForTesting
603     static final String ACTION_PROFILE_OFF_DEADLINE =
604             "com.android.server.ACTION_PROFILE_OFF_DEADLINE";
605 
606     private static final String CALLED_FROM_PARENT = "calledFromParent";
607     private static final String NOT_CALLED_FROM_PARENT = "notCalledFromParent";
608 
609     private static final String CREDENTIAL_MANAGEMENT_APP = "credentialManagementApp";
610     private static final String NOT_CREDENTIAL_MANAGEMENT_APP = "notCredentialManagementApp";
611 
612     private static final String NULL_STRING_ARRAY = "nullStringArray";
613 
614     private static final String ALLOW_USER_PROVISIONING_KEY = "ro.config.allowuserprovisioning";
615 
616     // Comprehensive list of delegations.
617     private static final String DELEGATIONS[] = {
618         DELEGATION_CERT_INSTALL,
619         DELEGATION_APP_RESTRICTIONS,
620         DELEGATION_BLOCK_UNINSTALL,
621         DELEGATION_ENABLE_SYSTEM_APP,
622         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
623         DELEGATION_PACKAGE_ACCESS,
624         DELEGATION_PERMISSION_GRANT,
625         DELEGATION_INSTALL_EXISTING_PACKAGE,
626         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
627         DELEGATION_NETWORK_LOGGING,
628         DELEGATION_SECURITY_LOGGING,
629         DELEGATION_CERT_SELECTION,
630     };
631 
632     // Subset of delegations that can only be delegated by Device Owner or Profile Owner of a
633     // managed profile.
634     private static final List<String> DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS =
635             Arrays.asList(new String[]{
636                     DELEGATION_NETWORK_LOGGING,
637             });
638 
639     // Subset of delegations that can only be delegated by Device Owner or Profile Owner of an
640     // organization-owned and managed profile.
641     private static final List<String>
642             DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS =
643             Arrays.asList(new String[]{
644                     DELEGATION_SECURITY_LOGGING,
645             });
646 
647     // Subset of delegations that only one single package within a given user can hold
648     private static final List<String> EXCLUSIVE_DELEGATIONS = Arrays.asList(new String[] {
649             DELEGATION_NETWORK_LOGGING,
650             DELEGATION_SECURITY_LOGGING,
651             DELEGATION_CERT_SELECTION,
652     });
653 
654     /**
655      * System property whose value indicates whether the device is fully owned by an organization:
656      * it can be either a device owner device, or a device with an organization-owned managed
657      * profile.
658      *
659      * <p>The state is stored as a Boolean string.
660      */
661     private static final String PROPERTY_ORGANIZATION_OWNED = "ro.organization_owned";
662 
663     private static final int STATUS_BAR_DISABLE_MASK =
664             StatusBarManager.DISABLE_EXPAND |
665             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
666             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
667             StatusBarManager.DISABLE_SEARCH;
668 
669     private static final int STATUS_BAR_DISABLE2_MASK =
670             StatusBarManager.DISABLE2_QUICK_SETTINGS;
671 
672     private static final Set<String> SECURE_SETTINGS_ALLOWLIST;
673     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST;
674     private static final Set<String> GLOBAL_SETTINGS_ALLOWLIST;
675     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
676     private static final Set<String> SYSTEM_SETTINGS_ALLOWLIST;
677     private static final Set<Integer> DA_DISALLOWED_POLICIES;
678     private static final String AB_DEVICE_KEY = "ro.build.ab_update";
679     // The version of the current DevicePolicyManagerService data. This version is used
680     // to decide whether an existing policy in the {@link #DEVICE_POLICIES_XML} needs to
681     // be upgraded. See {@link PolicyVersionUpgrader} on instructions how to add an upgrade
682     // step.
683     static final int DPMS_VERSION = 6;
684 
685     static {
686         SECURE_SETTINGS_ALLOWLIST = new ArraySet<>();
687         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
688         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
689         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
690 
691         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST = new ArraySet<>();
692         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.addAll(SECURE_SETTINGS_ALLOWLIST);
693         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.add(Settings.Secure.LOCATION_MODE);
694 
695         GLOBAL_SETTINGS_ALLOWLIST = new ArraySet<>();
696         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_ENABLED);
697         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_WIFI_ENABLED);
698         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME);
699         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME_ZONE);
700         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.DATA_ROAMING);
701         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
702         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_SLEEP_POLICY);
703         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
704         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
705         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_MODE);
706         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER);
707 
708         GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
709         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
710         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
711         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
712         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
713         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
714 
715         SYSTEM_SETTINGS_ALLOWLIST = new ArraySet<>();
716         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS);
717         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_FLOAT);
718         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE);
719         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_OFF_TIMEOUT);
720 
721         DA_DISALLOWED_POLICIES = new ArraySet<>();
722         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
723         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
724         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
725         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
726     }
727 
728     /**
729      * Keyguard features that when set on a profile affect the profile content or challenge only.
730      * These cannot be set on the managed profile's parent DPM instance
731      */
732     private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
733             DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
734 
735     /** Keyguard features that are allowed to be set on a managed profile */
736     private static final int PROFILE_KEYGUARD_FEATURES =
737             NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
738                     | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
739 
740     private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
741 
742     /**
743      * Minimum timeout in milliseconds after which unlocking with weak auth times out,
744      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
745      */
746     private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
747 
748     /**
749      * The amount of ms that a managed kiosk must go without user interaction to be considered
750      * unattended.
751      */
752     private static final int UNATTENDED_MANAGED_KIOSK_MS = 30000;
753 
754     /**
755      * Strings logged with {@link
756      * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB},
757      * {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB},
758      * {@link DevicePolicyEnums#SET_NETWORK_LOGGING_ENABLED} and
759      * {@link DevicePolicyEnums#RETRIEVE_NETWORK_LOGS}.
760      */
761     private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
762     private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
763 
764     /**
765      * For admin apps targeting R+, throw when the app sets password requirement
766      * that is not taken into account at given quality. For example when quality is set
767      * to {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, it doesn't
768      * make sense to require certain password length. If the intent is to require a password of
769      * certain length having at least NUMERIC quality, the admin should first call
770      * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} and only then call
771      * {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLength}.
772      *
773      * <p>Conversely when an admin app targeting R+ lowers password quality, those
774      * requirements that stop making sense are reset to default values.
775      */
776     @ChangeId
777     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
778     private static final long ADMIN_APP_PASSWORD_COMPLEXITY = 123562444L;
779 
780     /**
781      * Admin apps targeting Android R+ may not use
782      * {@link android.app.admin.DevicePolicyManager#setSecureSetting} to change the deprecated
783      * {@link android.provider.Settings.Secure#LOCATION_MODE} setting. Instead they should use
784      * {@link android.app.admin.DevicePolicyManager#setLocationEnabled}.
785      */
786     @ChangeId
787     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
788     private static final long USE_SET_LOCATION_ENABLED = 117835097L;
789 
790     /**
791      * Forces wipeDataNoLock to attempt removing the user or throw an error as
792      * opposed to trying to factory reset the device first and only then falling back to user
793      * removal.
794      */
795     @ChangeId
796     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
797     public static final long EXPLICIT_WIPE_BEHAVIOUR = 242193913L;
798 
799     /**
800      * Apps targetting U+ should now expect that attempts to grant sensor permissions without
801      * authorisation will result in a security exception.
802      */
803     @ChangeId
804     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
805     public static final long THROW_SECURITY_EXCEPTION_FOR_SENSOR_PERMISSIONS = 277035314L;
806 
807     // Only add to the end of the list. Do not change or rearrange these values, that will break
808     // historical data. Do not use negative numbers or zero, logger only handles positive
809     // integers.
810     private static final int COPY_ACCOUNT_SUCCEEDED = 1;
811     private static final int COPY_ACCOUNT_FAILED = 2;
812     private static final int COPY_ACCOUNT_TIMED_OUT = 3;
813     private static final int COPY_ACCOUNT_EXCEPTION = 4;
814 
815     @IntDef({
816             COPY_ACCOUNT_SUCCEEDED,
817             COPY_ACCOUNT_FAILED,
818             COPY_ACCOUNT_TIMED_OUT,
819             COPY_ACCOUNT_EXCEPTION})
820     private @interface CopyAccountStatus {}
821 
822     /**
823      * Mapping of {@link android.app.admin.DevicePolicyManager.ApplicationExemptionConstants} to
824      * corresponding app-ops.
825      */
826     private static final Map<Integer, String> APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS =
827             new ArrayMap<>();
828     static {
APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put( EXEMPT_FROM_SUSPENSION, OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION)829         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
830                 EXEMPT_FROM_SUSPENSION, OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION);
APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put( EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS, OPSTR_SYSTEM_EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS)831         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
832                 EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS,
833                 OPSTR_SYSTEM_EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS);
APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put( EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION, OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION)834         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
835                 EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION,
836                 OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION);
APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put( EXEMPT_FROM_HIBERNATION, OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION)837         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
838                 EXEMPT_FROM_HIBERNATION, OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION);
APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put( EXEMPT_FROM_POWER_RESTRICTIONS, OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS)839         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
840                 EXEMPT_FROM_POWER_RESTRICTIONS, OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS);
841     }
842 
843     /**
844      * Admin apps targeting Android S+ may not use
845      * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} to set password quality
846      * on the {@code DevicePolicyManager} instance obtained by calling
847      * {@link android.app.admin.DevicePolicyManager#getParentProfileInstance}.
848      * Instead, they should use
849      * {@link android.app.admin.DevicePolicyManager#setRequiredPasswordComplexity} to set
850      * coarse-grained password requirements device-wide.
851      */
852     @ChangeId
853     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S)
854     private static final long PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT = 165573442L;
855 
856     /**
857      * For Admin Apps targeting U+
858      * If {@link android.security.IKeyChainService#setGrant} is called with an alias with no
859      * existing key, throw IllegalArgumentException.
860      */
861     @ChangeId
862     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
863     private static final long THROW_EXCEPTION_WHEN_KEY_MISSING = 175101461L;
864 
865     private static final String CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG =
866             "The alias provided must be contained in the aliases specified in the credential "
867                     + "management app's authentication policy";
868     private static final String NOT_SYSTEM_CALLER_MSG = "Only the system can %s";
869 
870     private static final String PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG =
871             "enable_permission_based_access";
872     private static final boolean DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG = false;
873 
874     private static final String ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG =
875             "enable_device_policy_engine";
876     private static final boolean DEFAULT_ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG = true;
877 
878     // TODO(b/265683382) remove the flag after rollout.
879     public static final boolean DEFAULT_KEEP_PROFILES_RUNNING_FLAG = false;
880 
881     // TODO(b/261999445) remove the flag after rollout.
882     private static final String HEADLESS_FLAG = "headless";
883     private static final boolean DEFAULT_HEADLESS_FLAG = true;
884 
885     // TODO(b/266831522) remove the flag after rollout.
886     private static final String APPLICATION_EXEMPTIONS_FLAG = "application_exemptions";
887     private static final boolean DEFAULT_APPLICATION_EXEMPTIONS_FLAG = true;
888 
889     /**
890      * For apps targeting U+
891      * Enable multiple admins to coexist on the same device.
892      */
893     @ChangeId
894     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
895     static final long ENABLE_COEXISTENCE_CHANGE = 260560985L;
896 
897     final Context mContext;
898     final Injector mInjector;
899     final PolicyPathProvider mPathProvider;
900     final IPackageManager mIPackageManager;
901     final IPermissionManager mIPermissionManager;
902     final UserManager mUserManager;
903     final UserManagerInternal mUserManagerInternal;
904     final UsageStatsManagerInternal mUsageStatsManagerInternal;
905     final TelephonyManager mTelephonyManager;
906     final RoleManager mRoleManager;
907     private final LockPatternUtils mLockPatternUtils;
908     private final LockSettingsInternal mLockSettingsInternal;
909     private final DeviceAdminServiceController mDeviceAdminServiceController;
910     private final OverlayPackagesProvider mOverlayPackagesProvider;
911 
912     private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl();
913     private final DeviceStateCacheImpl mStateCache = new DeviceStateCacheImpl();
914     private final Object mESIDInitilizationLock = new Object();
915     private EnterpriseSpecificIdCalculator mEsidCalculator;
916     private final Object mSubscriptionsChangedListenerLock = new Object();
917     @GuardedBy("mSubscriptionsChangedListenerLock")
918     private SubscriptionManager.OnSubscriptionsChangedListener mSubscriptionsChangedListener;
919 
920     /**
921      * Contains the list of OEM Default Role Holders for Contact-related roles
922      * (DIALER, SMS, SYSTEM_CONTACTS)
923      */
924     private final Set<String> mContactSystemRoleHolders;
925 
926     /**
927      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
928      * is requested for user u.
929      */
930     private final Set<UserPackage> mPackagesToRemove = new ArraySet<>();
931 
932     final LocalService mLocalService;
933 
934     // Stores and loads state on device and profile owners.
935     @VisibleForTesting
936     final Owners mOwners;
937 
938     private final Binder mToken = new Binder();
939 
940     /**
941      * Whether or not device admin feature is supported. If it isn't return defaults for all
942      * public methods, unless the caller has the appropriate permission for a particular method.
943      */
944     final boolean mHasFeature;
945 
946     /**
947      * Whether or not this device is a watch.
948      */
949     final boolean mIsWatch;
950 
951     /**
952      * Whether or not this device is an automotive.
953      */
954     private final boolean mIsAutomotive;
955 
956     /**
957      * Whether this device has the telephony feature.
958      */
959     final boolean mHasTelephonyFeature;
960 
961     private final CertificateMonitor mCertificateMonitor;
962     private final SecurityLogMonitor mSecurityLogMonitor;
963     private final RemoteBugreportManager mBugreportCollectionManager;
964 
965     @GuardedBy("getLockObject()")
966     private NetworkLogger mNetworkLogger;
967 
968     private final SetupContentObserver mSetupContentObserver;
969     private final DevicePolicyConstantsObserver mConstantsObserver;
970 
971     private DevicePolicyConstants mConstants;
972 
973     /**
974      * User to be switched to on {@code logoutUser()}.
975      *
976      * <p>Only used on devices with headless system user mode
977      */
978     @GuardedBy("getLockObject()")
979     private @UserIdInt int mLogoutUserId = UserHandle.USER_NULL;
980 
981     /**
982      * User the network logging notification was sent to.
983      */
984     // Guarded by mHandler
985     private @UserIdInt int mNetworkLoggingNotificationUserId = UserHandle.USER_NULL;
986 
987     private final DeviceManagementResourcesProvider mDeviceManagementResourcesProvider;
988     private final DevicePolicyManagementRoleObserver mDevicePolicyManagementRoleObserver;
989 
990     private final DevicePolicyEngine mDevicePolicyEngine;
991 
992     private static final boolean ENABLE_LOCK_GUARD = true;
993 
994     /**
995      * Profile off deadline is not set or more than MANAGED_PROFILE_OFF_WARNING_PERIOD away, or the
996      * user is running unlocked, no need for notification.
997      */
998     private static final int PROFILE_OFF_NOTIFICATION_NONE = 0;
999     /**
1000      * Profile off deadline is closer than MANAGED_PROFILE_OFF_WARNING_PERIOD.
1001      */
1002     private static final int PROFILE_OFF_NOTIFICATION_WARNING = 1;
1003     /**
1004      * Profile off deadline reached, notify the user that personal apps blocked.
1005      */
1006     private static final int PROFILE_OFF_NOTIFICATION_SUSPENDED = 2;
1007 
1008     interface Stats {
1009         int LOCK_GUARD_GUARD = 0;
1010 
1011         int COUNT = LOCK_GUARD_GUARD + 1;
1012     }
1013 
1014     private final StatLogger mStatLogger = new StatLogger(new String[] {
1015             "LockGuard.guard()",
1016     });
1017 
1018     private final Object mLockDoNoUseDirectly = LockGuard.installNewLock(
1019             LockGuard.INDEX_DPMS, /* doWtf=*/ true);
1020 
getLockObject()1021     final Object getLockObject() {
1022         if (ENABLE_LOCK_GUARD) {
1023             final long start = mStatLogger.getTime();
1024             LockGuard.guard(LockGuard.INDEX_DPMS);
1025             mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start);
1026         }
1027         return mLockDoNoUseDirectly;
1028     }
1029 
1030     /**
1031      * Check if the current thread holds the DPMS lock, and if not, do a WTF.
1032      *
1033      * (Doing this check too much may be costly, so don't call it in a hot path.)
1034      */
ensureLocked()1035     final void ensureLocked() {
1036         if (Thread.holdsLock(mLockDoNoUseDirectly)) {
1037             return;
1038         }
1039         Slogf.wtfStack(LOG_TAG, "Not holding DPMS lock.");
1040     }
1041 
1042     /**
1043      * Calls wtfStack() if called with the DPMS lock held.
1044      */
wtfIfInLock()1045     private void wtfIfInLock() {
1046         if (Thread.holdsLock(mLockDoNoUseDirectly)) {
1047             Slogf.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
1048         }
1049     }
1050 
1051     @VisibleForTesting
1052     final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager;
1053 
1054     @Nullable
1055     private DevicePolicySafetyChecker mSafetyChecker;
1056 
1057     @GuardedBy("getLockObject()")
1058     private final ArrayList<Object> mPendingUserCreatedCallbackTokens = new ArrayList<>();
1059 
1060     public static final class Lifecycle extends SystemService {
1061         private DevicePolicyManagerService mService;
1062 
Lifecycle(Context context)1063         public Lifecycle(Context context) {
1064             super(context);
1065             String dpmsClassName = context.getResources()
1066                     .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
1067             if (TextUtils.isEmpty(dpmsClassName)) {
1068                 mService = new DevicePolicyManagerService(context);
1069             } else {
1070                 try {
1071                     Class<?> serviceClass = Class.forName(dpmsClassName);
1072                     Constructor<?> constructor = serviceClass.getConstructor(Context.class);
1073                     mService = (DevicePolicyManagerService) constructor.newInstance(context);
1074                 } catch (Exception e) {
1075                     throw new IllegalStateException(
1076                         "Failed to instantiate DevicePolicyManagerService with class name: "
1077                         + dpmsClassName, e);
1078                 }
1079             }
1080         }
1081 
1082         /** Sets the {@link DevicePolicySafetyChecker}. */
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1083         public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
1084             mService.setDevicePolicySafetyChecker(safetyChecker);
1085         }
1086 
1087         @Override
onStart()1088         public void onStart() {
1089             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
1090         }
1091 
1092         @Override
onBootPhase(int phase)1093         public void onBootPhase(int phase) {
1094             mService.systemReady(phase);
1095         }
1096 
1097         @Override
onUserStarting(@onNull TargetUser user)1098         public void onUserStarting(@NonNull TargetUser user) {
1099             if (user.isPreCreated()) return;
1100             mService.handleStartUser(user.getUserIdentifier());
1101         }
1102 
1103         @Override
onUserUnlocking(@onNull TargetUser user)1104         public void onUserUnlocking(@NonNull TargetUser user) {
1105             if (user.isPreCreated()) return;
1106             mService.handleUnlockUser(user.getUserIdentifier());
1107         }
1108 
1109         @Override
onUserStopping(@onNull TargetUser user)1110         public void onUserStopping(@NonNull TargetUser user) {
1111             if (user.isPreCreated()) return;
1112             mService.handleStopUser(user.getUserIdentifier());
1113         }
1114 
1115         @Override
onUserUnlocked(@onNull TargetUser user)1116         public void onUserUnlocked(@NonNull TargetUser user) {
1117             if (user.isPreCreated()) return;
1118             mService.handleOnUserUnlocked(user.getUserIdentifier());
1119         }
1120     }
1121 
1122     @GuardedBy("getLockObject()")
1123     final SparseArray<DevicePolicyData> mUserData;
1124 
1125     final Handler mHandler;
1126     final Handler mBackgroundHandler;
1127 
1128     /** Listens only if mHasFeature == true. */
1129     final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1130         @Override
1131         public void onReceive(Context context, Intent intent) {
1132             final String action = intent.getAction();
1133             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
1134                     getSendingUserId());
1135 
1136             /*
1137              * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
1138              * however it's too early in the boot process to register with IIpConnectivityMetrics
1139              * to listen for events.
1140              */
1141             if (Intent.ACTION_USER_STARTED.equals(action) && userHandle == UserHandle.USER_SYSTEM) {
1142                 synchronized (getLockObject()) {
1143                     if (isNetworkLoggingEnabledInternalLocked()) {
1144                         setNetworkLoggingActiveInternal(true);
1145                     }
1146                 }
1147             }
1148 
1149             if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
1150                 calculateHasIncompatibleAccounts();
1151             }
1152 
1153             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
1154                     && userHandle == mOwners.getDeviceOwnerUserId()) {
1155                 mBugreportCollectionManager.checkForPendingBugreportAfterBoot();
1156 
1157             }
1158             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
1159                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
1160                 if (VERBOSE_LOG) {
1161                     Slogf.v(LOG_TAG, "Sending password expiration notifications for action "
1162                             + action + " for user " + userHandle);
1163                 }
1164                 mHandler.post(new Runnable() {
1165                     @Override
1166                     public void run() {
1167                         handlePasswordExpirationNotification(userHandle);
1168                     }
1169                 });
1170             }
1171 
1172             if (Intent.ACTION_USER_ADDED.equals(action)) {
1173                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
1174                 synchronized (getLockObject()) {
1175                     // It might take a while for the user to become affiliated. Make security
1176                     // and network logging unavailable in the meantime.
1177                     maybePauseDeviceWideLoggingLocked();
1178                 }
1179             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
1180                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
1181                 synchronized (getLockObject()) {
1182                     // Check whether the user is affiliated, *before* removing its data.
1183                     boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
1184                     removeUserData(userHandle);
1185                     if (!isRemovedUserAffiliated) {
1186                         // We discard the logs when unaffiliated users are deleted (so that the
1187                         // device owner cannot retrieve data about that user after it's gone).
1188                         discardDeviceWideLogsLocked();
1189                         // Resume logging if all remaining users are affiliated.
1190                         maybeResumeDeviceWideLoggingLocked();
1191                     }
1192                 }
1193                 if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
1194                     mDevicePolicyEngine.handleUserRemoved(userHandle);
1195                 }
1196             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
1197                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle);
1198                 synchronized (getLockObject()) {
1199                     maybeSendAdminEnabledBroadcastLocked(userHandle);
1200                     // Reset the policy data
1201                     mUserData.remove(userHandle);
1202                 }
1203                 handlePackagesChanged(null /* check all admins */, userHandle);
1204                 updatePersonalAppsSuspensionOnUserStart(userHandle);
1205             } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1206                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle);
1207                 if (isManagedProfile(userHandle)) {
1208                     Slogf.d(LOG_TAG, "Managed profile was stopped");
1209                     updatePersonalAppsSuspension(userHandle);
1210                 }
1211             } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
1212                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle);
1213             } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
1214                 synchronized (getLockObject()) {
1215                     maybeSendAdminEnabledBroadcastLocked(userHandle);
1216                 }
1217                 if (isManagedProfile(userHandle)) {
1218                     Slogf.d(LOG_TAG, "Managed profile became unlocked");
1219                     final boolean suspended = updatePersonalAppsSuspension(userHandle);
1220                     triggerPolicyComplianceCheckIfNeeded(userHandle, suspended);
1221                 }
1222             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1223                 handlePackagesChanged(null /* check all admins */, userHandle);
1224             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1225                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
1226             } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1227                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1228                     handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
1229                 } else {
1230                     handleNewPackageInstalled(intent.getData().getSchemeSpecificPart(), userHandle);
1231                 }
1232             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1233                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1234                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
1235                 removeCredentialManagementApp(intent.getData().getSchemeSpecificPart());
1236             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
1237                 clearWipeProfileNotification();
1238             } else if (Intent.ACTION_DATE_CHANGED.equals(action)
1239                     || Intent.ACTION_TIME_CHANGED.equals(action)) {
1240                 // Update freeze period record when clock naturally progresses to the next day
1241                 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made
1242                 // (ACTION_TIME_CHANGED)
1243                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
1244                 final int userId = getManagedUserId(getMainUserId());
1245                 if (userId >= 0) {
1246                     updatePersonalAppsSuspension(userId);
1247                 }
1248             } else if (ACTION_PROFILE_OFF_DEADLINE.equals(action)) {
1249                 Slogf.i(LOG_TAG, "Profile off deadline alarm was triggered");
1250                 final int userId = getManagedUserId(getMainUserId());
1251                 if (userId >= 0) {
1252                     updatePersonalAppsSuspension(userId);
1253                 } else {
1254                     Slogf.wtf(LOG_TAG, "Got deadline alarm for nonexistent profile");
1255                 }
1256             } else if (ACTION_TURN_PROFILE_ON_NOTIFICATION.equals(action)) {
1257                 Slogf.i(LOG_TAG, "requesting to turn on the profile: " + userHandle);
1258                 mUserManager.requestQuietModeEnabled(false, UserHandle.of(userHandle));
1259             } else if (ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action)) {
1260                 notifyIfManagedSubscriptionsAreUnavailable(
1261                         UserHandle.of(userHandle), /* managedProfileAvailable= */ false);
1262                 updatePersonalAppsSuspension(userHandle);
1263             } else if (ACTION_MANAGED_PROFILE_AVAILABLE.equals(action)) {
1264                 notifyIfManagedSubscriptionsAreUnavailable(
1265                         UserHandle.of(userHandle), /* managedProfileAvailable= */ true);
1266                 final boolean suspended = updatePersonalAppsSuspension(userHandle);
1267                 triggerPolicyComplianceCheckIfNeeded(userHandle, suspended);
1268             } else if (LOGIN_ACCOUNTS_CHANGED_ACTION.equals(action)) {
1269                 calculateHasIncompatibleAccounts();
1270             }
1271         }
1272 
1273         private void sendDeviceOwnerUserCommand(String action, int userHandle) {
1274             synchronized (getLockObject()) {
1275                 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
1276                 if (deviceOwner != null) {
1277                     Bundle extras = new Bundle();
1278                     extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
1279                     sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null,
1280                             /* inForeground */ true);
1281                 }
1282             }
1283         }
1284     };
1285 
1286     protected static class RestrictionsListener implements UserRestrictionsListener {
1287         private final Context mContext;
1288         private final UserManagerInternal mUserManagerInternal;
1289         private final DevicePolicyManagerService mDpms;
1290 
RestrictionsListener( Context context, UserManagerInternal userManagerInternal, DevicePolicyManagerService dpms)1291         public RestrictionsListener(
1292                 Context context,
1293                 UserManagerInternal userManagerInternal,
1294                 DevicePolicyManagerService dpms) {
1295             mContext = context;
1296             mUserManagerInternal = userManagerInternal;
1297             mDpms = dpms;
1298         }
1299 
1300         @Override
onUserRestrictionsChanged(int userId, Bundle newRestrictions, Bundle prevRestrictions)1301         public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
1302                 Bundle prevRestrictions) {
1303             resetCrossProfileIntentFiltersIfNeeded(userId, newRestrictions, prevRestrictions);
1304             resetUserVpnIfNeeded(userId, newRestrictions, prevRestrictions);
1305         }
1306 
resetUserVpnIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1307         private void resetUserVpnIfNeeded(
1308                 int userId, Bundle newRestrictions, Bundle prevRestrictions) {
1309             final boolean newlyEnforced =
1310                     !prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN)
1311                     && newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN);
1312             if (newlyEnforced) {
1313                 mDpms.clearUserConfiguredVpns(userId);
1314             }
1315         }
1316 
resetCrossProfileIntentFiltersIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1317         private void resetCrossProfileIntentFiltersIfNeeded(
1318                 int userId, Bundle newRestrictions, Bundle prevRestrictions) {
1319             if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions,
1320                     UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE)) {
1321                 final int parentId = mUserManagerInternal.getProfileParentId(userId);
1322                 if (parentId == userId) {
1323                     return;
1324                 }
1325 
1326                 // Always reset filters on the parent user, which handles cross profile intent
1327                 // filters between the parent and its profiles.
1328                 Slogf.i(LOG_TAG, "Resetting cross-profile intent filters on restriction "
1329                         + "change");
1330                 mDpms.resetDefaultCrossProfileIntentFilters(parentId);
1331                 mContext.sendBroadcastAsUser(
1332                         new Intent(DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_APPLIED),
1333                         UserHandle.of(userId));
1334             }
1335         }
1336     }
1337 
clearUserConfiguredVpns(int userId)1338     private void clearUserConfiguredVpns(int userId) {
1339         final String adminConfiguredVpnPkg;
1340         synchronized (getLockObject()) {
1341             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
1342             if (owner == null) {
1343                 Slogf.wtf(LOG_TAG, "Admin not found");
1344                 return;
1345             }
1346             adminConfiguredVpnPkg = owner.mAlwaysOnVpnPackage;
1347         }
1348 
1349         // Clear always-on configuration if it wasn't set by the admin.
1350         if (adminConfiguredVpnPkg == null) {
1351             mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(userId, null, false, null);
1352         }
1353 
1354         // Clear app authorizations to establish VPNs. When DISALLOW_CONFIG_VPN is enforced apps
1355         // won't be able to get those authorizations unless it is configured by an admin.
1356         final List<AppOpsManager.PackageOps> allVpnOps = mInjector.getAppOpsManager()
1357                 .getPackagesForOps(new int[] {AppOpsManager.OP_ACTIVATE_VPN});
1358         if (allVpnOps == null) {
1359             return;
1360         }
1361         for (AppOpsManager.PackageOps pkgOps : allVpnOps) {
1362             if (UserHandle.getUserId(pkgOps.getUid()) != userId
1363                     || pkgOps.getPackageName().equals(adminConfiguredVpnPkg)) {
1364                 continue;
1365             }
1366             if (pkgOps.getOps().size() != 1) {
1367                 Slogf.wtf(LOG_TAG, "Unexpected number of ops returned");
1368                 continue;
1369             }
1370             final @Mode int mode = pkgOps.getOps().get(0).getMode();
1371             if (mode == MODE_ALLOWED) {
1372                 Slogf.i(LOG_TAG, String.format("Revoking VPN authorization for package %s uid %d",
1373                         pkgOps.getPackageName(), pkgOps.getUid()));
1374                 mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN, pkgOps.getUid(),
1375                         pkgOps.getPackageName(), MODE_DEFAULT);
1376             }
1377         }
1378     }
1379 
1380     private final class UserLifecycleListener implements UserManagerInternal.UserLifecycleListener {
1381 
1382         @Override
onUserCreated(UserInfo user, Object token)1383         public void onUserCreated(UserInfo user, Object token) {
1384             mHandler.post(() -> handleNewUserCreated(user, token));
1385         }
1386     }
1387 
handlePackagesChanged(@ullable String packageName, int userHandle)1388     private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1389         boolean removedAdmin = false;
1390         String removedAdminPackage = null;
1391         if (VERBOSE_LOG) {
1392             Slogf.d(LOG_TAG, "Handling package changes package " + packageName
1393                     + " for user " + userHandle);
1394         }
1395         DevicePolicyData policy = getUserData(userHandle);
1396         synchronized (getLockObject()) {
1397             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1398                 ActiveAdmin aa = policy.mAdminList.get(i);
1399                 try {
1400                     // If we're checking all packages or if the specific one we're checking matches,
1401                     // then check if the package and receiver still exist.
1402                     final String adminPackage = aa.info.getPackageName();
1403                     if (packageName == null || packageName.equals(adminPackage)) {
1404                         if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1405                                 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1406                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
1407                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1408                                 userHandle) == null) {
1409                             Slogf.e(LOG_TAG, String.format(
1410                                     "Admin package %s not found for user %d, removing active admin",
1411                                     packageName, userHandle));
1412                             removedAdmin = true;
1413                             removedAdminPackage = adminPackage;
1414                             policy.mAdminList.remove(i);
1415                             policy.mAdminMap.remove(aa.info.getComponent());
1416                             pushActiveAdminPackagesLocked(userHandle);
1417                             pushMeteredDisabledPackages(userHandle);
1418                         }
1419                     }
1420                 } catch (RemoteException re) {
1421                     // Shouldn't happen.
1422                     Slogf.wtf(LOG_TAG, "Error handling package changes", re);
1423                 }
1424             }
1425             if (removedAdmin) {
1426                 policy.validatePasswordOwner();
1427             }
1428 
1429             boolean removedDelegate = false;
1430 
1431             // Check if a delegate was removed.
1432             for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1433                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
1434                 if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1435                     policy.mDelegationMap.removeAt(i);
1436                     removedDelegate = true;
1437                 }
1438             }
1439 
1440             // If it's an owner package, we may need to refresh the bound connection.
1441             final ComponentName owner = getOwnerComponent(userHandle);
1442             if ((packageName != null) && (owner != null)
1443                     && (owner.getPackageName().equals(packageName))) {
1444                 startOwnerService(userHandle, "package-broadcast");
1445             }
1446             if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
1447                 mDevicePolicyEngine.handlePackageChanged(
1448                         packageName, userHandle, removedAdminPackage);
1449             }
1450             // Persist updates if the removed package was an admin or delegate.
1451             if (removedAdmin || removedDelegate) {
1452                 saveSettingsLocked(policy.mUserId);
1453             }
1454         }
1455         if (removedAdmin) {
1456             // The removed admin might have disabled camera, so update user restrictions.
1457             pushUserRestrictions(userHandle);
1458         }
1459     }
1460 
removeCredentialManagementApp(String packageName)1461     private void removeCredentialManagementApp(String packageName) {
1462         mBackgroundHandler.post(() -> {
1463             try (KeyChainConnection connection = mInjector.keyChainBind()) {
1464                 IKeyChainService service = connection.getService();
1465                 if (service.hasCredentialManagementApp()
1466                         && packageName.equals(service.getCredentialManagementAppPackageName())) {
1467                     service.removeCredentialManagementApp();
1468                 }
1469             } catch (RemoteException | InterruptedException | IllegalStateException
1470                     | AssertionError e) {
1471                 Slogf.e(LOG_TAG, "Unable to remove the credential management app", e);
1472             }
1473         });
1474     }
1475 
isRemovedPackage(String changedPackage, String targetPackage, int userHandle)1476     private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1477         try {
1478             return targetPackage != null
1479                     && (changedPackage == null || changedPackage.equals(targetPackage))
1480                     && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1481         } catch (RemoteException e) {
1482             // Shouldn't happen
1483             Slogf.wtf(LOG_TAG, "Error checking isRemovedPackage", e);
1484         }
1485 
1486         return false;
1487     }
1488 
handleNewPackageInstalled(String packageName, int userHandle)1489     private void handleNewPackageInstalled(String packageName, int userHandle) {
1490         // If personal apps were suspended by the admin, suspend the newly installed one.
1491         if (!getUserData(userHandle).mAppsSuspended) {
1492             return;
1493         }
1494         final String[] packagesToSuspend = { packageName };
1495         // Check if package is considered not suspendable?
1496         if (mInjector.getPackageManager(userHandle)
1497                 .getUnsuspendablePackages(packagesToSuspend).length != 0) {
1498             Slogf.i(LOG_TAG, "Newly installed package is unsuspendable: " + packageName);
1499             return;
1500         }
1501         mInjector.getPackageManagerInternal()
1502                 .setPackagesSuspendedByAdmin(userHandle, packagesToSuspend, true /*suspend*/);
1503     }
1504 
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1505     public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
1506         CallerIdentity callerIdentity = getCallerIdentity();
1507         Preconditions.checkCallAuthorization(mIsAutomotive || isAdb(callerIdentity), "can only set "
1508                 + "DevicePolicySafetyChecker on automotive builds or from ADB (but caller is %s)",
1509                 callerIdentity);
1510         setDevicePolicySafetyCheckerUnchecked(safetyChecker);
1511     }
1512 
1513     /**
1514      * Used by {@code setDevicePolicySafetyChecker()} above and {@link OneTimeSafetyChecker}.
1515      */
setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker)1516     void setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker) {
1517         Slogf.i(LOG_TAG, "Setting DevicePolicySafetyChecker as %s", safetyChecker);
1518         mSafetyChecker = safetyChecker;
1519         mInjector.setDevicePolicySafetyChecker(safetyChecker);
1520     }
1521 
1522     /**
1523      * Used by {@link OneTimeSafetyChecker} only.
1524      */
getDevicePolicySafetyChecker()1525     DevicePolicySafetyChecker getDevicePolicySafetyChecker() {
1526         return mSafetyChecker;
1527     }
1528 
1529     /**
1530      * Checks if it's safe to execute the given {@code operation}.
1531      *
1532      * @throws UnsafeStateException if it's not safe to execute the operation.
1533      */
checkCanExecuteOrThrowUnsafe(@evicePolicyOperation int operation)1534     private void checkCanExecuteOrThrowUnsafe(@DevicePolicyOperation int operation) {
1535         int reason = getUnsafeOperationReason(operation);
1536         if (reason == OPERATION_SAFETY_REASON_NONE) return;
1537 
1538         if (mSafetyChecker == null) {
1539             // Happens on CTS after it's set just once (by OneTimeSafetyChecker)
1540             throw new UnsafeStateException(operation, reason);
1541         }
1542         // Let mSafetyChecker customize it (for example, by explaining how to retry)
1543         throw mSafetyChecker.newUnsafeStateException(operation, reason);
1544     }
1545 
1546     /**
1547      * Returns whether it's safe to execute the given {@code operation}, and why.
1548      */
1549     @OperationSafetyReason
getUnsafeOperationReason(@evicePolicyOperation int operation)1550     int getUnsafeOperationReason(@DevicePolicyOperation int operation) {
1551         return mSafetyChecker == null ? OPERATION_SAFETY_REASON_NONE
1552                 : mSafetyChecker.getUnsafeOperationReason(operation);
1553     }
1554 
1555     @Override
setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)1556     public void setNextOperationSafety(@DevicePolicyOperation int operation,
1557             @OperationSafetyReason int reason) {
1558         Preconditions.checkCallAuthorization(
1559                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
1560         Slogf.i(LOG_TAG, "setNextOperationSafety(%s, %s)",
1561                 DevicePolicyManager.operationToString(operation),
1562                 DevicePolicyManager.operationSafetyReasonToString(reason));
1563         mSafetyChecker = new OneTimeSafetyChecker(this, operation, reason);
1564     }
1565 
1566     @Override
isSafeOperation(@perationSafetyReason int reason)1567     public boolean isSafeOperation(@OperationSafetyReason int reason) {
1568         if (VERBOSE_LOG) {
1569             Slogf.v(LOG_TAG, "checking isSafeOperation(%s) using mSafetyChecker %s",
1570                     DevicePolicyManager.operationSafetyReasonToString(reason), mSafetyChecker);
1571         }
1572         return mSafetyChecker == null ? true : mSafetyChecker.isSafeOperation(reason);
1573     }
1574 
1575     // Used by DevicePolicyManagerServiceShellCommand
listAllOwners()1576     List<OwnerShellData> listAllOwners() {
1577         Preconditions.checkCallAuthorization(
1578                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
1579         return mInjector.binderWithCleanCallingIdentity(() -> {
1580             SparseArray<DevicePolicyData> userData;
1581 
1582             // Gets the owners of "full users" first (device owner and profile owners)
1583             List<OwnerShellData> owners = mOwners.listAllOwners();
1584             synchronized (getLockObject()) {
1585                 for (int i = 0; i < owners.size(); i++) {
1586                     OwnerShellData owner = owners.get(i);
1587                     owner.isAffiliated = isUserAffiliatedWithDeviceLocked(owner.userId);
1588                 }
1589                 userData = mUserData;
1590             }
1591 
1592             // Then the owners of profile users (managed profiles)
1593             for (int i = 0; i < userData.size(); i++) {
1594                 DevicePolicyData policyData = mUserData.valueAt(i);
1595                 int userId = userData.keyAt(i);
1596                 int parentUserId = mUserManagerInternal.getProfileParentId(userId);
1597                 boolean isProfile = parentUserId != userId;
1598                 if (!isProfile) continue;
1599                 for (int j = 0; j < policyData.mAdminList.size(); j++) {
1600                     ActiveAdmin admin = policyData.mAdminList.get(j);
1601                     OwnerShellData owner = OwnerShellData.forManagedProfileOwner(userId,
1602                             parentUserId, admin.info.getComponent());
1603                     owners.add(owner);
1604                 }
1605             }
1606 
1607             return owners;
1608         });
1609     }
1610 
1611     /**
1612      * Unit test will subclass it to inject mocks.
1613      */
1614     @VisibleForTesting
1615     static class Injector {
1616 
1617         public final Context mContext;
1618 
1619         @Nullable private DevicePolicySafetyChecker mSafetyChecker;
1620 
Injector(Context context)1621         Injector(Context context) {
1622             mContext = context;
1623         }
1624 
hasFeature()1625         public boolean hasFeature() {
1626             return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1627         }
1628 
createContextAsUser(UserHandle user)1629         Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1630             final String packageName = mContext.getPackageName();
1631             return mContext.createPackageContextAsUser(packageName, 0, user);
1632         }
1633 
getResources()1634         Resources getResources() {
1635             return mContext.getResources();
1636         }
1637 
getUserManager()1638         UserManager getUserManager() {
1639             return UserManager.get(mContext);
1640         }
1641 
getUserManagerInternal()1642         UserManagerInternal getUserManagerInternal() {
1643             return LocalServices.getService(UserManagerInternal.class);
1644         }
1645 
getPackageManagerInternal()1646         PackageManagerInternal getPackageManagerInternal() {
1647             return LocalServices.getService(PackageManagerInternal.class);
1648         }
1649 
getPackageManagerLocal()1650         PackageManagerLocal getPackageManagerLocal() {
1651             return LocalManagerRegistry.getManager(PackageManagerLocal.class);
1652         }
1653 
getActivityTaskManagerInternal()1654         ActivityTaskManagerInternal getActivityTaskManagerInternal() {
1655             return LocalServices.getService(ActivityTaskManagerInternal.class);
1656         }
1657 
getPermissionControllerManager( @onNull UserHandle user)1658         @NonNull PermissionControllerManager getPermissionControllerManager(
1659                 @NonNull UserHandle user) {
1660             if (user.equals(mContext.getUser())) {
1661                 return mContext.getSystemService(PermissionControllerManager.class);
1662             } else {
1663                 try {
1664                     return mContext.createPackageContextAsUser(mContext.getPackageName(), 0,
1665                             user).getSystemService(PermissionControllerManager.class);
1666                 } catch (NameNotFoundException notPossible) {
1667                     // not possible
1668                     throw new IllegalStateException(notPossible);
1669                 }
1670             }
1671         }
1672 
getUsageStatsManagerInternal()1673         UsageStatsManagerInternal getUsageStatsManagerInternal() {
1674             return LocalServices.getService(UsageStatsManagerInternal.class);
1675         }
1676 
getNetworkPolicyManagerInternal()1677         NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() {
1678             return LocalServices.getService(NetworkPolicyManagerInternal.class);
1679         }
1680 
getNotificationManager()1681         NotificationManager getNotificationManager() {
1682             return mContext.getSystemService(NotificationManager.class);
1683         }
1684 
getIIpConnectivityMetrics()1685         IIpConnectivityMetrics getIIpConnectivityMetrics() {
1686             return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1687                 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1688         }
1689 
getPackageManager()1690         PackageManager getPackageManager() {
1691             return mContext.getPackageManager();
1692         }
1693 
getPackageManager(int userId)1694         PackageManager getPackageManager(int userId) {
1695             try {
1696                 return createContextAsUser(UserHandle.of(userId)).getPackageManager();
1697             } catch (NameNotFoundException e) {
1698                 throw new IllegalStateException(e);
1699             }
1700         }
1701 
getPowerManagerInternal()1702         PowerManagerInternal getPowerManagerInternal() {
1703             return LocalServices.getService(PowerManagerInternal.class);
1704         }
1705 
getTelephonyManager()1706         TelephonyManager getTelephonyManager() {
1707             return mContext.getSystemService(TelephonyManager.class);
1708         }
1709 
getRoleManager()1710         RoleManager getRoleManager() {
1711             return mContext.getSystemService(RoleManager.class);
1712         }
1713 
getTrustManager()1714         TrustManager getTrustManager() {
1715             return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1716         }
1717 
getAlarmManager()1718         AlarmManager getAlarmManager() {
1719             return mContext.getSystemService(AlarmManager.class);
1720         }
1721 
getAlarmManagerInternal()1722         AlarmManagerInternal getAlarmManagerInternal() {
1723             return LocalServices.getService(AlarmManagerInternal.class);
1724         }
1725 
getConnectivityManager()1726         ConnectivityManager getConnectivityManager() {
1727             return mContext.getSystemService(ConnectivityManager.class);
1728         }
1729 
getVpnManager()1730         VpnManager getVpnManager() {
1731             return mContext.getSystemService(VpnManager.class);
1732         }
1733 
getLocationManager()1734         LocationManager getLocationManager() {
1735             return mContext.getSystemService(LocationManager.class);
1736         }
1737 
getIWindowManager()1738         IWindowManager getIWindowManager() {
1739             return IWindowManager.Stub
1740                     .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1741         }
1742 
getIActivityManager()1743         IActivityManager getIActivityManager() {
1744             return ActivityManager.getService();
1745         }
1746 
getIActivityTaskManager()1747         IActivityTaskManager getIActivityTaskManager() {
1748             return ActivityTaskManager.getService();
1749         }
1750 
getActivityManagerInternal()1751         ActivityManagerInternal getActivityManagerInternal() {
1752             return LocalServices.getService(ActivityManagerInternal.class);
1753         }
1754 
getIPackageManager()1755         IPackageManager getIPackageManager() {
1756             return AppGlobals.getPackageManager();
1757         }
1758 
getIPermissionManager()1759         IPermissionManager getIPermissionManager() {
1760             return AppGlobals.getPermissionManager();
1761         }
1762 
getIBackupManager()1763         IBackupManager getIBackupManager() {
1764             return IBackupManager.Stub.asInterface(
1765                     ServiceManager.getService(Context.BACKUP_SERVICE));
1766         }
1767 
getIAudioService()1768         IAudioService getIAudioService() {
1769             return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1770         }
1771 
getPersistentDataBlockManagerInternal()1772         PersistentDataBlockManagerInternal getPersistentDataBlockManagerInternal() {
1773             return LocalServices.getService(PersistentDataBlockManagerInternal.class);
1774         }
1775 
getAppOpsManager()1776         AppOpsManager getAppOpsManager() {
1777             return mContext.getSystemService(AppOpsManager.class);
1778         }
1779 
getLockSettingsInternal()1780         LockSettingsInternal getLockSettingsInternal() {
1781             return LocalServices.getService(LockSettingsInternal.class);
1782         }
1783 
getCrossProfileApps(@serIdInt int userId)1784         CrossProfileApps getCrossProfileApps(@UserIdInt int userId) {
1785             return mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0)
1786                     .getSystemService(CrossProfileApps.class);
1787         }
1788 
hasUserSetupCompleted(DevicePolicyData userData)1789         boolean hasUserSetupCompleted(DevicePolicyData userData) {
1790             return userData.mUserSetupComplete;
1791         }
1792 
isBuildDebuggable()1793         boolean isBuildDebuggable() {
1794             return Build.IS_DEBUGGABLE;
1795         }
1796 
newLockPatternUtils()1797         LockPatternUtils newLockPatternUtils() {
1798             return new LockPatternUtils(mContext);
1799         }
1800 
newEnterpriseSpecificIdCalculator()1801         EnterpriseSpecificIdCalculator newEnterpriseSpecificIdCalculator() {
1802             return new EnterpriseSpecificIdCalculator(mContext);
1803         }
1804 
storageManagerIsFileBasedEncryptionEnabled()1805         boolean storageManagerIsFileBasedEncryptionEnabled() {
1806             return StorageManager.isFileEncrypted();
1807         }
1808 
getMyLooper()1809         Looper getMyLooper() {
1810             return Looper.myLooper();
1811         }
1812 
getWifiManager()1813         WifiManager getWifiManager() {
1814             return mContext.getSystemService(WifiManager.class);
1815         }
1816 
getUsbManager()1817         UsbManager getUsbManager() {
1818             return mContext.getSystemService(UsbManager.class);
1819         }
1820 
1821         @SuppressWarnings("ResultOfClearIdentityCallNotStoredInVariable")
binderClearCallingIdentity()1822         long binderClearCallingIdentity() {
1823             return Binder.clearCallingIdentity();
1824         }
1825 
binderRestoreCallingIdentity(long token)1826         void binderRestoreCallingIdentity(long token) {
1827             Binder.restoreCallingIdentity(token);
1828         }
1829 
binderGetCallingUid()1830         int binderGetCallingUid() {
1831             return Binder.getCallingUid();
1832         }
1833 
binderGetCallingPid()1834         int binderGetCallingPid() {
1835             return Binder.getCallingPid();
1836         }
1837 
binderGetCallingUserHandle()1838         UserHandle binderGetCallingUserHandle() {
1839             return Binder.getCallingUserHandle();
1840         }
1841 
binderIsCallingUidMyUid()1842         boolean binderIsCallingUidMyUid() {
1843             return getCallingUid() == Process.myUid();
1844         }
1845 
binderWithCleanCallingIdentity(@onNull ThrowingRunnable action)1846         void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
1847              Binder.withCleanCallingIdentity(action);
1848         }
1849 
binderWithCleanCallingIdentity(@onNull ThrowingSupplier<T> action)1850         final <T> T binderWithCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
1851             return Binder.withCleanCallingIdentity(action);
1852         }
1853 
userHandleGetCallingUserId()1854         final int userHandleGetCallingUserId() {
1855             return UserHandle.getUserId(binderGetCallingUid());
1856         }
1857 
powerManagerGoToSleep(long time, int reason, int flags)1858         void powerManagerGoToSleep(long time, int reason, int flags) {
1859             mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1860         }
1861 
powerManagerReboot(String reason)1862         void powerManagerReboot(String reason) {
1863             mContext.getSystemService(PowerManager.class).reboot(reason);
1864         }
1865 
recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)1866         boolean recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1867                 boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)
1868                         throws IOException {
1869             return FactoryResetter.newBuilder(mContext).setSafetyChecker(mSafetyChecker)
1870                     .setReason(reason).setShutdown(shutdown).setForce(force).setWipeEuicc(wipeEuicc)
1871                     .setWipeAdoptableStorage(wipeExtRequested)
1872                     .setWipeFactoryResetProtection(wipeResetProtectionData)
1873                     .build().factoryReset();
1874         }
1875 
systemPropertiesGetBoolean(String key, boolean def)1876         boolean systemPropertiesGetBoolean(String key, boolean def) {
1877             return SystemProperties.getBoolean(key, def);
1878         }
1879 
systemPropertiesGetLong(String key, long def)1880         long systemPropertiesGetLong(String key, long def) {
1881             return SystemProperties.getLong(key, def);
1882         }
1883 
systemPropertiesGet(String key, String def)1884         String systemPropertiesGet(String key, String def) {
1885             return SystemProperties.get(key, def);
1886         }
1887 
systemPropertiesGet(String key)1888         String systemPropertiesGet(String key) {
1889             return SystemProperties.get(key);
1890         }
1891 
systemPropertiesSet(String key, String value)1892         void systemPropertiesSet(String key, String value) {
1893             SystemProperties.set(key, value);
1894         }
1895 
userManagerIsHeadlessSystemUserMode()1896         boolean userManagerIsHeadlessSystemUserMode() {
1897             return UserManager.isHeadlessSystemUserMode();
1898         }
1899 
1900         @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
pendingIntentGetActivityAsUser(Context context, int requestCode, @NonNull Intent intent, int flags, Bundle options, UserHandle user)1901         PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1902                 @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
1903             return PendingIntent.getActivityAsUser(
1904                     context, requestCode, intent, flags, options, user);
1905         }
1906 
1907         @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
pendingIntentGetBroadcast( Context context, int requestCode, Intent intent, int flags)1908         PendingIntent pendingIntentGetBroadcast(
1909                 Context context, int requestCode, Intent intent, int flags) {
1910             return PendingIntent.getBroadcast(context, requestCode, intent, flags);
1911         }
1912 
registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer, int userHandle)1913         void registerContentObserver(Uri uri, boolean notifyForDescendents,
1914                 ContentObserver observer, int userHandle) {
1915             mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1916                     observer, userHandle);
1917         }
1918 
settingsSecureGetIntForUser(String name, int def, int userHandle)1919         int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1920             return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1921                     name, def, userHandle);
1922         }
1923 
settingsSecureGetStringForUser(String name, int userHandle)1924         String settingsSecureGetStringForUser(String name, int userHandle) {
1925             return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
1926                     userHandle);
1927         }
1928 
settingsSecurePutIntForUser(String name, int value, int userHandle)1929         void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1930             Settings.Secure.putIntForUser(mContext.getContentResolver(),
1931                     name, value, userHandle);
1932         }
1933 
settingsSecurePutStringForUser(String name, String value, int userHandle)1934         void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1935             Settings.Secure.putStringForUser(mContext.getContentResolver(),
1936                     name, value, userHandle);
1937         }
1938 
settingsGlobalPutStringForUser(String name, String value, int userHandle)1939         void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1940             Settings.Global.putStringForUser(mContext.getContentResolver(),
1941                     name, value, userHandle);
1942         }
1943 
settingsSecurePutInt(String name, int value)1944         void settingsSecurePutInt(String name, int value) {
1945             Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1946         }
1947 
settingsGlobalGetInt(String name, int def)1948         int settingsGlobalGetInt(String name, int def) {
1949             return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1950         }
1951 
1952         @Nullable
settingsGlobalGetString(String name)1953         String settingsGlobalGetString(String name) {
1954             return Settings.Global.getString(mContext.getContentResolver(), name);
1955         }
1956 
settingsGlobalPutInt(String name, int value)1957         void settingsGlobalPutInt(String name, int value) {
1958             Settings.Global.putInt(mContext.getContentResolver(), name, value);
1959         }
1960 
settingsSecurePutString(String name, String value)1961         void settingsSecurePutString(String name, String value) {
1962             Settings.Secure.putString(mContext.getContentResolver(), name, value);
1963         }
1964 
settingsGlobalPutString(String name, String value)1965         void settingsGlobalPutString(String name, String value) {
1966             Settings.Global.putString(mContext.getContentResolver(), name, value);
1967         }
1968 
settingsSystemPutStringForUser(String name, String value, int userId)1969         void settingsSystemPutStringForUser(String name, String value, int userId) {
1970           Settings.System.putStringForUser(
1971               mContext.getContentResolver(), name, value, userId);
1972         }
1973 
securityLogSetLoggingEnabledProperty(boolean enabled)1974         void securityLogSetLoggingEnabledProperty(boolean enabled) {
1975             SecurityLog.setLoggingEnabledProperty(enabled);
1976         }
1977 
securityLogGetLoggingEnabledProperty()1978         boolean securityLogGetLoggingEnabledProperty() {
1979             return SecurityLog.getLoggingEnabledProperty();
1980         }
1981 
securityLogIsLoggingEnabled()1982         boolean securityLogIsLoggingEnabled() {
1983             return SecurityLog.isLoggingEnabled();
1984         }
1985 
keyChainBind()1986         KeyChainConnection keyChainBind() throws InterruptedException {
1987             return KeyChain.bind(mContext);
1988         }
1989 
keyChainBindAsUser(UserHandle user)1990         KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
1991             return KeyChain.bindAsUser(mContext, user);
1992         }
1993 
postOnSystemServerInitThreadPool(Runnable runnable)1994         void postOnSystemServerInitThreadPool(Runnable runnable) {
1995             SystemServerInitThreadPool.submit(runnable, LOG_TAG);
1996         }
1997 
newTransferOwnershipMetadataManager()1998         public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() {
1999             return new TransferOwnershipMetadataManager();
2000         }
2001 
runCryptoSelfTest()2002         public void runCryptoSelfTest() {
2003             CryptoTestHelper.runAndLogSelfTest();
2004         }
2005 
getPersonalAppsForSuspension(@serIdInt int userId)2006         public String[] getPersonalAppsForSuspension(@UserIdInt int userId) {
2007             return PersonalAppsSuspensionHelper.forUser(mContext, userId)
2008                     .getPersonalAppsForSuspension();
2009         }
2010 
systemCurrentTimeMillis()2011         public long systemCurrentTimeMillis() {
2012             return System.currentTimeMillis();
2013         }
2014 
isChangeEnabled(long changeId, String packageName, int userId)2015         public boolean isChangeEnabled(long changeId, String packageName, int userId) {
2016             return CompatChanges.isChangeEnabled(changeId, packageName, UserHandle.of(userId));
2017         }
2018 
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)2019         void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
2020             mSafetyChecker = safetyChecker;
2021         }
2022 
getDeviceManagementResourcesProvider()2023         DeviceManagementResourcesProvider getDeviceManagementResourcesProvider() {
2024             return new DeviceManagementResourcesProvider();
2025         }
2026     }
2027 
2028     /**
2029      * Instantiates the service.
2030      */
DevicePolicyManagerService(Context context)2031     public DevicePolicyManagerService(Context context) {
2032         this(new Injector(
2033                 context.createAttributionContext(ATTRIBUTION_TAG)), new PolicyPathProvider() {});
2034     }
2035 
2036     @VisibleForTesting
DevicePolicyManagerService(Injector injector, PolicyPathProvider pathProvider)2037     DevicePolicyManagerService(Injector injector, PolicyPathProvider pathProvider) {
2038         DevicePolicyManager.disableLocalCaches();
2039 
2040         mInjector = injector;
2041         mPathProvider = pathProvider;
2042         mContext = Objects.requireNonNull(injector.mContext);
2043         mHandler = new Handler(Objects.requireNonNull(injector.getMyLooper()));
2044 
2045         mConstantsObserver = new DevicePolicyConstantsObserver(mHandler);
2046         mConstantsObserver.register();
2047         mConstants = loadConstants();
2048 
2049         mUserManager = Objects.requireNonNull(injector.getUserManager());
2050         mUserManagerInternal = Objects.requireNonNull(injector.getUserManagerInternal());
2051         mUsageStatsManagerInternal = Objects.requireNonNull(
2052                 injector.getUsageStatsManagerInternal());
2053         mIPackageManager = Objects.requireNonNull(injector.getIPackageManager());
2054         mIPermissionManager = Objects.requireNonNull(injector.getIPermissionManager());
2055         mTelephonyManager = Objects.requireNonNull(injector.getTelephonyManager());
2056         mRoleManager = Objects.requireNonNull(injector.getRoleManager());
2057 
2058         mLocalService = new LocalService();
2059         mLockPatternUtils = injector.newLockPatternUtils();
2060         mLockSettingsInternal = injector.getLockSettingsInternal();
2061         // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
2062         mSecurityLogMonitor = new SecurityLogMonitor(this);
2063 
2064         mHasFeature = mInjector.hasFeature();
2065         mIsWatch = mInjector.getPackageManager()
2066                 .hasSystemFeature(PackageManager.FEATURE_WATCH);
2067         mHasTelephonyFeature = mInjector.getPackageManager()
2068                 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
2069         mIsAutomotive = mInjector.getPackageManager()
2070                 .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
2071         mBackgroundHandler = BackgroundThread.getHandler();
2072 
2073         // Needed when mHasFeature == false, because it controls the certificate warning text.
2074         mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
2075 
2076         mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
2077         mOverlayPackagesProvider = new OverlayPackagesProvider(mContext);
2078         mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager();
2079         mBugreportCollectionManager = new RemoteBugreportManager(this, mInjector);
2080 
2081         mDeviceManagementResourcesProvider = mInjector.getDeviceManagementResourcesProvider();
2082         mDevicePolicyManagementRoleObserver = new DevicePolicyManagementRoleObserver(mContext);
2083         mDevicePolicyManagementRoleObserver.register();
2084 
2085         // "Lite" interface is available even when the device doesn't have the feature
2086         LocalServices.addService(DevicePolicyManagerLiteInternal.class, mLocalService);
2087 
2088         // Policy version upgrade must not depend on either mOwners or mUserData, so they are
2089         // initialized only after performing the upgrade.
2090         if (mHasFeature) {
2091             performPolicyVersionUpgrade();
2092         }
2093 
2094         mUserData = new SparseArray<>();
2095         mOwners = makeOwners(injector, pathProvider);
2096 
2097         mDevicePolicyEngine = new DevicePolicyEngine(
2098                 mContext, mDeviceAdminServiceController, getLockObject());
2099 
2100         if (!mHasFeature) {
2101             // Skip the rest of the initialization
2102             mSetupContentObserver = null;
2103             mContactSystemRoleHolders = Collections.emptySet();
2104             return;
2105         }
2106 
2107         loadOwners();
2108 
2109         IntentFilter filter = new IntentFilter();
2110         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
2111         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
2112         filter.addAction(ACTION_TURN_PROFILE_ON_NOTIFICATION);
2113         filter.addAction(ACTION_PROFILE_OFF_DEADLINE);
2114         filter.addAction(Intent.ACTION_USER_ADDED);
2115         filter.addAction(Intent.ACTION_USER_REMOVED);
2116         filter.addAction(Intent.ACTION_USER_STARTED);
2117         filter.addAction(Intent.ACTION_USER_STOPPED);
2118         filter.addAction(Intent.ACTION_USER_SWITCHED);
2119         filter.addAction(Intent.ACTION_USER_UNLOCKED);
2120         filter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
2121         filter.addAction(ACTION_MANAGED_PROFILE_UNAVAILABLE);
2122         filter.addAction(ACTION_MANAGED_PROFILE_AVAILABLE);
2123         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2124         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2125         filter = new IntentFilter();
2126         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
2127         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2128         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
2129         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
2130         filter.addDataScheme("package");
2131         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2132         filter = new IntentFilter();
2133         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
2134         filter.addAction(Intent.ACTION_TIME_CHANGED);
2135         filter.addAction(Intent.ACTION_DATE_CHANGED);
2136         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2137 
2138         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
2139 
2140         mSetupContentObserver = new SetupContentObserver(mHandler);
2141 
2142         mUserManagerInternal.addUserRestrictionsListener(
2143                 new RestrictionsListener(mContext, mUserManagerInternal, this));
2144         mUserManagerInternal.addUserLifecycleListener(new UserLifecycleListener());
2145 
2146         mDeviceManagementResourcesProvider.load();
2147 	mDevicePolicyEngine.load();
2148 
2149         mContactSystemRoleHolders = fetchOemSystemHolders(/* roleResIds...= */
2150                 com.android.internal.R.string.config_defaultSms,
2151                 com.android.internal.R.string.config_defaultDialer,
2152                 com.android.internal.R.string.config_systemContacts
2153         );
2154 
2155         // The binder caches are not enabled until the first invalidation.
2156         invalidateBinderCaches();
2157     }
2158 
2159     /**
2160      * Fetch the OEM System Holders for the supplied roleNames
2161      *
2162      * @param roleResIds the list of resource ids whose role holders are needed
2163      * @return the set of packageNames that handle the requested roles
2164      */
fetchOemSystemHolders(int... roleResIds)2165     private @NonNull Set<String> fetchOemSystemHolders(int... roleResIds) {
2166         Set<String> packageNames = new ArraySet<>();
2167 
2168         for (int roleResId : roleResIds) {
2169             String packageName = getDefaultRoleHolderPackageName(roleResId);
2170             if (packageName != null) {
2171                 packageNames.add(packageName);
2172             }
2173         }
2174 
2175         return Collections.unmodifiableSet(packageNames);
2176     }
2177 
2178 
getDefaultRoleHolderPackageName(int resId)2179     private @Nullable String getDefaultRoleHolderPackageName(int resId) {
2180         String packageNameAndSignature = mContext.getString(resId);
2181 
2182         if (TextUtils.isEmpty(packageNameAndSignature)) {
2183             return null;
2184         }
2185 
2186         if (packageNameAndSignature.contains(":")) {
2187             return packageNameAndSignature.split(":")[0];
2188         }
2189 
2190         return packageNameAndSignature;
2191     }
2192 
suspendAppsForQuietProfiles(boolean toSuspend)2193     private void suspendAppsForQuietProfiles(boolean toSuspend) {
2194         PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
2195         List<UserInfo> users = mUserManagerInternal.getUsers(true /* excludeDying */);
2196         for (UserInfo user : users) {
2197             if (user.isManagedProfile() && user.isQuietModeEnabled()) {
2198                 pmi.setPackagesSuspendedForQuietMode(user.id, toSuspend);
2199             }
2200         }
2201     }
2202 
makeOwners(Injector injector, PolicyPathProvider pathProvider)2203     private Owners makeOwners(Injector injector, PolicyPathProvider pathProvider) {
2204         return new Owners(
2205                 injector.getUserManager(), injector.getUserManagerInternal(),
2206                 injector.getPackageManagerInternal(),
2207                 injector.getActivityTaskManagerInternal(),
2208                 injector.getActivityManagerInternal(), mStateCache, pathProvider);
2209     }
2210 
2211     /**
2212      * Invalidate the binder API caches. The invalidation itself does not require any
2213      * locking, but this specific call should be protected by getLockObject() to ensure
2214      * that the invalidation is synchronous with cached queries, for those queries that
2215      * are served under getLockObject().
2216      */
invalidateBinderCaches()2217     static void invalidateBinderCaches() {
2218         DevicePolicyManager.invalidateBinderCaches();
2219     }
2220 
2221     /**
2222      * Creates and loads the policy data from xml.
2223      * @param userHandle the user for whom to load the policy data
2224      * @return
2225      */
2226     @NonNull
getUserData(int userHandle)2227     DevicePolicyData getUserData(int userHandle) {
2228         synchronized (getLockObject()) {
2229             DevicePolicyData policy = mUserData.get(userHandle);
2230             if (policy == null) {
2231                 policy = new DevicePolicyData(userHandle);
2232                 mUserData.append(userHandle, policy);
2233                 loadSettingsLocked(policy, userHandle);
2234                 if (userHandle == UserHandle.USER_SYSTEM) {
2235                     mStateCache.setDeviceProvisioned(policy.mUserSetupComplete);
2236                 }
2237             }
2238             return policy;
2239         }
2240     }
2241 
2242     /**
2243      * Creates and loads the policy data from xml for data that is shared between
2244      * various profiles of a user. In contrast to {@link #getUserData(int)}
2245      * it allows access to data of users other than the calling user.
2246      *
2247      * This function should only be used for shared data, e.g. everything regarding
2248      * passwords and should be removed once multiple screen locks are present.
2249      * @param userHandle the user for whom to load the policy data
2250      * @return
2251      */
getUserDataUnchecked(int userHandle)2252     DevicePolicyData getUserDataUnchecked(int userHandle) {
2253         return mInjector.binderWithCleanCallingIdentity(() -> getUserData(userHandle));
2254     }
2255 
removeUserData(int userHandle)2256     void removeUserData(int userHandle) {
2257         final boolean isOrgOwned;
2258         synchronized (getLockObject()) {
2259             if (userHandle == UserHandle.USER_SYSTEM) {
2260                 Slogf.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
2261                 return;
2262             }
2263             updatePasswordQualityCacheForUserGroup(userHandle);
2264             mPolicyCache.onUserRemoved(userHandle);
2265 
2266             if (isManagedProfile(userHandle)) {
2267                 clearManagedProfileApnUnchecked();
2268             }
2269             isOrgOwned = mOwners.isProfileOwnerOfOrganizationOwnedDevice(userHandle);
2270 
2271             // Clear any restrictions set by the a profile owner and the parent admin.
2272             final ActiveAdmin admin = getProfileOwnerLocked(userHandle);
2273             if (admin != null) {
2274                 admin.userRestrictions = null;
2275                 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
2276                 if (parentAdmin != null) {
2277                     parentAdmin.userRestrictions = null;
2278                 }
2279                 pushUserRestrictions(userHandle);
2280             }
2281             mOwners.removeProfileOwner(userHandle);
2282             mOwners.writeProfileOwner(userHandle);
2283             pushScreenCapturePolicy(userHandle);
2284 
2285             DevicePolicyData policy = mUserData.get(userHandle);
2286             if (policy != null) {
2287                 mUserData.remove(userHandle);
2288             }
2289 
2290             File policyFile =
2291                     new File(mPathProvider.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML);
2292             policyFile.delete();
2293             Slogf.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
2294         }
2295         if (isOrgOwned) {
2296             final UserInfo primaryUser = mUserManager.getPrimaryUser();
2297             if (primaryUser != null) {
2298                 clearOrgOwnedProfileOwnerDeviceWidePolicies(primaryUser.id);
2299             } else {
2300                 Slogf.wtf(LOG_TAG, "Was unable to get primary user.");
2301             }
2302         }
2303     }
2304 
2305     /**
2306      * Load information about device and profile owners of the device, populating mOwners and
2307      * pushing owner info to other system services. This is called at a fairly early stage of
2308      * system server initialiation (via DevicePolicyManagerService's ctor), so care should to
2309      * be taken to not interact with system services that are initialiated after DPMS.
2310      * onLockSettingsReady() is a safer place to do initialization work not critical during
2311      * the first boot stage.
2312      * Note this only loads the list of owners, and not their actual policy (DevicePolicyData).
2313      * The policy is normally loaded lazily when it's first accessed. In several occasions
2314      * the list of owners is necessary for providing callers with aggregated policies across
2315      * multiple owners, hence the owner list is loaded as part of DPMS's construction here.
2316      */
loadOwners()2317     void loadOwners() {
2318         synchronized (getLockObject()) {
2319             mOwners.load();
2320             setDeviceOwnershipSystemPropertyLocked();
2321             if (mOwners.hasDeviceOwner()) {
2322                 setGlobalSettingDeviceOwnerType(
2323                         mOwners.getDeviceOwnerType(mOwners.getDeviceOwnerPackageName()));
2324             }
2325         }
2326     }
2327 
2328     /**
2329      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
2330      */
getCallerIdentity()2331     private CallerIdentity getCallerIdentity() {
2332         return getCallerIdentity(null, null);
2333     }
2334 
2335     /**
2336      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
2337      */
getCallerIdentity(@ullable String callerPackage)2338     private CallerIdentity getCallerIdentity(@Nullable String callerPackage) {
2339         return getCallerIdentity(null, callerPackage);
2340     }
2341 
2342     /**
2343      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
2344      * The component name should be an active admin for the calling user.
2345      */
2346     @VisibleForTesting
getCallerIdentity(@ullable ComponentName adminComponent)2347     CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent) {
2348         return getCallerIdentity(adminComponent, null);
2349     }
2350 
2351     /**
2352      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
2353      * If {@code adminComponent} is provided, it's validated against the list of known
2354      * active admins and caller uid. If {@code callerPackage} is provided, it's validated
2355      * against the caller uid. If a valid {@code adminComponent} is provided but not
2356      * {@code callerPackage}, the package name of the {@code adminComponent} is used instead.
2357      */
2358     @VisibleForTesting
getCallerIdentity(@ullable ComponentName adminComponent, @Nullable String callerPackage)2359     CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent,
2360             @Nullable String callerPackage) {
2361         final int callerUid = mInjector.binderGetCallingUid();
2362 
2363         if (callerPackage != null) {
2364             if (!isCallingFromPackage(callerPackage, callerUid)) {
2365                 throw new SecurityException(
2366                         String.format("Caller with uid %d is not %s", callerUid, callerPackage));
2367             }
2368         }
2369 
2370         if (adminComponent != null) {
2371             final DevicePolicyData policy = getUserData(UserHandle.getUserId(callerUid));
2372             ActiveAdmin admin = policy.mAdminMap.get(adminComponent);
2373 
2374             // Throwing combined exception message for both the cases here, because from different
2375             // security exceptions it could be deduced if particular package is admin package.
2376             if (admin == null || admin.getUid() != callerUid) {
2377                 throw new SecurityException(String.format(
2378                         "Admin %s does not exist or is not owned by uid %d", adminComponent,
2379                         callerUid));
2380             }
2381             if (callerPackage != null) {
2382                 Preconditions.checkArgument(callerPackage.equals(adminComponent.getPackageName()));
2383             } else {
2384                 callerPackage = adminComponent.getPackageName();
2385             }
2386         }
2387 
2388         return new CallerIdentity(callerUid, callerPackage, adminComponent);
2389     }
2390 
2391     /**
2392      * Checks if the device is in COMP mode, and if so migrates it to managed profile on a
2393      * corporate owned device.
2394      */
2395     @GuardedBy("getLockObject()")
migrateToProfileOnOrganizationOwnedDeviceIfCompLocked()2396     private void migrateToProfileOnOrganizationOwnedDeviceIfCompLocked() {
2397         if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Checking whether we need to migrate COMP ");
2398         final int doUserId = mOwners.getDeviceOwnerUserId();
2399         if (doUserId == UserHandle.USER_NULL) {
2400             if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping migration.");
2401             return;
2402         }
2403 
2404         final List<UserInfo> profiles = mUserManager.getProfiles(doUserId);
2405         if (profiles.size() != 2) {
2406             if (profiles.size() == 1) {
2407                 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Profile not found, skipping migration.");
2408             } else {
2409                 Slogf.wtf(LOG_TAG, "Found " + profiles.size() + " profiles, skipping migration");
2410             }
2411             return;
2412         }
2413 
2414         final int poUserId = getManagedUserId(doUserId);
2415         if (poUserId < 0) {
2416             Slogf.wtf(LOG_TAG, "Found DO and a profile, but it is not managed, skipping migration");
2417             return;
2418         }
2419 
2420         final ActiveAdmin doAdmin = getDeviceOwnerAdminLocked();
2421         final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(poUserId);
2422         if (doAdmin == null || poAdmin == null) {
2423             Slogf.wtf(LOG_TAG, "Failed to get either PO or DO admin, aborting migration.");
2424             return;
2425         }
2426 
2427         final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent();
2428         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(poUserId);
2429         if (doAdminComponent == null || poAdminComponent == null) {
2430             Slogf.wtf(LOG_TAG, "Cannot find PO or DO component name, aborting migration.");
2431             return;
2432         }
2433         if (!doAdminComponent.getPackageName().equals(poAdminComponent.getPackageName())) {
2434             Slogf.e(LOG_TAG, "DO and PO are different packages, aborting migration.");
2435             return;
2436         }
2437 
2438         Slogf.i(LOG_TAG, "Migrating COMP to PO on a corp owned device; primary user: %d; "
2439                 + "profile: %d", doUserId, poUserId);
2440 
2441         Slogf.i(LOG_TAG, "Giving the PO additional power...");
2442         setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(poAdminComponent, poUserId, true);
2443         Slogf.i(LOG_TAG, "Migrating DO policies to PO...");
2444         moveDoPoliciesToProfileParentAdminLocked(doAdmin, poAdmin.getParentActiveAdmin());
2445         migratePersonalAppSuspensionLocked(doUserId, poUserId, poAdmin);
2446         saveSettingsLocked(poUserId);
2447         Slogf.i(LOG_TAG, "Clearing the DO...");
2448         final ComponentName doAdminReceiver = doAdmin.info.getComponent();
2449         clearDeviceOwnerLocked(doAdmin, doUserId);
2450         Slogf.i(LOG_TAG, "Removing admin artifacts...");
2451         removeAdminArtifacts(doAdminReceiver, doUserId);
2452         Slogf.i(LOG_TAG, "Uninstalling the DO...");
2453         uninstallOrDisablePackage(doAdminComponent.getPackageName(), doUserId);
2454         Slogf.i(LOG_TAG, "Migration complete.");
2455 
2456         // Note: KeyChain keys are not removed and will remain accessible for the apps that have
2457         // been given grants to use them.
2458 
2459         DevicePolicyEventLogger
2460                 .createEvent(DevicePolicyEnums.COMP_TO_ORG_OWNED_PO_MIGRATED)
2461                 .setAdmin(poAdminComponent)
2462                 .write();
2463     }
2464 
2465     @GuardedBy("getLockObject()")
migratePersonalAppSuspensionLocked( int doUserId, int poUserId, ActiveAdmin poAdmin)2466     private void migratePersonalAppSuspensionLocked(
2467             int doUserId, int poUserId, ActiveAdmin poAdmin) {
2468         final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
2469         if (!pmi.isSuspendingAnyPackages(PLATFORM_PACKAGE_NAME, doUserId)) {
2470             Slogf.i(LOG_TAG, "DO is not suspending any apps.");
2471             return;
2472         }
2473 
2474         if (getTargetSdk(poAdmin.info.getPackageName(), poUserId) >= Build.VERSION_CODES.R) {
2475             Slogf.i(LOG_TAG, "PO is targeting R+, keeping personal apps suspended.");
2476             getUserData(doUserId).mAppsSuspended = true;
2477             poAdmin.mSuspendPersonalApps = true;
2478         } else {
2479             Slogf.i(LOG_TAG, "PO isn't targeting R+, unsuspending personal apps.");
2480             pmi.unsuspendForSuspendingPackage(PLATFORM_PACKAGE_NAME, doUserId);
2481         }
2482     }
2483 
uninstallOrDisablePackage(String packageName, @UserIdInt int userId)2484     private void uninstallOrDisablePackage(String packageName, @UserIdInt int userId) {
2485         final ApplicationInfo appInfo;
2486         try {
2487             appInfo = mIPackageManager.getApplicationInfo(
2488                     packageName, MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId);
2489         } catch (RemoteException e) {
2490             // Shouldn't happen.
2491             Slogf.wtf(LOG_TAG, "Error getting application info", e);
2492             return;
2493         }
2494         if (appInfo == null) {
2495             Slogf.wtf(LOG_TAG, "Failed to get package info for " + packageName);
2496             return;
2497         }
2498         if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2499             Slogf.i(LOG_TAG, "Package %s is pre-installed, marking disabled until used",
2500                     packageName);
2501             mContext.getPackageManager().setApplicationEnabledSetting(packageName,
2502                     PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, /* flags= */ 0);
2503             return;
2504         }
2505 
2506         final IIntentSender.Stub mLocalSender = new IIntentSender.Stub() {
2507             @Override
2508             public void send(int code, Intent intent, String resolvedType, IBinder allowlistToken,
2509                     IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
2510                 final int status = intent.getIntExtra(
2511                         PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
2512                 if (status == PackageInstaller.STATUS_SUCCESS) {
2513                     Slogf.i(LOG_TAG, "Package %s uninstalled for user %d", packageName, userId);
2514                 } else {
2515                     Slogf.e(LOG_TAG, "Failed to uninstall %s; status: %d", packageName, status);
2516                 }
2517             }
2518         };
2519 
2520         final PackageInstaller pi = mInjector.getPackageManager(userId).getPackageInstaller();
2521         pi.uninstall(packageName, /* flags= */ 0, new IntentSender((IIntentSender) mLocalSender));
2522     }
2523 
2524     @GuardedBy("getLockObject()")
moveDoPoliciesToProfileParentAdminLocked( ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2525     private void moveDoPoliciesToProfileParentAdminLocked(
2526             ActiveAdmin doAdmin, ActiveAdmin parentAdmin) {
2527         // The following policies can be already controlled via parent instance, skip if so.
2528         if (parentAdmin.mPasswordPolicy.quality == PASSWORD_QUALITY_UNSPECIFIED) {
2529             parentAdmin.mPasswordPolicy = doAdmin.mPasswordPolicy;
2530         }
2531         if (parentAdmin.passwordHistoryLength == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) {
2532             parentAdmin.passwordHistoryLength = doAdmin.passwordHistoryLength;
2533         }
2534         if (parentAdmin.passwordExpirationTimeout == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) {
2535             parentAdmin.passwordExpirationTimeout = doAdmin.passwordExpirationTimeout;
2536         }
2537         if (parentAdmin.maximumFailedPasswordsForWipe
2538                 == ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
2539             parentAdmin.maximumFailedPasswordsForWipe = doAdmin.maximumFailedPasswordsForWipe;
2540         }
2541         if (parentAdmin.maximumTimeToUnlock == ActiveAdmin.DEF_MAXIMUM_TIME_TO_UNLOCK) {
2542             parentAdmin.maximumTimeToUnlock = doAdmin.maximumTimeToUnlock;
2543         }
2544         if (parentAdmin.strongAuthUnlockTimeout
2545                 == DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
2546             parentAdmin.strongAuthUnlockTimeout = doAdmin.strongAuthUnlockTimeout;
2547         }
2548         parentAdmin.disabledKeyguardFeatures |=
2549                 doAdmin.disabledKeyguardFeatures & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
2550 
2551         parentAdmin.trustAgentInfos.putAll(doAdmin.trustAgentInfos);
2552 
2553         // The following policies weren't available to PO, but will be available after migration.
2554         parentAdmin.disableCamera = doAdmin.disableCamera;
2555         parentAdmin.disableScreenCapture = doAdmin.disableScreenCapture;
2556         parentAdmin.accountTypesWithManagementDisabled.addAll(
2557                 doAdmin.accountTypesWithManagementDisabled);
2558 
2559         moveDoUserRestrictionsToCopeParent(doAdmin, parentAdmin);
2560 
2561         // From Android 11, {@link setAutoTimeRequired} is no longer used. The user restriction
2562         // {@link UserManager#DISALLOW_CONFIG_DATE_TIME} should be used to enforce auto time
2563         // settings instead.
2564         if (doAdmin.requireAutoTime) {
2565             parentAdmin.ensureUserRestrictions().putBoolean(
2566                     UserManager.DISALLOW_CONFIG_DATE_TIME, true);
2567         }
2568     }
2569 
moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2570     private void moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin) {
2571         if (doAdmin.userRestrictions == null) {
2572             return;
2573         }
2574         for (final String restriction : doAdmin.userRestrictions.keySet()) {
2575             if (UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(restriction)) {
2576                 parentAdmin.ensureUserRestrictions().putBoolean(
2577                         restriction, doAdmin.userRestrictions.getBoolean(restriction));
2578             }
2579         }
2580     }
2581 
2582     /**
2583      * If the device is in Device Owner mode, apply the restriction on adding
2584      * a managed profile.
2585      */
2586     @GuardedBy("getLockObject()")
applyProfileRestrictionsIfDeviceOwnerLocked()2587     private void applyProfileRestrictionsIfDeviceOwnerLocked() {
2588         final int doUserId = mOwners.getDeviceOwnerUserId();
2589         if (doUserId == UserHandle.USER_NULL) {
2590             if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping application of restriction.");
2591             return;
2592         }
2593 
2594         for (UserInfo userInfo : mUserManager.getUsers()) {
2595             UserHandle userHandle = userInfo.getUserHandle();
2596             // Based on  CDD : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support,
2597             // creation of clone profile is not allowed in case device owner is set.
2598             // Enforcing this restriction on setting up of device owner.
2599             if (!mUserManager.hasUserRestriction(
2600                     UserManager.DISALLOW_ADD_CLONE_PROFILE, userHandle)) {
2601                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, true,
2602                         userHandle);
2603             }
2604             // Creation of managed profile is restricted in case device owner is set, enforcing this
2605             // restriction by setting user level restriction at time of device owner setup.
2606             if (!mUserManager.hasUserRestriction(
2607                     UserManager.DISALLOW_ADD_MANAGED_PROFILE, userHandle)) {
2608                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
2609                         userHandle);
2610             }
2611         }
2612     }
2613 
2614     /** Apply default restrictions that haven't been applied to profile owners yet. */
maybeSetDefaultProfileOwnerUserRestrictions()2615     private void maybeSetDefaultProfileOwnerUserRestrictions() {
2616         synchronized (getLockObject()) {
2617             for (final int userId : mOwners.getProfileOwnerKeys()) {
2618                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
2619                 // The following restrictions used to be applied to managed profiles by different
2620                 // means (via Settings or by disabling components). Now they are proper user
2621                 // restrictions so we apply them to managed profile owners. Non-managed secondary
2622                 // users didn't have those restrictions so we skip them to keep existing behavior.
2623                 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
2624                     continue;
2625                 }
2626                 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner);
2627                 ensureUnknownSourcesRestrictionForProfileOwnerLocked(
2628                         userId, profileOwner, false /* newOwner */);
2629             }
2630         }
2631     }
2632 
2633     /**
2634      * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
2635      * set of restrictions for this profile owner.
2636      */
ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, ActiveAdmin profileOwner, boolean newOwner)2637     private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
2638             ActiveAdmin profileOwner, boolean newOwner) {
2639         if (newOwner || mInjector.settingsSecureGetIntForUser(
2640                 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
2641             if (isPolicyEngineForFinanceFlagEnabled()) {
2642                 mDevicePolicyEngine.setLocalPolicy(
2643                         PolicyDefinition.getPolicyDefinitionForUserRestriction(
2644                                 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
2645                         EnforcingAdmin.createEnterpriseEnforcingAdmin(
2646                                 profileOwner.info.getComponent(),
2647                                 profileOwner.getUserHandle().getIdentifier()),
2648                         new BooleanPolicyValue(true),
2649                         userId);
2650             } else {
2651                 profileOwner.ensureUserRestrictions().putBoolean(
2652                         UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
2653                 saveUserRestrictionsLocked(userId);
2654             }
2655             mInjector.settingsSecurePutIntForUser(
2656                     Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
2657         }
2658     }
2659 
2660     /**
2661      * Apply default restrictions that haven't been applied to a given admin yet.
2662      */
maybeSetDefaultRestrictionsForAdminLocked(int userId, ActiveAdmin admin)2663     private void maybeSetDefaultRestrictionsForAdminLocked(int userId, ActiveAdmin admin) {
2664         Set<String> defaultRestrictions =
2665                 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles();
2666         if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
2667             return; // The same set of default restrictions has been already applied.
2668         }
2669         if (isPolicyEngineForFinanceFlagEnabled()) {
2670             for (String restriction : defaultRestrictions) {
2671                 mDevicePolicyEngine.setLocalPolicy(
2672                         PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction),
2673                         EnforcingAdmin.createEnterpriseEnforcingAdmin(
2674                                 admin.info.getComponent(),
2675                                 admin.getUserHandle().getIdentifier()),
2676                         new BooleanPolicyValue(true),
2677                         userId);
2678             }
2679             admin.defaultEnabledRestrictionsAlreadySet.addAll(defaultRestrictions);
2680             Slogf.i(LOG_TAG, "Enabled the following restrictions by default: " +
2681                     defaultRestrictions);
2682             return;
2683         }
2684 
2685         Slogf.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
2686 
2687         if (VERBOSE_LOG) {
2688             Slogf.d(LOG_TAG, "Default enabled restrictions: "
2689                     + defaultRestrictions
2690                     + ". Restrictions already enabled: "
2691                     + admin.defaultEnabledRestrictionsAlreadySet);
2692         }
2693 
2694         final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
2695         restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
2696         if (!restrictionsToSet.isEmpty()) {
2697             for (final String restriction : restrictionsToSet) {
2698                 admin.ensureUserRestrictions().putBoolean(restriction, true);
2699             }
2700             admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
2701             Slogf.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
2702             saveUserRestrictionsLocked(userId);
2703         }
2704     }
2705 
setDeviceOwnershipSystemPropertyLocked()2706     private void setDeviceOwnershipSystemPropertyLocked() {
2707         final boolean deviceProvisioned =
2708                 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2709         final boolean hasDeviceOwner = mOwners.hasDeviceOwner();
2710         final boolean hasOrgOwnedProfile = isOrganizationOwnedDeviceWithManagedProfile();
2711         // If the device is not provisioned and there is currently no management, do not set the
2712         // read-only system property yet, since device owner / org-owned profile may still be
2713         // provisioned.
2714         if (!hasDeviceOwner && !hasOrgOwnedProfile && !deviceProvisioned) {
2715             return;
2716         }
2717         final String value = Boolean.toString(hasDeviceOwner || hasOrgOwnedProfile);
2718         final String currentVal = mInjector.systemPropertiesGet(PROPERTY_ORGANIZATION_OWNED, null);
2719         if (TextUtils.isEmpty(currentVal)) {
2720             Slogf.i(LOG_TAG, "Set ro.organization_owned property to " + value);
2721             mInjector.systemPropertiesSet(PROPERTY_ORGANIZATION_OWNED, value);
2722         } else if (!value.equals(currentVal)) {
2723             Slogf.w(LOG_TAG, "Cannot change existing ro.organization_owned to " + value);
2724         }
2725     }
2726 
maybeStartSecurityLogMonitorOnActivityManagerReady()2727     private void maybeStartSecurityLogMonitorOnActivityManagerReady() {
2728         synchronized (getLockObject()) {
2729             if (mInjector.securityLogIsLoggingEnabled()) {
2730                 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
2731                 mInjector.runCryptoSelfTest();
2732                 maybePauseDeviceWideLoggingLocked();
2733             }
2734         }
2735     }
2736 
2737     /**
2738      * Fix left-over restrictions and auto-time policy during COMP -> COPE migration.
2739      *
2740      * When a COMP device with requireAutoTime policy set was migrated to an
2741      * organization-owned profile, a DISALLOW_CONFIG_DATE_TIME restriction is set
2742      * on user 0 from the DO user, which becomes unremovable by the organization-owned
2743      * profile owner. Fix this by force removing that restriction. Also revert the
2744      * parentAdmin.requireAutoTime bit (since the COPE PO cannot unset this bit)
2745      * and replace it with DISALLOW_CONFIG_DATE_TIME on the correct
2746      * admin, in line with the deprecation recommendation of setAutoTimeRequired().
2747      */
fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration()2748     private void fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration() {
2749         for (UserInfo ui : mUserManager.getUsers()) {
2750             final int userId = ui.id;
2751             if (isProfileOwnerOfOrganizationOwnedDevice(userId)) {
2752                 final ActiveAdmin parent = getProfileOwnerAdminLocked(userId).parentAdmin;
2753                 if (parent != null && parent.requireAutoTime) {
2754                     // Remove deprecated requireAutoTime
2755                     parent.requireAutoTime = false;
2756                     saveSettingsLocked(userId);
2757 
2758                     // Remove user restrictions set by the device owner before the upgrade to
2759                     // Android 11.
2760                     mUserManagerInternal.setDevicePolicyUserRestrictions(UserHandle.USER_SYSTEM,
2761                             new Bundle(), new RestrictionsSet(), /* isDeviceOwner */ false);
2762 
2763                     // Apply user restriction to parent active admin instead
2764                     parent.ensureUserRestrictions().putBoolean(
2765                             UserManager.DISALLOW_CONFIG_DATE_TIME, true);
2766                     pushUserRestrictions(userId);
2767                 }
2768             }
2769         }
2770     }
2771 
2772     /**
2773      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2774      * reminders.  Clears alarm if no expirations are configured.
2775      */
setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent)2776     private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2777         final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2778         final long now = System.currentTimeMillis();
2779         final long timeToExpire = expiration - now;
2780         final long alarmTime;
2781         if (expiration == 0) {
2782             // No expirations are currently configured:  Cancel alarm.
2783             alarmTime = 0;
2784         } else if (timeToExpire <= 0) {
2785             // The password has already expired:  Repeat every 24 hours.
2786             alarmTime = now + MS_PER_DAY;
2787         } else {
2788             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2789             // the expiration time.
2790             long alarmInterval = timeToExpire % MS_PER_DAY;
2791             if (alarmInterval == 0) {
2792                 alarmInterval = MS_PER_DAY;
2793             }
2794             alarmTime = now + alarmInterval;
2795         }
2796 
2797         mInjector.binderWithCleanCallingIdentity(() -> {
2798             int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2799             AlarmManager am = mInjector.getAlarmManager();
2800             // Broadcast alarms sent by system are immutable
2801             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2802                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2803                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
2804                             | PendingIntent.FLAG_IMMUTABLE,
2805                     UserHandle.of(affectedUserHandle));
2806             am.cancel(pi);
2807             if (alarmTime != 0) {
2808                 am.set(AlarmManager.RTC, alarmTime, pi);
2809             }
2810         });
2811     }
2812 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle)2813     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2814         ensureLocked();
2815         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2816         if (admin != null
2817                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2818                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2819             return admin;
2820         }
2821         return null;
2822     }
2823 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent)2824     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2825         ensureLocked();
2826         if (parent) {
2827             Preconditions.checkCallAuthorization(isManagedProfile(userHandle),
2828                     "You can not call APIs on the parent profile outside a managed profile, "
2829                             + "userId = %d", userHandle);
2830         }
2831         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2832         if (admin != null && parent) {
2833             admin = admin.getParentActiveAdmin();
2834         }
2835         return admin;
2836     }
2837 
getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)2838     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2839             throws SecurityException {
2840         return getActiveAdminOrCheckPermissionForCallerLocked(who,
2841                 reqPolicy, /* permission= */ null);
2842     }
2843 
getDeviceOwnerLocked(@serIdInt int userId)2844     ActiveAdmin getDeviceOwnerLocked(@UserIdInt int userId) {
2845         ensureLocked();
2846         ComponentName doComponent = mOwners.getDeviceOwnerComponent();
2847         ActiveAdmin doAdmin = getUserData(userId).mAdminMap.get(doComponent);
2848         return doAdmin;
2849     }
2850 
getDefaultDeviceOwnerLocked(@serIdInt int userId)2851     ActiveAdmin getDefaultDeviceOwnerLocked(@UserIdInt int userId) {
2852         ensureLocked();
2853         ComponentName doComponent = mOwners.getDeviceOwnerComponent();
2854         if (mOwners.getDeviceOwnerType(doComponent.getPackageName()) == DEFAULT_DEVICE_OWNER) {
2855             ActiveAdmin doAdmin = getUserData(userId).mAdminMap.get(doComponent);
2856             return doAdmin;
2857         }
2858         return null;
2859     }
2860 
getProfileOwnerLocked(@serIdInt int userId)2861     ActiveAdmin getProfileOwnerLocked(@UserIdInt int userId) {
2862         ensureLocked();
2863         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(userId);
2864         ActiveAdmin poAdmin = getUserData(userId).mAdminMap.get(poAdminComponent);
2865         return poAdmin;
2866     }
2867 
getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller)2868     @NonNull ActiveAdmin getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller) {
2869         Preconditions.checkCallAuthorization(
2870                 mOwners.isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()),
2871                 "Caller %s is not an admin of an org-owned device",
2872                 caller.getComponentName());
2873         final ActiveAdmin profileOwner = getProfileOwnerLocked(caller.getUserId());
2874 
2875         return profileOwner;
2876     }
2877 
getProfileOwnerOrDeviceOwnerLocked(@serIdInt int userId)2878     ActiveAdmin getProfileOwnerOrDeviceOwnerLocked(@UserIdInt int userId) {
2879         ensureLocked();
2880         // Try to find an admin which can use reqPolicy
2881         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(userId);
2882 
2883         if (poAdminComponent != null) {
2884             return getProfileOwnerLocked(userId);
2885         }
2886 
2887         return getDeviceOwnerLocked(userId);
2888     }
2889 
getProfileOwnerOrDefaultDeviceOwnerLocked(@serIdInt int userId)2890     ActiveAdmin getProfileOwnerOrDefaultDeviceOwnerLocked(@UserIdInt int userId) {
2891         ensureLocked();
2892         // Try to find an admin which can use reqPolicy
2893         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(userId);
2894 
2895         if (poAdminComponent != null) {
2896             return getProfileOwnerLocked(userId);
2897         }
2898 
2899         return getDefaultDeviceOwnerLocked(userId);
2900     }
2901 
getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent)2902     @NonNull ActiveAdmin getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent) {
2903         Objects.requireNonNull(admin);
2904         return parent ? admin.getParentActiveAdmin() : admin;
2905     }
2906 
2907     /**
2908      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2909      *
2910      * @return an active admin or {@code null} if there is no active admin but
2911      * {@code permission} is granted
2912      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2913      */
2914     @Nullable
getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, @Nullable String permission)2915     ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
2916             ComponentName who,
2917             int reqPolicy,
2918             @Nullable String permission) throws SecurityException {
2919         return getActiveAdminOrCheckPermissionsForCallerLocked(
2920                 who, reqPolicy, permission == null ? Set.of() : Set.of(permission));
2921     }
2922 
2923     /**
2924      * Finds an active admin for the caller then checks {@code permissions} if admin check failed.
2925      *
2926      * @return an active admin or {@code null} if there is no active admin but
2927      * one of {@code permissions} is granted
2928      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2929      */
2930     @Nullable
getActiveAdminOrCheckPermissionsForCallerLocked( ComponentName who, int reqPolicy, Set<String> permissions)2931     ActiveAdmin getActiveAdminOrCheckPermissionsForCallerLocked(
2932             ComponentName who,
2933             int reqPolicy,
2934             Set<String> permissions) throws SecurityException {
2935         ensureLocked();
2936         final CallerIdentity caller = getCallerIdentity();
2937 
2938         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, caller.getUid());
2939         if (result != null) {
2940             return result;
2941         } else {
2942             for (String permission : permissions) {
2943                 if (hasCallingPermission(permission)) {
2944                     return null;
2945                 }
2946             }
2947         }
2948 
2949         // Code for handling failure from getActiveAdminWithPolicyForUidLocked to find an admin
2950         // that satisfies the required policy.
2951         // Throws a security exception with the right error message.
2952         if (who != null) {
2953             final DevicePolicyData policy = getUserData(caller.getUserId());
2954             ActiveAdmin admin = policy.mAdminMap.get(who);
2955             final boolean isDeviceOwner = isDeviceOwner(admin.info.getComponent(),
2956                     caller.getUserId());
2957             final boolean isProfileOwner = isProfileOwner(admin.info.getComponent(),
2958                     caller.getUserId());
2959 
2960             if (DA_DISALLOWED_POLICIES.contains(reqPolicy) && !isDeviceOwner && !isProfileOwner) {
2961                 throw new SecurityException("Admin " + admin.info.getComponent()
2962                         + " is not a device owner or profile owner, so may not use policy: "
2963                         + admin.info.getTagForPolicy(reqPolicy));
2964             }
2965             throw new SecurityException("Admin " + admin.info.getComponent()
2966                     + " did not specify uses-policy for: "
2967                     + admin.info.getTagForPolicy(reqPolicy));
2968         } else {
2969             throw new SecurityException("No active admin owned by uid "
2970                     + caller.getUid() + " for policy #" + reqPolicy + (permissions.isEmpty() ? ""
2971                     : ", which doesn't have " + permissions));
2972         }
2973     }
2974 
getActiveAdminForCallerLocked(@ullable ComponentName who, int reqPolicy, boolean parent)2975     ActiveAdmin getActiveAdminForCallerLocked(@Nullable ComponentName who, int reqPolicy,
2976             boolean parent) throws SecurityException {
2977         return getActiveAdminOrCheckPermissionForCallerLocked(
2978                 who, reqPolicy, parent, /* permission= */ null);
2979     }
2980 
2981     /**
2982      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2983      *
2984      * @return an active admin or {@code null} if there is no active admin but
2985      * {@code permission} is granted
2986      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2987      */
2988     @Nullable
getActiveAdminOrCheckPermissionForCallerLocked( @ullable ComponentName who, int reqPolicy, boolean parent, @Nullable String permission)2989     ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
2990             @Nullable ComponentName who,
2991             int reqPolicy,
2992             boolean parent,
2993             @Nullable String permission) throws SecurityException {
2994         return getActiveAdminOrCheckPermissionsForCallerLocked(
2995                 who, reqPolicy, parent, permission == null ? Set.of() : Set.of(permission));
2996     }
2997 
2998     /**
2999      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
3000      *
3001      * @return an active admin or {@code null} if there is no active admin but
3002      * {@code permission} is granted
3003      * @throws SecurityException if caller neither has an active admin nor {@code permission}
3004      */
3005     @Nullable
getActiveAdminOrCheckPermissionsForCallerLocked( @ullable ComponentName who, int reqPolicy, boolean parent, Set<String> permissions)3006     ActiveAdmin getActiveAdminOrCheckPermissionsForCallerLocked(
3007             @Nullable ComponentName who,
3008             int reqPolicy,
3009             boolean parent,
3010             Set<String> permissions) throws SecurityException {
3011         ensureLocked();
3012         if (parent) {
3013             Preconditions.checkCallingUser(isManagedProfile(getCallerIdentity().getUserId()));
3014         }
3015         ActiveAdmin admin = getActiveAdminOrCheckPermissionsForCallerLocked(
3016                 who, reqPolicy, permissions);
3017         return parent ? admin.getParentActiveAdmin() : admin;
3018     }
3019 
3020     /**
3021      * Find the admin for the component and userId bit of the uid, then check
3022      * the admin's uid matches the uid.
3023      */
getActiveAdminForUidLocked(ComponentName who, int uid)3024     private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
3025         ensureLocked();
3026         final int userId = UserHandle.getUserId(uid);
3027         final DevicePolicyData policy = getUserData(userId);
3028         ActiveAdmin admin = policy.mAdminMap.get(who);
3029         if (admin == null) {
3030             throw new SecurityException("No active admin " + who + " for UID " + uid);
3031         }
3032         if (admin.getUid() != uid) {
3033             throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
3034         }
3035         return admin;
3036     }
3037 
3038     /**
3039      * Returns the active admin for the user of the caller as denoted by uid, which implements
3040      * the {@code reqPolicy}.
3041      *
3042      * The {@code who} parameter is used as a hint:
3043      * If provided, it must be the component name of the active admin for that user and the caller
3044      * uid must match the uid of the admin.
3045      * If not provided, iterate over all of the active admins in the DevicePolicyData for that user
3046      * and return the one with the uid specified as parameter, and has the policy specified.
3047      */
3048     @Nullable
getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, int uid)3049     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
3050             int uid) {
3051         ensureLocked();
3052         // Try to find an admin which can use reqPolicy
3053         final int userId = UserHandle.getUserId(uid);
3054         final DevicePolicyData policy = getUserData(userId);
3055         if (who != null) {
3056             ActiveAdmin admin = policy.mAdminMap.get(who);
3057             if (admin == null || admin.getUid() != uid) {
3058                 throw new SecurityException(
3059                         "Admin " + who + " is not active or not owned by uid " + uid);
3060             }
3061             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
3062                 return admin;
3063             }
3064         } else {
3065             for (ActiveAdmin admin : policy.mAdminList) {
3066                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
3067                         userId)) {
3068                     return admin;
3069                 }
3070             }
3071         }
3072 
3073         return null;
3074     }
3075 
3076     @VisibleForTesting
isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, int userId)3077     boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
3078             int userId) {
3079         ensureLocked();
3080         final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
3081         final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
3082 
3083         boolean allowedToUsePolicy = ownsDevice || ownsProfile
3084                 || !DA_DISALLOWED_POLICIES.contains(reqPolicy)
3085                 || getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.Q;
3086         return allowedToUsePolicy && admin.info.usesPolicy(reqPolicy);
3087     }
3088 
3089     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
3090         sendAdminCommandLocked(admin, action, null);
3091     }
3092 
3093     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
3094         sendAdminCommandLocked(admin, action, null, result);
3095     }
3096 
3097     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
3098             BroadcastReceiver result) {
3099         sendAdminCommandLocked(admin, action, adminExtras, result, false);
3100     }
3101 
3102     /**
3103      * Send an update to one specific admin, get notified when that admin returns a result.
3104      *
3105      * @return whether the broadcast was successfully sent
3106      */
3107     boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
3108             BroadcastReceiver result, boolean inForeground) {
3109         Intent intent = new Intent(action);
3110         intent.setComponent(admin.info.getComponent());
3111         if (UserManager.isDeviceInDemoMode(mContext)) {
3112             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3113         }
3114         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
3115             intent.putExtra("expiration", admin.passwordExpirationDate);
3116         }
3117         if (inForeground) {
3118             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3119         }
3120         if (adminExtras != null) {
3121             intent.putExtras(adminExtras);
3122         }
3123         if (mInjector.getPackageManager().queryBroadcastReceiversAsUser(
3124                 intent,
3125                 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3126                 admin.getUserHandle()).isEmpty()) {
3127             return false;
3128         }
3129 
3130         final BroadcastOptions options = BroadcastOptions.makeBasic();
3131         options.setBackgroundActivityStartsAllowed(true);
3132 
3133         if (result != null) {
3134             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
3135                     null, AppOpsManager.OP_NONE, options.toBundle(),
3136                     result, mHandler, Activity.RESULT_OK, null, null);
3137         } else {
3138             mContext.sendBroadcastAsUser(intent, admin.getUserHandle(), null, options.toBundle());
3139         }
3140 
3141         return true;
3142     }
3143 
3144     /**
3145      * Send an update to all admins of a user that enforce a specified policy.
3146      */
3147     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
3148         final DevicePolicyData policy = getUserData(userHandle);
3149         final int count = policy.mAdminList.size();
3150         for (int i = 0; i < count; i++) {
3151             final ActiveAdmin admin = policy.mAdminList.get(i);
3152             if (admin.info.usesPolicy(reqPolicy)) {
3153                 sendAdminCommandLocked(admin, action, adminExtras, null);
3154             }
3155         }
3156     }
3157 
3158     /**
3159      * Send an update intent to all admins of a user and its profiles. Only send to admins that
3160      * enforce a specified policy.
3161      */
3162     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
3163             int userHandle, Bundle adminExtras) {
3164         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
3165         for (int profileId : profileIds) {
3166             sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
3167         }
3168     }
3169 
3170     /**
3171      * Sends a broadcast to each profile that share the password unlock with the given user id.
3172      */
3173     private void sendAdminCommandForLockscreenPoliciesLocked(
3174             String action, int reqPolicy, int userHandle) {
3175         final Bundle extras = new Bundle();
3176         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3177         if (isSeparateProfileChallengeEnabled(userHandle)) {
3178             sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
3179         } else {
3180             sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
3181         }
3182     }
3183 
3184     void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
3185         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3186         DevicePolicyData policy = getUserData(userHandle);
3187         if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
3188             policy.mRemovingAdmins.add(adminReceiver);
3189             sendAdminCommandLocked(admin,
3190                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
3191                     new BroadcastReceiver() {
3192                         @Override
3193                         public void onReceive(Context context, Intent intent) {
3194                             removeAdminArtifacts(adminReceiver, userHandle);
3195                             removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
3196                         }
3197                     });
3198         }
3199     }
3200 
3201     private DeviceAdminInfo findAdmin(final ComponentName adminName, final int userHandle,
3202             boolean throwForMissingPermission) {
3203         final ActivityInfo ai = mInjector.binderWithCleanCallingIdentity(() -> {
3204             try {
3205                 return mIPackageManager.getReceiverInfo(adminName,
3206                         GET_META_DATA
3207                         | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS
3208                         | PackageManager.MATCH_DIRECT_BOOT_AWARE
3209                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
3210             } catch (RemoteException e) {
3211                 // shouldn't happen.
3212                 Slogf.wtf(LOG_TAG, "Error getting receiver info", e);
3213                 return null;
3214             }
3215         });
3216         if (ai == null) {
3217             throw new IllegalArgumentException("Unknown admin: " + adminName);
3218         }
3219 
3220         if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
3221             final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
3222                     + permission.BIND_DEVICE_ADMIN;
3223             Slogf.w(LOG_TAG, message);
3224             if (throwForMissingPermission &&
3225                     ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
3226                 throw new IllegalArgumentException(message);
3227             }
3228         }
3229 
3230         try {
3231             return new DeviceAdminInfo(mContext, ai);
3232         } catch (XmlPullParserException | IOException e) {
3233             Slogf.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
3234                     e);
3235             return null;
3236         }
3237     }
3238 
3239     private File getPolicyFileDirectory(@UserIdInt int userId) {
3240         return userId == UserHandle.USER_SYSTEM
3241                 ? mPathProvider.getDataSystemDirectory()
3242                 : mPathProvider.getUserSystemDirectory(userId);
3243     }
3244 
3245     private JournaledFile makeJournaledFile(@UserIdInt int userId, String fileName) {
3246         final String base = new File(getPolicyFileDirectory(userId), fileName)
3247                 .getAbsolutePath();
3248         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Opening %s", base);
3249         return new JournaledFile(new File(base), new File(base + ".tmp"));
3250     }
3251 
3252     private JournaledFile makeJournaledFile(@UserIdInt int userId) {
3253         return makeJournaledFile(userId, DEVICE_POLICIES_XML);
3254     }
3255 
3256     /**
3257      * Persist modified values to disk by calling {@link #saveSettingsLocked} for each
3258      * affected user ID.
3259      */
3260     @GuardedBy("getLockObject()")
3261     private void saveSettingsForUsersLocked(Set<Integer> affectedUserIds) {
3262         for (int userId : affectedUserIds) {
3263             saveSettingsLocked(userId);
3264         }
3265     }
3266 
3267     private void saveSettingsLocked(int userHandle) {
3268         if (DevicePolicyData.store(getUserData(userHandle), makeJournaledFile(userHandle))) {
3269             sendChangedNotification(userHandle);
3270         }
3271         invalidateBinderCaches();
3272     }
3273 
3274     private void sendChangedNotification(int userHandle) {
3275         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
3276         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3277         Bundle options = new BroadcastOptions()
3278                 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
3279                 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
3280                 .toBundle();
3281         mInjector.binderWithCleanCallingIdentity(() ->
3282                 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle), null, options));
3283     }
3284 
3285     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
3286         DevicePolicyData.load(policy,
3287                 makeJournaledFile(userHandle),
3288                 component -> findAdmin(
3289                         component, userHandle, /* throwForMissingPermission= */ false),
3290                 getOwnerComponent(userHandle));
3291 
3292         policy.validatePasswordOwner();
3293         updateMaximumTimeToLockLocked(userHandle);
3294         if (!isPolicyEngineForFinanceFlagEnabled()) {
3295             updateLockTaskPackagesLocked(mContext, policy.mLockTaskPackages, userHandle);
3296             updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle);
3297         }
3298         if (policy.mStatusBarDisabled) {
3299             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
3300         }
3301     }
3302 
3303     static void updateLockTaskPackagesLocked(Context context, List<String> packages, int userId) {
3304         Binder.withCleanCallingIdentity(() -> {
3305 
3306             String[] packagesArray = null;
3307             if (!packages.isEmpty()) {
3308                 // When adding packages, we need to include the exempt apps so they can still be
3309                 // launched (ideally we should use a different AM API as these apps don't need to
3310                 // use lock-task mode).
3311                 // They're not added when the packages is empty though, as in that case we're
3312                 // disabling lock-task mode.
3313                 List<String> exemptApps = listPolicyExemptAppsUnchecked(context);
3314                 if (!exemptApps.isEmpty()) {
3315                     // TODO(b/175377361): add unit test to verify it (cannot be CTS because the
3316                     //  policy-exempt apps are provided by OEM and the test would have no control
3317                     //  over it) once tests are migrated to the new infra-structure
3318                     HashSet<String> updatedPackages = new HashSet<>(packages);
3319                     updatedPackages.addAll(exemptApps);
3320                     if (VERBOSE_LOG) {
3321                         Slogf.v(LOG_TAG, "added %d policy-exempt apps to %d lock task "
3322                                 + "packages. Final list: %s",
3323                                 exemptApps.size(), packages.size(), updatedPackages);
3324                     }
3325                     packagesArray = updatedPackages.toArray(new String[updatedPackages.size()]);
3326                 }
3327             }
3328 
3329             if (packagesArray == null) {
3330                 packagesArray = packages.toArray(new String[packages.size()]);
3331             }
3332             try {
3333                 ActivityManager.getService().updateLockTaskPackages(userId, packagesArray);
3334             } catch (RemoteException e) {
3335                 // Shouldn't happen.
3336                 Slog.wtf(LOG_TAG, "Remote Exception: ", e);
3337             }
3338         });
3339     }
3340 
3341     static void updateLockTaskFeaturesLocked(int flags, int userId) {
3342         Binder.withCleanCallingIdentity(() -> {
3343             try {
3344                 ActivityTaskManager.getService().updateLockTaskFeatures(userId, flags);
3345             } catch (RemoteException e) {
3346                 // Shouldn't happen.
3347                 Slog.wtf(LOG_TAG, "Remote Exception: ", e);
3348             }
3349         });
3350     }
3351 
3352     static void validateQualityConstant(int quality) {
3353         switch (quality) {
3354             case PASSWORD_QUALITY_UNSPECIFIED:
3355             case PASSWORD_QUALITY_BIOMETRIC_WEAK:
3356             case PASSWORD_QUALITY_SOMETHING:
3357             case PASSWORD_QUALITY_NUMERIC:
3358             case PASSWORD_QUALITY_NUMERIC_COMPLEX:
3359             case PASSWORD_QUALITY_ALPHABETIC:
3360             case PASSWORD_QUALITY_ALPHANUMERIC:
3361             case PASSWORD_QUALITY_COMPLEX:
3362             case PASSWORD_QUALITY_MANAGED:
3363                 return;
3364         }
3365         throw new IllegalArgumentException("Invalid quality constant: 0x"
3366                 + Integer.toHexString(quality));
3367     }
3368 
3369     @VisibleForTesting
3370     void systemReady(int phase) {
3371         if (!mHasFeature) {
3372             return;
3373         }
3374         switch (phase) {
3375             case SystemService.PHASE_LOCK_SETTINGS_READY:
3376                 onLockSettingsReady();
3377                 loadAdminDataAsync();
3378                 mOwners.systemReady();
3379                 applyManagedSubscriptionsPolicyIfRequired();
3380                 break;
3381             case SystemService.PHASE_SYSTEM_SERVICES_READY:
3382             	synchronized (getLockObject()) {
3383                     mDevicePolicyEngine.reapplyAllPoliciesLocked();
3384                 }
3385                 break;
3386             case SystemService.PHASE_ACTIVITY_MANAGER_READY:
3387                 synchronized (getLockObject()) {
3388                     migrateToProfileOnOrganizationOwnedDeviceIfCompLocked();
3389                     applyProfileRestrictionsIfDeviceOwnerLocked();
3390 
3391                     // TODO: Is this the right place to trigger the migration?
3392                     if (shouldMigrateToDevicePolicyEngine()) {
3393                         migratePoliciesToDevicePolicyEngine();
3394                     }
3395                 }
3396                 maybeStartSecurityLogMonitorOnActivityManagerReady();
3397                 break;
3398             case SystemService.PHASE_BOOT_COMPLETED:
3399                 // Ideally it should be done earlier, but currently it relies on RecoverySystem,
3400                 // which would hang on earlier phases
3401                 factoryResetIfDelayedEarlier();
3402 
3403                 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
3404                 break;
3405         }
3406     }
3407 
3408     private void applyManagedSubscriptionsPolicyIfRequired() {
3409         int copeProfileUserId = getOrganizationOwnedProfileUserId();
3410         // This policy is relevant only for COPE devices.
3411         if (copeProfileUserId != UserHandle.USER_NULL) {
3412             unregisterOnSubscriptionsChangedListener();
3413             int policyType = getManagedSubscriptionsPolicy().getPolicyType();
3414             if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS) {
3415                 clearManagedSubscriptionsPolicy();
3416             } else if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
3417                 // Add listener to assign all current and future subs to managed profile.
3418                 registerListenerToAssignSubscriptionsToUser(copeProfileUserId);
3419             }
3420         }
3421     }
3422 
3423     private void updatePersonalAppsSuspensionOnUserStart(int userHandle) {
3424         final int profileUserHandle = getManagedUserId(userHandle);
3425         if (profileUserHandle >= 0) {
3426             // Given that the parent user has just started, profile should be locked.
3427             updatePersonalAppsSuspension(profileUserHandle);
3428         } else {
3429             suspendPersonalAppsInternal(userHandle, profileUserHandle, false);
3430         }
3431     }
3432 
3433     private void onLockSettingsReady() {
3434         synchronized (getLockObject()) {
3435             fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration();
3436         }
3437         getUserData(UserHandle.USER_SYSTEM);
3438         cleanUpOldUsers();
3439         maybeSetDefaultProfileOwnerUserRestrictions();
3440         handleStartUser(UserHandle.USER_SYSTEM);
3441         maybeLogStart();
3442 
3443         // Register an observer for watching for user setup complete and settings changes.
3444         mSetupContentObserver.register();
3445         // Initialize the user setup state, to handle the upgrade case.
3446         updateUserSetupCompleteAndPaired();
3447 
3448         List<String> packageList;
3449         synchronized (getLockObject()) {
3450             packageList = getKeepUninstalledPackagesLocked();
3451         }
3452         if (packageList != null) {
3453             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3454         }
3455 
3456         synchronized (getLockObject()) {
3457             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3458             if (deviceOwner != null) {
3459                 // Push the force-ephemeral-users policy to the user manager.
3460                 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3461 
3462                 // Update user switcher message to activity manager.
3463                 ActivityManagerInternal activityManagerInternal =
3464                         mInjector.getActivityManagerInternal();
3465                 activityManagerInternal.setSwitchingFromSystemUserMessage(
3466                         deviceOwner.startUserSessionMessage);
3467                 activityManagerInternal.setSwitchingToSystemUserMessage(
3468                         deviceOwner.endUserSessionMessage);
3469             }
3470 
3471             revertTransferOwnershipIfNecessaryLocked();
3472         }
3473         updateUsbDataSignal();
3474 
3475         // In case flag value has changed, we apply it during boot to avoid doing it concurrently
3476         // with user toggling quiet mode.
3477         setKeepProfileRunningEnabledUnchecked(isKeepProfilesRunningFlagEnabled());
3478     }
3479 
3480     // TODO(b/230841522) Make it static.
3481     private class DpmsUpgradeDataProvider implements PolicyUpgraderDataProvider {
3482         @Override
3483         public JournaledFile makeDevicePoliciesJournaledFile(int userId) {
3484             return DevicePolicyManagerService.this.makeJournaledFile(userId, DEVICE_POLICIES_XML);
3485         }
3486 
3487         @Override
3488         public JournaledFile makePoliciesVersionJournaledFile(int userId) {
3489             return DevicePolicyManagerService.this.makeJournaledFile(userId, POLICIES_VERSION_XML);
3490         }
3491 
3492         @Override
3493         public Function<ComponentName, DeviceAdminInfo> getAdminInfoSupplier(int userId) {
3494             return component ->
3495                     findAdmin(component, userId, /* throwForMissingPermission= */ false);
3496         }
3497 
3498         @Override
3499         public int[] getUsersForUpgrade() {
3500             List<UserInfo> allUsers = mUserManager.getUsers();
3501             return allUsers.stream().mapToInt(u -> u.id).toArray();
3502         }
3503 
3504         @Override
3505         public List<String> getPlatformSuspendedPackages(int userId) {
3506             PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
3507             return mInjector.getPackageManager(userId)
3508                     .getInstalledPackages(PackageManager.PackageInfoFlags.of(
3509                             MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE))
3510                     .stream()
3511                     .map(packageInfo -> packageInfo.packageName)
3512                     .filter(pkg ->
3513                             PLATFORM_PACKAGE_NAME.equals(pmi.getSuspendingPackage(pkg, userId))
3514                     )
3515                     .collect(Collectors.toList());
3516         }
3517     }
3518 
3519     private void performPolicyVersionUpgrade() {
3520         PolicyVersionUpgrader upgrader = new PolicyVersionUpgrader(
3521                 new DpmsUpgradeDataProvider(), mPathProvider);
3522         upgrader.upgradePolicy(DPMS_VERSION);
3523     }
3524 
3525     private void revertTransferOwnershipIfNecessaryLocked() {
3526         if (!mTransferOwnershipMetadataManager.metadataFileExists()) {
3527             return;
3528         }
3529         Slogf.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer.");
3530         final TransferOwnershipMetadataManager.Metadata metadata =
3531                 mTransferOwnershipMetadataManager.loadMetadataFile();
3532         // Revert transfer
3533         if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) {
3534             transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3535                     metadata.userId);
3536             deleteTransferOwnershipMetadataFileLocked();
3537             deleteTransferOwnershipBundleLocked(metadata.userId);
3538         } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) {
3539             transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3540                     metadata.userId);
3541             deleteTransferOwnershipMetadataFileLocked();
3542             deleteTransferOwnershipBundleLocked(metadata.userId);
3543         }
3544         updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
3545         if (!isPolicyEngineForFinanceFlagEnabled()) {
3546             pushUserControlDisabledPackagesLocked(metadata.userId);
3547         }
3548     }
3549 
3550     private void maybeLogStart() {
3551         if (!SecurityLog.isLoggingEnabled()) {
3552             return;
3553         }
3554         final String verifiedBootState =
3555                 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate");
3556         final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode");
3557         SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode);
3558     }
3559 
3560     private void ensureDeviceOwnerUserStarted() {
3561         final int userId;
3562         synchronized (getLockObject()) {
3563             if (!mOwners.hasDeviceOwner()) {
3564                 return;
3565             }
3566             userId = mOwners.getDeviceOwnerUserId();
3567         }
3568         if (VERBOSE_LOG) {
3569             Slogf.v(LOG_TAG, "Starting non-system DO user: " + userId);
3570         }
3571         if (userId != UserHandle.USER_SYSTEM) {
3572             try {
3573                 mInjector.getIActivityManager().startUserInBackground(userId);
3574 
3575                 // STOPSHIP Prevent the DO user from being killed.
3576 
3577             } catch (RemoteException e) {
3578                 Slogf.w(LOG_TAG, "Exception starting user", e);
3579             }
3580         }
3581     }
3582 
3583     void handleStartUser(int userId) {
3584         synchronized (getLockObject()) {
3585             pushScreenCapturePolicy(userId);
3586             if (!isPolicyEngineForFinanceFlagEnabled()) {
3587                 pushUserControlDisabledPackagesLocked(userId);
3588             }
3589         }
3590         pushUserRestrictions(userId);
3591         // When system user is started (device boot), load cache for all users.
3592         // This is to mitigate the potential race between loading the cache and keyguard
3593         // reading the value during user switch, due to onStartUser() being asynchronous.
3594         updatePasswordQualityCacheForUserGroup(
3595                 userId == UserHandle.USER_SYSTEM ? UserHandle.USER_ALL : userId);
3596         updatePermissionPolicyCache(userId);
3597         updateAdminCanGrantSensorsPermissionCache(userId);
3598 
3599         final List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs;
3600         synchronized (getLockObject()) {
3601             ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
3602             preferentialNetworkServiceConfigs = owner != null
3603                     ? owner.mPreferentialNetworkServiceConfigs
3604                     : List.of(PreferentialNetworkServiceConfig.DEFAULT);
3605         }
3606         updateNetworkPreferenceForUser(userId, preferentialNetworkServiceConfigs);
3607 
3608         if (isProfileOwnerOfOrganizationOwnedDevice(userId)
3609                 && getManagedSubscriptionsPolicy().getPolicyType()
3610                 == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
3611             updateDialerAndSmsManagedShortcutsOverrideCache();
3612         }
3613 
3614         startOwnerService(userId, "start-user");
3615         if (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled()) {
3616             mDevicePolicyEngine.handleStartUser(userId);
3617         }
3618     }
3619 
3620     void pushUserControlDisabledPackagesLocked(int userId) {
3621         final int targetUserId;
3622         final ActiveAdmin owner;
3623         if (getDeviceOwnerUserIdUncheckedLocked() == userId) {
3624             owner = getDeviceOwnerAdminLocked();
3625             targetUserId = UserHandle.USER_ALL;
3626         } else {
3627             owner = getProfileOwnerAdminLocked(userId);
3628             targetUserId = userId;
3629         }
3630 
3631         List<String> protectedPackages = (owner == null || owner.protectedPackages == null)
3632                 ? null : owner.protectedPackages;
3633         mInjector.binderWithCleanCallingIdentity(() ->
3634                 mInjector.getPackageManagerInternal().setOwnerProtectedPackages(
3635                         targetUserId, protectedPackages));
3636         mUsageStatsManagerInternal.setAdminProtectedPackages(new ArraySet(protectedPackages),
3637                 targetUserId);
3638     }
3639 
3640     void handleUnlockUser(int userId) {
3641         startOwnerService(userId, "unlock-user");
3642         if (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled()) {
3643             mDevicePolicyEngine.handleUnlockUser(userId);
3644         }
3645     }
3646 
3647     void handleOnUserUnlocked(int userId) {
3648         showNewUserDisclaimerIfNecessary(userId);
3649     }
3650 
3651     void handleStopUser(int userId) {
3652         updateNetworkPreferenceForUser(userId, List.of(PreferentialNetworkServiceConfig.DEFAULT));
3653         mDeviceAdminServiceController.stopServicesForUser(userId, /* actionForLog= */ "stop-user");
3654         if (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled()) {
3655             mDevicePolicyEngine.handleStopUser(userId);
3656         }
3657     }
3658 
3659     private void startOwnerService(int userId, String actionForLog) {
3660         final ComponentName owner = getOwnerComponent(userId);
3661         if (owner != null) {
3662             mDeviceAdminServiceController.startServiceForAdmin(
3663                     owner.getPackageName(), userId, actionForLog);
3664             invalidateBinderCaches();
3665         }
3666     }
3667 
3668     private void cleanUpOldUsers() {
3669         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3670         // before reboot
3671         Set<Integer> usersWithProfileOwners;
3672         Set<Integer> usersWithData;
3673         synchronized (getLockObject()) {
3674             usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3675             usersWithData = new ArraySet<>();
3676             for (int i = 0; i < mUserData.size(); i++) {
3677                 usersWithData.add(mUserData.keyAt(i));
3678             }
3679         }
3680         List<UserInfo> allUsers = mUserManager.getUsers();
3681 
3682         Set<Integer> deletedUsers = new ArraySet<>();
3683         deletedUsers.addAll(usersWithProfileOwners);
3684         deletedUsers.addAll(usersWithData);
3685         for (UserInfo userInfo : allUsers) {
3686             deletedUsers.remove(userInfo.id);
3687         }
3688         for (Integer userId : deletedUsers) {
3689             removeUserData(userId);
3690             if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
3691                 mDevicePolicyEngine.handleUserRemoved(userId);
3692             }
3693         }
3694     }
3695 
3696     private void handlePasswordExpirationNotification(int userHandle) {
3697         final Bundle adminExtras = new Bundle();
3698         adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3699 
3700         synchronized (getLockObject()) {
3701             final long now = System.currentTimeMillis();
3702 
3703             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
3704             final int N = admins.size();
3705             for (int i = 0; i < N; i++) {
3706                 ActiveAdmin admin = admins.get(i);
3707                 if ((admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD))
3708                         && admin.passwordExpirationTimeout > 0L
3709                         && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3710                         && admin.passwordExpirationDate > 0L) {
3711                     sendAdminCommandLocked(admin,
3712                             DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3713                 }
3714             }
3715             setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3716         }
3717     }
3718 
3719     /**
3720      * Clean up internal state when the set of installed trusted CA certificates changes.
3721      *
3722      * @param userHandle user to check for. This must be a real user and not, for example,
3723      *        {@link UserHandle#ALL}.
3724      * @param installedCertificates the full set of certificate authorities currently installed for
3725      *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3726      *        correspond to some subset of this.
3727      */
3728     protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3729             final @NonNull Collection<String> installedCertificates) {
3730         if (!mHasFeature) {
3731             return;
3732         }
3733         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
3734 
3735         synchronized (getLockObject()) {
3736             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3737 
3738             boolean changed = false;
3739             changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3740             changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3741             if (changed) {
3742                 saveSettingsLocked(userHandle.getIdentifier());
3743             }
3744         }
3745     }
3746 
3747     /**
3748      * Internal method used by {@link CertificateMonitor}.
3749      */
3750     protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3751         if (!mHasFeature) {
3752             return Collections.<String> emptySet();
3753         }
3754         synchronized (getLockObject()) {
3755             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3756             return policy.mAcceptedCaCertificates;
3757         }
3758     }
3759 
3760     /**
3761      * @param adminReceiver The admin to add
3762      * @param refreshing true = update an active admin, no error
3763      */
3764     @Override
3765     public void setActiveAdmin(
3766             ComponentName adminReceiver, boolean refreshing, int userHandle) {
3767         if (!mHasFeature) {
3768             return;
3769         }
3770         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3771 
3772         final CallerIdentity caller = getCallerIdentity();
3773         Preconditions.checkCallAuthorization(
3774                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
3775         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3776 
3777         DevicePolicyData policy = getUserData(userHandle);
3778         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3779                 /* throwForMissingPermission= */ true);
3780         synchronized (getLockObject()) {
3781             checkActiveAdminPrecondition(adminReceiver, info, policy);
3782             mInjector.binderWithCleanCallingIdentity(() -> {
3783                 final ActiveAdmin existingAdmin
3784                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3785                 if (!refreshing && existingAdmin != null) {
3786                     throw new IllegalArgumentException("Admin is already added");
3787                 }
3788                 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3789                 newAdmin.testOnlyAdmin =
3790                         (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3791                                 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3792                 policy.mAdminMap.put(adminReceiver, newAdmin);
3793                 int replaceIndex = -1;
3794                 final int N = policy.mAdminList.size();
3795                 for (int i=0; i < N; i++) {
3796                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3797                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3798                         replaceIndex = i;
3799                         break;
3800                     }
3801                 }
3802                 if (replaceIndex == -1) {
3803                     policy.mAdminList.add(newAdmin);
3804                     enableIfNecessary(info.getPackageName(), userHandle);
3805                     mUsageStatsManagerInternal.onActiveAdminAdded(
3806                             adminReceiver.getPackageName(), userHandle);
3807                 } else {
3808                     policy.mAdminList.set(replaceIndex, newAdmin);
3809                 }
3810                 saveSettingsLocked(userHandle);
3811                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3812                         /* adminExtras= */ null, /* result= */ null);
3813             });
3814         }
3815     }
3816 
3817     private void loadAdminDataAsync() {
3818         mInjector.postOnSystemServerInitThreadPool(() -> {
3819             pushActiveAdminPackages();
3820             mUsageStatsManagerInternal.onAdminDataAvailable();
3821             pushAllMeteredRestrictedPackages();
3822             mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable();
3823         });
3824     }
3825 
3826     private void pushActiveAdminPackages() {
3827         synchronized (getLockObject()) {
3828             final List<UserInfo> users = mUserManager.getUsers();
3829             for (int i = users.size() - 1; i >= 0; --i) {
3830                 final int userId = users.get(i).id;
3831                 mUsageStatsManagerInternal.setActiveAdminApps(
3832                         getActiveAdminPackagesLocked(userId), userId);
3833             }
3834         }
3835     }
3836 
3837     private void pushAllMeteredRestrictedPackages() {
3838         synchronized (getLockObject()) {
3839             final List<UserInfo> users = mUserManager.getUsers();
3840             for (int i = users.size() - 1; i >= 0; --i) {
3841                 final int userId = users.get(i).id;
3842                 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync(
3843                         getMeteredDisabledPackages(userId), userId);
3844             }
3845         }
3846     }
3847 
3848     private void pushActiveAdminPackagesLocked(int userId) {
3849         mUsageStatsManagerInternal.setActiveAdminApps(
3850                 getActiveAdminPackagesLocked(userId), userId);
3851     }
3852 
3853     private Set<String> getActiveAdminPackagesLocked(int userId) {
3854         final DevicePolicyData policy = getUserData(userId);
3855         Set<String> adminPkgs = null;
3856         for (int i = policy.mAdminList.size() - 1; i >= 0; --i) {
3857             final String pkgName = policy.mAdminList.get(i).info.getPackageName();
3858             if (adminPkgs == null) {
3859                 adminPkgs = new ArraySet<>();
3860             }
3861             adminPkgs.add(pkgName);
3862         }
3863         return adminPkgs;
3864     }
3865 
3866     private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver,
3867             ComponentName outgoingReceiver, int userHandle) {
3868         final DevicePolicyData policy = getUserData(userHandle);
3869         if (!policy.mAdminMap.containsKey(outgoingReceiver)
3870                 && policy.mAdminMap.containsKey(incomingReceiver)) {
3871             // Nothing to transfer - the incoming receiver is already the active admin.
3872             return;
3873         }
3874         final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle,
3875             /* throwForMissingPermission= */ true);
3876         final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver);
3877         final int oldAdminUid = adminToTransfer.getUid();
3878 
3879         if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
3880             EnforcingAdmin oldAdmin =
3881                     EnforcingAdmin.createEnterpriseEnforcingAdmin(
3882                             outgoingReceiver, userHandle, adminToTransfer);
3883             EnforcingAdmin newAdmin =
3884                     EnforcingAdmin.createEnterpriseEnforcingAdmin(
3885                             incomingReceiver, userHandle, adminToTransfer);
3886 
3887             mDevicePolicyEngine.transferPolicies(oldAdmin, newAdmin);
3888         }
3889 
3890         adminToTransfer.transfer(incomingDeviceInfo);
3891         policy.mAdminMap.remove(outgoingReceiver);
3892         policy.mAdminMap.put(incomingReceiver, adminToTransfer);
3893         if (policy.mPasswordOwner == oldAdminUid) {
3894             policy.mPasswordOwner = adminToTransfer.getUid();
3895         }
3896 
3897         saveSettingsLocked(userHandle);
3898         sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3899                 null, null);
3900     }
3901 
3902     private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info,
3903             DevicePolicyData policy) {
3904         if (info == null) {
3905             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3906         }
3907         if (!info.getActivityInfo().applicationInfo.isInternal()) {
3908             throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3909                     + adminReceiver);
3910         }
3911         if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3912             throw new IllegalArgumentException("Instant apps cannot be device admins: "
3913                     + adminReceiver);
3914         }
3915         if (policy.mRemovingAdmins.contains(adminReceiver)) {
3916             throw new IllegalArgumentException(
3917                     "Trying to set an admin which is being removed");
3918         }
3919     }
3920 
3921     private void checkAllUsersAreAffiliatedWithDevice() {
3922         Preconditions.checkCallAuthorization(areAllUsersAffiliatedWithDeviceLocked(),
3923                 "operation not allowed when device has unaffiliated users");
3924     }
3925 
3926     @Override
3927     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3928         if (!mHasFeature) {
3929             return false;
3930         }
3931         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3932 
3933         final CallerIdentity caller = getCallerIdentity();
3934         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3935 
3936         synchronized (getLockObject()) {
3937             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3938         }
3939     }
3940 
3941     @Override
3942     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3943         if (!mHasFeature) {
3944             return false;
3945         }
3946         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3947 
3948         final CallerIdentity caller = getCallerIdentity();
3949         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3950 
3951         synchronized (getLockObject()) {
3952             DevicePolicyData policyData = getUserData(userHandle);
3953             return policyData.mRemovingAdmins.contains(adminReceiver);
3954         }
3955     }
3956 
3957     @Override
3958     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3959         if (!mHasFeature) {
3960             return false;
3961         }
3962         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3963 
3964         final CallerIdentity caller = getCallerIdentity();
3965         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3966         Preconditions.checkCallAuthorization(
3967                 isCallingFromPackage(adminReceiver.getPackageName(), caller.getUid())
3968                         || isSystemUid(caller));
3969 
3970         synchronized (getLockObject()) {
3971             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3972             if (administrator == null) {
3973                 throw new SecurityException("No active admin " + adminReceiver);
3974             }
3975             return administrator.info.usesPolicy(policyId);
3976         }
3977     }
3978 
3979     @Override
3980     @SuppressWarnings("unchecked")
3981     public List<ComponentName> getActiveAdmins(int userHandle) {
3982         if (!mHasFeature) {
3983             return Collections.EMPTY_LIST;
3984         }
3985         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3986 
3987         final CallerIdentity caller = getCallerIdentity();
3988         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3989 
3990         synchronized (getLockObject()) {
3991             DevicePolicyData policy = getUserData(userHandle);
3992             final int N = policy.mAdminList.size();
3993             if (N <= 0) {
3994                 return null;
3995             }
3996             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3997             for (int i=0; i<N; i++) {
3998                 res.add(policy.mAdminList.get(i).info.getComponent());
3999             }
4000             return res;
4001         }
4002     }
4003 
4004     @Override
4005     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
4006         if (!mHasFeature) {
4007             return false;
4008         }
4009         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4010 
4011         final CallerIdentity caller = getCallerIdentity();
4012         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4013 
4014         synchronized (getLockObject()) {
4015             DevicePolicyData policy = getUserData(userHandle);
4016             final int N = policy.mAdminList.size();
4017             for (int i=0; i<N; i++) {
4018                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
4019                     return true;
4020                 }
4021             }
4022             return false;
4023         }
4024     }
4025 
4026     @Override
4027     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
4028         if (!mHasFeature) {
4029             return;
4030         }
4031         Objects.requireNonNull(adminReceiver, "ComponentName is null");
4032         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
4033                         || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS),
4034                 "Caller must be shell or hold MANAGE_PROFILE_AND_DEVICE_OWNERS to call "
4035                         + "forceRemoveActiveAdmin");
4036         mInjector.binderWithCleanCallingIdentity(() -> {
4037             boolean isOrgOwnedProfile = false;
4038             synchronized (getLockObject()) {
4039                 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
4040                     throw new SecurityException("Attempt to remove non-test admin "
4041                             + adminReceiver + " " + userHandle);
4042                 }
4043 
4044                 // If admin is a device or profile owner tidy that up first.
4045                 if (isDeviceOwner(adminReceiver, userHandle)) {
4046                     clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
4047                 }
4048                 if (isProfileOwner(adminReceiver, userHandle)) {
4049                     isOrgOwnedProfile = isProfileOwnerOfOrganizationOwnedDevice(userHandle);
4050                     final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
4051                             userHandle, /* parent */ false);
4052                     clearProfileOwnerLocked(admin, userHandle);
4053                 }
4054             }
4055             // Remove the admin skipping sending the broadcast.
4056             removeAdminArtifacts(adminReceiver, userHandle);
4057 
4058             // In case of PO on org owned device, clean device-wide policies and restrictions.
4059             if (isOrgOwnedProfile) {
4060                 final UserHandle parentUser = UserHandle.of(getProfileParentId(userHandle));
4061                 clearOrgOwnedProfileOwnerUserRestrictions(parentUser);
4062                 clearOrgOwnedProfileOwnerDeviceWidePolicies(parentUser.getIdentifier());
4063             }
4064 
4065             Slogf.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
4066         });
4067     }
4068 
4069     private void clearOrgOwnedProfileOwnerUserRestrictions(UserHandle parentUserHandle) {
4070         mUserManager.setUserRestriction(
4071                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, false, parentUserHandle);
4072         mUserManager.setUserRestriction(
4073                 UserManager.DISALLOW_ADD_USER, false, parentUserHandle);
4074     }
4075 
4076     private void clearDeviceOwnerUserRestriction(UserHandle userHandle) {
4077         if (isHeadlessFlagEnabled()) {
4078             for (int userId : mUserManagerInternal.getUserIds()) {
4079                 UserHandle user = UserHandle.of(userId);
4080                 // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the
4081                 // original state
4082                 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, user)) {
4083                     mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER,
4084                             false, user);
4085                 }
4086                 // When a device owner is set, the system automatically restricts adding a
4087                 // managed profile.
4088                 // Remove this restriction when the device owner is cleared.
4089                 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
4090                         user)) {
4091                     mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
4092                             false,
4093                             user);
4094                 }
4095                 // When a device owner is set, the system automatically restricts adding a
4096                 // clone profile.
4097                 // Remove this restriction when the device owner is cleared.
4098                 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, user)) {
4099                     mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
4100                             false, user);
4101                 }
4102             }
4103         } else {
4104             // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state
4105             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
4106                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false,
4107                         userHandle);
4108             }
4109             // When a device owner is set, the system automatically restricts adding a
4110             // managed profile.
4111             // Remove this restriction when the device owner is cleared.
4112             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
4113                     userHandle)) {
4114                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
4115                         false,
4116                         userHandle);
4117             }
4118             // When a device owner is set, the system automatically restricts adding a clone
4119             // profile.
4120             // Remove this restriction when the device owner is cleared.
4121             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
4122                     userHandle)) {
4123                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
4124                         false,
4125                         userHandle);
4126             }
4127         }
4128     }
4129 
4130     /**
4131      * Return if a given package has testOnly="true", in which case we'll relax certain rules
4132      * for CTS.
4133      *
4134      * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
4135      * to check wehter an active admin is test-only or not.
4136      *
4137      * The system allows this flag to be changed when an app is updated, which is not good
4138      * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
4139      * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
4140      */
4141     private boolean isPackageTestOnly(String packageName, int userHandle) {
4142         final ApplicationInfo ai;
4143         try {
4144             ai = mInjector.getIPackageManager().getApplicationInfo(packageName,
4145                     (PackageManager.MATCH_DIRECT_BOOT_AWARE
4146                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
4147         } catch (RemoteException e) {
4148             throw new IllegalStateException(e);
4149         }
4150         if (ai == null) {
4151             throw new IllegalStateException("Couldn't find package: "
4152                     + packageName + " on user " + userHandle);
4153         }
4154         return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
4155     }
4156 
4157     /**
4158      * See {@link #isPackageTestOnly}.
4159      */
4160     private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
4161         final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4162         return (admin != null) && admin.testOnlyAdmin;
4163     }
4164 
4165     @Override
4166     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
4167         if (!mHasFeature) {
4168             return;
4169         }
4170         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4171 
4172         final CallerIdentity caller = hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)
4173                 ? getCallerIdentity() : getCallerIdentity(adminReceiver);
4174         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4175         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_ACTIVE_ADMIN);
4176         enforceUserUnlocked(userHandle);
4177 
4178         ActiveAdmin admin;
4179         synchronized (getLockObject()) {
4180             admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
4181             if (admin == null) {
4182                 return;
4183             }
4184             // Active device/profile owners must remain active admins.
4185             if (isDeviceOwner(adminReceiver, userHandle)
4186                     || isProfileOwner(adminReceiver, userHandle)) {
4187                 Slogf.e(LOG_TAG, "Device/profile owner cannot be removed: component="
4188                         + adminReceiver);
4189                 return;
4190             }
4191             mInjector.binderWithCleanCallingIdentity(() ->
4192                     removeActiveAdminLocked(adminReceiver, userHandle));
4193         }
4194         if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
4195             mDevicePolicyEngine.removePoliciesForAdmin(
4196                     EnforcingAdmin.createEnterpriseEnforcingAdmin(
4197                             adminReceiver, userHandle, admin));
4198         }
4199     }
4200 
4201     private boolean canSetPasswordQualityOnParent(String packageName, final CallerIdentity caller) {
4202         return !mInjector.isChangeEnabled(
4203                 PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT, packageName, caller.getUserId())
4204             || isProfileOwnerOfOrganizationOwnedDevice(caller);
4205     }
4206 
4207     private boolean isPasswordLimitingAdminTargetingP(CallerIdentity caller) {
4208         if (!caller.hasAdminComponent()) {
4209             return false;
4210         }
4211 
4212         synchronized (getLockObject()) {
4213             return getActiveAdminWithPolicyForUidLocked(
4214                     caller.getComponentName(), DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD,
4215                     caller.getUid()) != null;
4216         }
4217     }
4218 
4219     private boolean notSupportedOnAutomotive(String method) {
4220         if (mIsAutomotive) {
4221             Slogf.i(LOG_TAG, "%s is not supported on automotive builds", method);
4222             return true;
4223         }
4224         return false;
4225     }
4226 
4227     @Override
4228     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
4229         if (!mHasFeature || notSupportedOnAutomotive("setPasswordQuality")) {
4230             return;
4231         }
4232         Objects.requireNonNull(who, "ComponentName is null");
4233         validateQualityConstant(quality);
4234 
4235         final CallerIdentity caller = getCallerIdentity(who);
4236         Preconditions.checkCallAuthorization(
4237                 isProfileOwner(caller) || isDefaultDeviceOwner(caller)
4238                         || isSystemUid(caller) || isPasswordLimitingAdminTargetingP(caller));
4239 
4240         if (parent) {
4241             Preconditions.checkCallAuthorization(
4242                     canSetPasswordQualityOnParent(who.getPackageName(), caller),
4243                     "Profile Owner may not apply password quality requirements device-wide");
4244         }
4245 
4246         final int userId = caller.getUserId();
4247         synchronized (getLockObject()) {
4248             ActiveAdmin ap = getActiveAdminForCallerLocked(
4249                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4250 
4251             // If setPasswordQuality is called on the parent, ensure that
4252             // the primary admin does not have password complexity state (this is an
4253             // unsupported state).
4254             if (parent) {
4255                 final ActiveAdmin primaryAdmin = getActiveAdminForCallerLocked(
4256                         who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, false);
4257                 final boolean hasComplexitySet =
4258                         primaryAdmin.mPasswordComplexity != PASSWORD_COMPLEXITY_NONE;
4259                 Preconditions.checkState(!hasComplexitySet,
4260                         "Cannot set password quality when complexity is set on the primary admin."
4261                         + " Set the primary admin's complexity to NONE first.");
4262             }
4263             mInjector.binderWithCleanCallingIdentity(() -> {
4264                 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4265                 if (passwordPolicy.quality != quality) {
4266                     passwordPolicy.quality = quality;
4267                     ap.mPasswordComplexity = PASSWORD_COMPLEXITY_NONE;
4268                     resetInactivePasswordRequirementsIfRPlus(userId, ap);
4269                     updatePasswordValidityCheckpointLocked(userId, parent);
4270                     updatePasswordQualityCacheForUserGroup(userId);
4271                     saveSettingsLocked(userId);
4272                 }
4273                 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4274             });
4275         }
4276         DevicePolicyEventLogger
4277                 .createEvent(DevicePolicyEnums.SET_PASSWORD_QUALITY)
4278                 .setAdmin(who)
4279                 .setInt(quality)
4280                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
4281                 .write();
4282     }
4283 
4284     private boolean passwordQualityInvocationOrderCheckEnabled(String packageName, int userId) {
4285         return mInjector.isChangeEnabled(ADMIN_APP_PASSWORD_COMPLEXITY, packageName, userId);
4286     }
4287 
4288     /**
4289      * For admins targeting R+ reset various password constraints to default values when quality is
4290      * set to a value that makes those constraints that have no effect.
4291      */
4292     private void resetInactivePasswordRequirementsIfRPlus(int userId, ActiveAdmin admin) {
4293         if (passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(), userId)) {
4294             final PasswordPolicy policy = admin.mPasswordPolicy;
4295             if (policy.quality < PASSWORD_QUALITY_NUMERIC) {
4296                 policy.length = PasswordPolicy.DEF_MINIMUM_LENGTH;
4297             }
4298             if (policy.quality < PASSWORD_QUALITY_COMPLEX) {
4299                 policy.letters = PasswordPolicy.DEF_MINIMUM_LETTERS;
4300                 policy.upperCase = PasswordPolicy.DEF_MINIMUM_UPPER_CASE;
4301                 policy.lowerCase = PasswordPolicy.DEF_MINIMUM_LOWER_CASE;
4302                 policy.numeric = PasswordPolicy.DEF_MINIMUM_NUMERIC;
4303                 policy.symbols = PasswordPolicy.DEF_MINIMUM_SYMBOLS;
4304                 policy.nonLetter = PasswordPolicy.DEF_MINIMUM_NON_LETTER;
4305             }
4306         }
4307     }
4308 
4309     /**
4310      * Updates a flag that tells us whether the user's password currently satisfies the
4311      * requirements set by all of the user's active admins.
4312      * This should be called whenever the password or the admin policies have changed. The caller
4313      * is responsible for calling {@link #saveSettingsLocked} to persist the change.
4314      *
4315      * @return the set of user IDs that have been affected
4316      */
4317     @GuardedBy("getLockObject()")
4318     private Set<Integer> updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) {
4319         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
4320         final int credentialOwner = getCredentialOwner(userHandle, parent);
4321         DevicePolicyData policy = getUserData(credentialOwner);
4322         PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
4323         // Update the checkpoint only if the user's password metrics is known
4324         if (metrics != null) {
4325             final int userToCheck = getProfileParentUserIfRequested(userHandle, parent);
4326             final boolean newCheckpoint = isPasswordSufficientForUserWithoutCheckpointLocked(
4327                     metrics, userToCheck);
4328             if (newCheckpoint != policy.mPasswordValidAtLastCheckpoint) {
4329                 policy.mPasswordValidAtLastCheckpoint = newCheckpoint;
4330                 affectedUserIds.add(credentialOwner);
4331             }
4332         }
4333         return affectedUserIds;
4334     }
4335 
4336     /**
4337      * Update password quality values in policy cache for all users in the same user group as
4338      * the given user. The cached password quality for user X is the aggregated quality among all
4339      * admins who have influence of user X's screenlock, i.e. it's equivalent to the return value of
4340      * getPasswordQuality(null, user X, false).
4341      *
4342      * Caches for all users in the same user group often need to be updated alltogether because a
4343      * user's admin policy can affect another's aggregated password quality in some situation.
4344      * For example a managed profile's policy will affect the parent user if the profile has unified
4345      * challenge. A profile can also explicitly set a parent password quality which will affect the
4346      * aggregated password quality of the parent user.
4347      */
4348     private void updatePasswordQualityCacheForUserGroup(@UserIdInt int userId) {
4349         final List<UserInfo> users;
4350         if (userId == UserHandle.USER_ALL) {
4351             users = mUserManager.getUsers();
4352         } else {
4353             users = mUserManager.getProfiles(userId);
4354         }
4355         for (UserInfo userInfo : users) {
4356             final int currentUserId = userInfo.id;
4357             mPolicyCache.setPasswordQuality(currentUserId,
4358                     getPasswordQuality(null, currentUserId, false));
4359         }
4360     }
4361 
4362     @Override
4363     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
4364         if (!mHasFeature) {
4365             return PASSWORD_QUALITY_UNSPECIFIED;
4366         }
4367         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4368 
4369         final CallerIdentity caller = getCallerIdentity();
4370         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4371         // System caller can query policy for a particular admin.
4372         Preconditions.checkCallAuthorization(
4373                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
4374                         || canQueryAdminPolicy(caller));
4375 
4376         synchronized (getLockObject()) {
4377             int mode = PASSWORD_QUALITY_UNSPECIFIED;
4378 
4379             if (who != null) {
4380                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4381                 return admin != null ? admin.mPasswordPolicy.quality : mode;
4382             }
4383 
4384             // Return the strictest policy across all participating admins.
4385             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4386                     getProfileParentUserIfRequested(userHandle, parent));
4387             final int N = admins.size();
4388             for (int i = 0; i < N; i++) {
4389                 ActiveAdmin admin = admins.get(i);
4390                 if (mode < admin.mPasswordPolicy.quality) {
4391                     mode = admin.mPasswordPolicy.quality;
4392                 }
4393             }
4394             return mode;
4395         }
4396     }
4397 
4398     @GuardedBy("getLockObject()")
4399     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(int userHandle) {
4400         if (isSeparateProfileChallengeEnabled(userHandle)) {
4401 
4402             if (isPermissionCheckFlagEnabled()) {
4403                 return getActiveAdminsForAffectedUserInclPermissionBasedAdminLocked(userHandle);
4404             }
4405             // If this user has a separate challenge, only return its restrictions.
4406             return getUserDataUnchecked(userHandle).mAdminList;
4407         }
4408         // If isSeparateProfileChallengeEnabled is false and userHandle points to a managed profile
4409         // we need to query the parent user who owns the credential.
4410         if (isPermissionCheckFlagEnabled()) {
4411             return getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(getProfileParentId(userHandle),
4412                     (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
4413         } else {
4414             return getActiveAdminsForUserAndItsManagedProfilesLocked(getProfileParentId(userHandle),
4415                     (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
4416         }
4417 
4418     }
4419 
4420     /**
4421      * Get the list of active admins for an affected user:
4422      * <ul>
4423      * <li>The active admins associated with the userHandle itself</li>
4424      * <li>The parent active admins for each managed profile associated with the userHandle</li>
4425      * </ul>
4426      *
4427      * @param userHandle the affected user for whom to get the active admins
4428      * @return the list of active admins for the affected user
4429      */
4430     @GuardedBy("getLockObject()")
4431     private List<ActiveAdmin> getActiveAdminsForAffectedUserLocked(int userHandle) {
4432         if (isManagedProfile(userHandle)) {
4433             return getUserDataUnchecked(userHandle).mAdminList;
4434         }
4435         return getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
4436                 /* shouldIncludeProfileAdmins */ (user) -> false);
4437     }
4438 
4439     /**
4440      * Get the list of active admins for an affected user:
4441      * <ul>
4442      * <li>The active admins associated with the userHandle itself</li>
4443      * <li>The parent active admins for each managed profile associated with the userHandle</li>
4444      * <li>The permission based admin associated with the userHandle itself</li>
4445      * </ul>
4446      *
4447      * @param userHandle the affected user for whom to get the active admins
4448      * @return the list of active admins for the affected user
4449      */
4450     @GuardedBy("getLockObject()")
4451     private List<ActiveAdmin> getActiveAdminsForAffectedUserInclPermissionBasedAdminLocked(
4452             int userHandle) {
4453         List<ActiveAdmin> list;
4454 
4455         if (isManagedProfile(userHandle)) {
4456             list = getUserDataUnchecked(userHandle).mAdminList;
4457         }
4458         list = getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(userHandle,
4459                 /* shouldIncludeProfileAdmins */ (user) -> false);
4460 
4461         if (getUserData(userHandle).mPermissionBasedAdmin != null) {
4462             list.add(getUserData(userHandle).mPermissionBasedAdmin);
4463         }
4464         return list;
4465     }
4466 
4467     /**
4468      * Returns the list of admins on the given user, as well as parent admins for each managed
4469      * profile associated with the given user. Optionally also include the admin of each managed
4470      * profile.
4471      * <p> Should not be called on a profile user.
4472      */
4473     @GuardedBy("getLockObject()")
4474     private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesLocked(int userHandle,
4475             Predicate<UserInfo> shouldIncludeProfileAdmins) {
4476         ArrayList<ActiveAdmin> admins = new ArrayList<>();
4477         mInjector.binderWithCleanCallingIdentity(() -> {
4478             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4479                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4480                 if (userInfo.id == userHandle) {
4481                     admins.addAll(policy.mAdminList);
4482                 } else if (userInfo.isManagedProfile()) {
4483                     for (int i = 0; i < policy.mAdminList.size(); i++) {
4484                         ActiveAdmin admin = policy.mAdminList.get(i);
4485                         if (admin.hasParentActiveAdmin()) {
4486                             admins.add(admin.getParentActiveAdmin());
4487                         }
4488                         if (shouldIncludeProfileAdmins.test(userInfo)) {
4489                             admins.add(admin);
4490                         }
4491                     }
4492                 }
4493             }
4494         });
4495         return admins;
4496     }
4497 
4498     /**
4499      * Returns the list of admins on the given user, as well as parent admins for each managed
4500      * profile associated with the given user. Optionally also include the admin of each managed
4501      * profile.
4502      * <p> Should not be called on a profile user.
4503      */
4504     @GuardedBy("getLockObject()")
4505     private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(int userHandle,
4506             Predicate<UserInfo> shouldIncludeProfileAdmins) {
4507         ArrayList<ActiveAdmin> admins = new ArrayList<>();
4508         mInjector.binderWithCleanCallingIdentity(() -> {
4509             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4510                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4511                 if (userInfo.id == userHandle) {
4512                     admins.addAll(policy.mAdminList);
4513                     if (policy.mPermissionBasedAdmin != null) {
4514                         admins.add(policy.mPermissionBasedAdmin);
4515                     }
4516                 } else if (userInfo.isManagedProfile()) {
4517                     for (int i = 0; i < policy.mAdminList.size(); i++) {
4518                         ActiveAdmin admin = policy.mAdminList.get(i);
4519                         if (admin.hasParentActiveAdmin()) {
4520                             admins.add(admin.getParentActiveAdmin());
4521                         }
4522                         if (shouldIncludeProfileAdmins.test(userInfo)) {
4523                             admins.add(admin);
4524                         }
4525                     }
4526                     if (policy.mPermissionBasedAdmin != null
4527                             && shouldIncludeProfileAdmins.test(userInfo)) {
4528                         admins.add(policy.mPermissionBasedAdmin);
4529                     }
4530                 }
4531             }
4532         });
4533         return admins;
4534     }
4535 
4536     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
4537         return mInjector.binderWithCleanCallingIdentity(() ->
4538                 mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle));
4539     }
4540 
4541     @Override
4542     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
4543         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLength")) {
4544             return;
4545         }
4546         Objects.requireNonNull(who, "ComponentName is null");
4547         final int userId = mInjector.userHandleGetCallingUserId();
4548         synchronized (getLockObject()) {
4549             ActiveAdmin ap = getActiveAdminForCallerLocked(
4550                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4551             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_NUMERIC, "setPasswordMinimumLength");
4552             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4553             if (passwordPolicy.length != length) {
4554                 passwordPolicy.length = length;
4555                 updatePasswordValidityCheckpointLocked(userId, parent);
4556                 saveSettingsLocked(userId);
4557             }
4558             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4559         }
4560         DevicePolicyEventLogger
4561                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LENGTH)
4562                 .setAdmin(who)
4563                 .setInt(length)
4564                 .write();
4565     }
4566 
4567     private void ensureMinimumQuality(
4568             int userId, ActiveAdmin admin, int minimumQuality, String operation) {
4569         mInjector.binderWithCleanCallingIdentity(() -> {
4570             // This check will also take care of the case where the password requirements
4571             // are specified as complexity rather than quality: When a password complexity
4572             // is set, the quality is reset to "unspecified" which will be below any value
4573             // of minimumQuality.
4574             if (admin.mPasswordPolicy.quality < minimumQuality
4575                     && passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(),
4576                     userId)) {
4577                 throw new IllegalStateException(String.format(
4578                         "password quality should be at least %d for %s",
4579                         minimumQuality, operation));
4580             }
4581         });
4582     }
4583 
4584     @Override
4585     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
4586         return getStrictestPasswordRequirement(who, userHandle, parent,
4587                 admin -> admin.mPasswordPolicy.length, PASSWORD_QUALITY_NUMERIC);
4588     }
4589 
4590     @Override
4591     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
4592         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4593             return;
4594         }
4595         Objects.requireNonNull(who, "ComponentName is null");
4596         final int userId = mInjector.userHandleGetCallingUserId();
4597         synchronized (getLockObject()) {
4598             ActiveAdmin ap = getActiveAdminForCallerLocked(
4599                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4600             if (ap.passwordHistoryLength != length) {
4601                 ap.passwordHistoryLength = length;
4602                 updatePasswordValidityCheckpointLocked(userId, parent);
4603                 saveSettingsLocked(userId);
4604             }
4605         }
4606         if (SecurityLog.isLoggingEnabled()) {
4607             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4608             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET,
4609                     who.getPackageName(), userId, affectedUserId, length);
4610         }
4611     }
4612 
4613     @Override
4614     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
4615         if (!mLockPatternUtils.hasSecureLockScreen()) {
4616             return 0;
4617         }
4618         return getStrictestPasswordRequirement(who, userHandle, parent,
4619                 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
4620     }
4621 
4622     @Override
4623     public void setPasswordExpirationTimeout(ComponentName who, String callerPackageName,
4624             long timeout, boolean parent) {
4625         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4626             return;
4627         }
4628         if (!isPermissionCheckFlagEnabled()) {
4629             Objects.requireNonNull(who, "ComponentName is null");
4630         }
4631 
4632         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
4633         int userHandle = mInjector.userHandleGetCallingUserId();
4634         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
4635         synchronized (getLockObject()) {
4636             ActiveAdmin ap;
4637             if (isPermissionCheckFlagEnabled()) {
4638                 CallerIdentity caller = getCallerIdentity(who, callerPackageName);
4639                 ap = enforcePermissionAndGetEnforcingAdmin(
4640                         who, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
4641                         caller.getPackageName(), affectedUserId)
4642                         .getActiveAdmin();
4643             } else {
4644                 ap = getActiveAdminForCallerLocked(
4645                         who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
4646             }
4647             // Calling this API automatically bumps the expiration date
4648             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4649             ap.passwordExpirationDate = expiration;
4650             ap.passwordExpirationTimeout = timeout;
4651             if (timeout > 0L) {
4652                 Slogf.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
4653                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
4654                         .format(new Date(expiration)));
4655             }
4656             saveSettingsLocked(userHandle);
4657 
4658             // in case this is the first one, set the alarm on the appropriate user.
4659             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
4660         }
4661         if (SecurityLog.isLoggingEnabled()) {
4662             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, callerPackageName,
4663                     userHandle, affectedUserId, timeout);
4664         }
4665     }
4666 
4667     /**
4668      * Return a single admin's expiration cycle time, or the min of all cycle times.
4669      * Returns 0 if not configured.
4670      */
4671     @Override
4672     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
4673         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4674             return 0L;
4675         }
4676         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4677 
4678         final CallerIdentity caller = getCallerIdentity(who);
4679         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4680 
4681         synchronized (getLockObject()) {
4682             long timeout = 0L;
4683 
4684             if (who != null) {
4685                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4686                 return admin != null ? admin.passwordExpirationTimeout : timeout;
4687             }
4688 
4689             // Return the strictest policy across all participating admins.
4690             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4691                     getProfileParentUserIfRequested(userHandle, parent));
4692             final int N = admins.size();
4693             for (int i = 0; i < N; i++) {
4694                 ActiveAdmin admin = admins.get(i);
4695                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
4696                         && timeout > admin.passwordExpirationTimeout)) {
4697                     timeout = admin.passwordExpirationTimeout;
4698                 }
4699             }
4700             return timeout;
4701         }
4702     }
4703 
4704     @Override
4705     public boolean addCrossProfileWidgetProvider(ComponentName admin, String callerPackageName,
4706             String packageName) {
4707         CallerIdentity caller;
4708 
4709         if (isPermissionCheckFlagEnabled()) {
4710             caller = getCallerIdentity(admin, callerPackageName);
4711         } else {
4712             caller = getCallerIdentity(admin);
4713         }
4714         ActiveAdmin activeAdmin;
4715 
4716         if (isPermissionCheckFlagEnabled()) {
4717             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
4718                     admin,
4719                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
4720                     caller.getPackageName(),
4721                     caller.getUserId());
4722             activeAdmin = enforcingAdmin.getActiveAdmin();
4723         } else {
4724             Objects.requireNonNull(admin, "ComponentName is null");
4725             Preconditions.checkCallAuthorization(isProfileOwner(caller));
4726             synchronized (getLockObject()) {
4727                 activeAdmin = getProfileOwnerLocked(caller.getUserId());
4728             }
4729         }
4730         List<String> changedProviders = null;
4731 
4732         synchronized (getLockObject()) {
4733             if (activeAdmin.crossProfileWidgetProviders == null) {
4734                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
4735             }
4736             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4737             if (!providers.contains(packageName)) {
4738                 providers.add(packageName);
4739                 changedProviders = new ArrayList<>(providers);
4740                 saveSettingsLocked(caller.getUserId());
4741             }
4742         }
4743 
4744         DevicePolicyEventLogger
4745                 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_WIDGET_PROVIDER)
4746                 .setAdmin(caller.getPackageName())
4747                 .write();
4748 
4749         if (changedProviders != null) {
4750             mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(),
4751                     changedProviders);
4752             return true;
4753         }
4754 
4755         return false;
4756     }
4757 
4758     @Override
4759     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String callerPackageName,
4760             String packageName) {
4761         CallerIdentity caller;
4762         if (isPermissionCheckFlagEnabled()) {
4763             caller = getCallerIdentity(admin, callerPackageName);
4764         } else {
4765             caller = getCallerIdentity(admin);
4766         }
4767 
4768         ActiveAdmin activeAdmin;
4769 
4770         if (isPermissionCheckFlagEnabled()) {
4771             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
4772                     admin,
4773                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
4774                     caller.getPackageName(),
4775                     caller.getUserId());
4776             activeAdmin = enforcingAdmin.getActiveAdmin();
4777         } else {
4778             Objects.requireNonNull(admin, "ComponentName is null");
4779             Preconditions.checkCallAuthorization(isProfileOwner(caller));
4780             synchronized (getLockObject()) {
4781                 activeAdmin = getProfileOwnerLocked(caller.getUserId());
4782             }
4783         }
4784         List<String> changedProviders = null;
4785 
4786         synchronized (getLockObject()) {
4787             if (activeAdmin.crossProfileWidgetProviders == null
4788                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4789                 return false;
4790             }
4791             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4792             if (providers.remove(packageName)) {
4793                 changedProviders = new ArrayList<>(providers);
4794                 saveSettingsLocked(caller.getUserId());
4795             }
4796         }
4797 
4798         DevicePolicyEventLogger
4799                 .createEvent(DevicePolicyEnums.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER)
4800                 .setAdmin(caller.getPackageName())
4801                 .write();
4802 
4803         if (changedProviders != null) {
4804             mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(),
4805                     changedProviders);
4806             return true;
4807         }
4808 
4809         return false;
4810     }
4811 
4812     @Override
4813     public List<String> getCrossProfileWidgetProviders(ComponentName admin,
4814             String callerPackageName) {
4815         CallerIdentity caller;
4816         if (isPermissionCheckFlagEnabled()) {
4817             caller = getCallerIdentity(admin, callerPackageName);
4818         } else {
4819             caller = getCallerIdentity(admin);
4820         }
4821         ActiveAdmin activeAdmin;
4822 
4823         if (isPermissionCheckFlagEnabled()) {
4824             EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
4825                     admin,
4826                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
4827                     caller.getPackageName(),
4828                     caller.getUserId());
4829             activeAdmin = enforcingAdmin.getActiveAdmin();
4830         } else {
4831             Objects.requireNonNull(admin, "ComponentName is null");
4832             Preconditions.checkCallAuthorization(isProfileOwner(caller));
4833             synchronized (getLockObject()) {
4834                 activeAdmin = getProfileOwnerLocked(caller.getUserId());
4835             }
4836         }
4837 
4838         synchronized (getLockObject()) {
4839             if (activeAdmin.crossProfileWidgetProviders == null
4840                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4841                 return null;
4842             }
4843             if (mInjector.binderIsCallingUidMyUid()) {
4844                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
4845             } else {
4846                 return activeAdmin.crossProfileWidgetProviders;
4847             }
4848         }
4849     }
4850 
4851     /**
4852      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
4853      * Returns 0 if not configured.
4854      */
4855     @GuardedBy("getLockObject()")
4856     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
4857         long timeout = 0L;
4858 
4859         if (who != null) {
4860             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4861             return admin != null ? admin.passwordExpirationDate : timeout;
4862         }
4863 
4864         // Return the strictest policy across all participating admins.
4865         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4866                 getProfileParentUserIfRequested(userHandle, parent));
4867         final int N = admins.size();
4868         for (int i = 0; i < N; i++) {
4869             ActiveAdmin admin = admins.get(i);
4870             if (timeout == 0L || (admin.passwordExpirationDate != 0
4871                     && timeout > admin.passwordExpirationDate)) {
4872                 timeout = admin.passwordExpirationDate;
4873             }
4874         }
4875         return timeout;
4876     }
4877 
4878     @Override
4879     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
4880         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4881             return 0L;
4882         }
4883         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4884 
4885         final CallerIdentity caller = getCallerIdentity(who);
4886         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4887 
4888         synchronized (getLockObject()) {
4889             return getPasswordExpirationLocked(who, userHandle, parent);
4890         }
4891     }
4892 
4893     @Override
4894     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
4895         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumUpperCase")) {
4896             return;
4897         }
4898         Objects.requireNonNull(who, "ComponentName is null");
4899         final int userId = mInjector.userHandleGetCallingUserId();
4900         synchronized (getLockObject()) {
4901             final ActiveAdmin ap = getActiveAdminForCallerLocked(
4902                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4903             ensureMinimumQuality(
4904                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumUpperCase");
4905             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4906             if (passwordPolicy.upperCase != length) {
4907                 passwordPolicy.upperCase = length;
4908                 updatePasswordValidityCheckpointLocked(userId, parent);
4909                 saveSettingsLocked(userId);
4910             }
4911             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4912         }
4913         DevicePolicyEventLogger
4914                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_UPPER_CASE)
4915                 .setAdmin(who)
4916                 .setInt(length)
4917                 .write();
4918     }
4919 
4920     @Override
4921     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
4922         return getStrictestPasswordRequirement(who, userHandle, parent,
4923                 admin -> admin.mPasswordPolicy.upperCase, PASSWORD_QUALITY_COMPLEX);
4924     }
4925 
4926     @Override
4927     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
4928         if (notSupportedOnAutomotive("setPasswordMinimumLowerCase")) {
4929             return;
4930         }
4931         Objects.requireNonNull(who, "ComponentName is null");
4932         final int userId = mInjector.userHandleGetCallingUserId();
4933         synchronized (getLockObject()) {
4934             ActiveAdmin ap = getActiveAdminForCallerLocked(
4935                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4936             ensureMinimumQuality(
4937                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLowerCase");
4938             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4939             if (passwordPolicy.lowerCase != length) {
4940                 passwordPolicy.lowerCase = length;
4941                 updatePasswordValidityCheckpointLocked(userId, parent);
4942                 saveSettingsLocked(userId);
4943             }
4944             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4945         }
4946         DevicePolicyEventLogger
4947                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LOWER_CASE)
4948                 .setAdmin(who)
4949                 .setInt(length)
4950                 .write();
4951     }
4952 
4953     @Override
4954     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
4955         return getStrictestPasswordRequirement(who, userHandle, parent,
4956                 admin -> admin.mPasswordPolicy.lowerCase, PASSWORD_QUALITY_COMPLEX);
4957     }
4958 
4959     @Override
4960     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
4961         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLetters")) {
4962             return;
4963         }
4964         Objects.requireNonNull(who, "ComponentName is null");
4965         final int userId = mInjector.userHandleGetCallingUserId();
4966         synchronized (getLockObject()) {
4967             ActiveAdmin ap = getActiveAdminForCallerLocked(
4968                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4969             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLetters");
4970             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4971             if (passwordPolicy.letters != length) {
4972                 passwordPolicy.letters = length;
4973                 updatePasswordValidityCheckpointLocked(userId, parent);
4974                 saveSettingsLocked(userId);
4975             }
4976             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4977         }
4978         DevicePolicyEventLogger
4979                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LETTERS)
4980                 .setAdmin(who)
4981                 .setInt(length)
4982                 .write();
4983     }
4984 
4985     @Override
4986     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
4987         return getStrictestPasswordRequirement(who, userHandle, parent,
4988                 admin -> admin.mPasswordPolicy.letters, PASSWORD_QUALITY_COMPLEX);
4989     }
4990 
4991     @Override
4992     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
4993         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNumeric")) {
4994             return;
4995         }
4996         Objects.requireNonNull(who, "ComponentName is null");
4997         final int userId = mInjector.userHandleGetCallingUserId();
4998         synchronized (getLockObject()) {
4999             ActiveAdmin ap = getActiveAdminForCallerLocked(
5000                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5001             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNumeric");
5002             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
5003             if (passwordPolicy.numeric != length) {
5004                 passwordPolicy.numeric = length;
5005                 updatePasswordValidityCheckpointLocked(userId, parent);
5006                 saveSettingsLocked(userId);
5007             }
5008             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
5009         }
5010         DevicePolicyEventLogger
5011                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NUMERIC)
5012                 .setAdmin(who)
5013                 .setInt(length)
5014                 .write();
5015     }
5016 
5017     @Override
5018     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
5019         return getStrictestPasswordRequirement(who, userHandle, parent,
5020                 admin -> admin.mPasswordPolicy.numeric, PASSWORD_QUALITY_COMPLEX);
5021     }
5022 
5023     @Override
5024     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
5025         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumSymbols")) {
5026             return;
5027         }
5028         Objects.requireNonNull(who, "ComponentName is null");
5029         final int userId = mInjector.userHandleGetCallingUserId();
5030         synchronized (getLockObject()) {
5031             ActiveAdmin ap = getActiveAdminForCallerLocked(
5032                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5033             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumSymbols");
5034             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
5035             if (passwordPolicy.symbols != length) {
5036                 ap.mPasswordPolicy.symbols = length;
5037                 updatePasswordValidityCheckpointLocked(userId, parent);
5038                 saveSettingsLocked(userId);
5039             }
5040             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
5041         }
5042         DevicePolicyEventLogger
5043                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_SYMBOLS)
5044                 .setAdmin(who)
5045                 .setInt(length)
5046                 .write();
5047     }
5048 
5049     @Override
5050     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
5051         return getStrictestPasswordRequirement(who, userHandle, parent,
5052                 admin -> admin.mPasswordPolicy.symbols, PASSWORD_QUALITY_COMPLEX);
5053     }
5054 
5055     @Override
5056     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
5057         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNonLetter")) {
5058             return;
5059         }
5060         Objects.requireNonNull(who, "ComponentName is null");
5061         final int userId = mInjector.userHandleGetCallingUserId();
5062         synchronized (getLockObject()) {
5063             ActiveAdmin ap = getActiveAdminForCallerLocked(
5064                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5065             ensureMinimumQuality(
5066                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNonLetter");
5067             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
5068             if (passwordPolicy.nonLetter != length) {
5069                 ap.mPasswordPolicy.nonLetter = length;
5070                 updatePasswordValidityCheckpointLocked(userId, parent);
5071                 saveSettingsLocked(userId);
5072             }
5073             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
5074         }
5075         DevicePolicyEventLogger
5076                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NON_LETTER)
5077                 .setAdmin(who)
5078                 .setInt(length)
5079                 .write();
5080     }
5081 
5082     @Override
5083     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
5084         return getStrictestPasswordRequirement(who, userHandle, parent,
5085                 admin -> admin.mPasswordPolicy.nonLetter, PASSWORD_QUALITY_COMPLEX);
5086     }
5087 
5088     /**
5089      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
5090      */
5091     private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
5092             boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
5093         if (!mHasFeature) {
5094             return 0;
5095         }
5096         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5097 
5098         final CallerIdentity caller = getCallerIdentity(who);
5099         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5100 
5101         synchronized (getLockObject()) {
5102             if (who != null) {
5103                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5104                 return admin != null ? getter.apply(admin) : 0;
5105             }
5106 
5107             int maxValue = 0;
5108             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5109                     getProfileParentUserIfRequested(userHandle, parent));
5110             final int N = admins.size();
5111             for (int i = 0; i < N; i++) {
5112                 final ActiveAdmin admin = admins.get(i);
5113                 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
5114                     continue;
5115                 }
5116                 final Integer adminValue = getter.apply(admin);
5117                 if (adminValue > maxValue) {
5118                     maxValue = adminValue;
5119                 }
5120             }
5121             return maxValue;
5122         }
5123     }
5124 
5125     /**
5126      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
5127      */
5128     @Override
5129     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
5130             boolean deviceWideOnly) {
5131         final CallerIdentity caller = getCallerIdentity();
5132         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)
5133                 && (isSystemUid(caller) || hasCallingOrSelfPermission(
5134                 permission.SET_INITIAL_LOCK)));
5135         return getPasswordMinimumMetricsUnchecked(userHandle, deviceWideOnly);
5136     }
5137 
5138     private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId) {
5139         return getPasswordMinimumMetricsUnchecked(userId, false);
5140     }
5141 
5142     private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId,
5143             boolean deviceWideOnly) {
5144         if (!mHasFeature) {
5145             new PasswordMetrics(CREDENTIAL_TYPE_NONE);
5146         }
5147         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
5148         if (deviceWideOnly) {
5149             Preconditions.checkArgument(!isManagedProfile(userId));
5150         }
5151 
5152         ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>();
5153         final List<ActiveAdmin> admins;
5154         synchronized (getLockObject()) {
5155             if (deviceWideOnly) {
5156                 admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userId,
5157                         /* shouldIncludeProfileAdmins */ (user) -> false);
5158             } else {
5159                 admins = getActiveAdminsForLockscreenPoliciesLocked(userId);
5160             }
5161             for (ActiveAdmin admin : admins) {
5162                 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
5163             }
5164         }
5165         return PasswordMetrics.merge(adminMetrics);
5166     }
5167 
5168     @Override
5169     public boolean isActivePasswordSufficient(
5170             String callerPackageName, int userHandle, boolean parent) {
5171         if (!mHasFeature) {
5172             return true;
5173         }
5174         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5175 
5176         final CallerIdentity caller = getCallerIdentity();
5177         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5178         enforceUserUnlocked(userHandle, parent);
5179 
5180         synchronized (getLockObject()) {
5181             if (isPermissionCheckFlagEnabled()) {
5182                 int affectedUser = parent ? getProfileParentId(userHandle) : userHandle;
5183                 enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5184                         callerPackageName, affectedUser);
5185             } else {
5186                 // This API can only be called by an active device admin,
5187                 // so try to retrieve it to check that the caller is one.
5188                 getActiveAdminForCallerLocked(
5189                         null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5190             }
5191 
5192             int credentialOwner = getCredentialOwner(userHandle, parent);
5193             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
5194             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
5195             final int userToCheck = getProfileParentUserIfRequested(userHandle, parent);
5196             boolean activePasswordSufficientForUserLocked = isActivePasswordSufficientForUserLocked(
5197                     policy.mPasswordValidAtLastCheckpoint, metrics, userToCheck);
5198             return activePasswordSufficientForUserLocked;
5199         }
5200     }
5201 
5202     @Override
5203     public boolean isActivePasswordSufficientForDeviceRequirement() {
5204         if (!mHasFeature) {
5205             return true;
5206         }
5207         final CallerIdentity caller = getCallerIdentity();
5208         Preconditions.checkCallAuthorization(isProfileOwner(caller));
5209 
5210         final int profileUserId = caller.getUserId();
5211         Preconditions.checkCallingUser(isManagedProfile(profileUserId));
5212 
5213         // This method is always called on the parent DPM instance to check if its password (i.e.
5214         // the device password) is sufficient for all explicit password requirement set on it
5215         // So retrieve the parent user Id to which the device password belongs.
5216         final int parentUser = getProfileParentId(profileUserId);
5217         enforceUserUnlocked(parentUser);
5218 
5219         final boolean isSufficient;
5220         synchronized (getLockObject()) {
5221 
5222             int complexity = getAggregatedPasswordComplexityLocked(parentUser, true);
5223             PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(parentUser, true);
5224 
5225             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(parentUser);
5226             final List<PasswordValidationError> passwordValidationErrors =
5227                     PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics);
5228             isSufficient = passwordValidationErrors.isEmpty();
5229         }
5230         DevicePolicyEventLogger
5231                 .createEvent(DevicePolicyEnums.IS_ACTIVE_PASSWORD_SUFFICIENT_FOR_DEVICE)
5232                 .setStrings(mOwners.getProfileOwnerComponent(caller.getUserId()).getPackageName())
5233                 .write();
5234         return isSufficient;
5235     }
5236 
5237     @Override
5238     public boolean isUsingUnifiedPassword(ComponentName admin) {
5239         if (!mHasFeature) {
5240             return true;
5241         }
5242         Objects.requireNonNull(admin, "ComponentName is null");
5243 
5244         final CallerIdentity caller = getCallerIdentity(admin);
5245         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
5246                 || isProfileOwner(caller));
5247         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
5248 
5249         return !isSeparateProfileChallengeEnabled(caller.getUserId());
5250     }
5251 
5252     @Override
5253     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
5254         if (!mHasFeature) {
5255             return true;
5256         }
5257         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5258 
5259         final CallerIdentity caller = getCallerIdentity();
5260         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5261         Preconditions.checkCallAuthorization(!isManagedProfile(userHandle),
5262                 "You can not check password sufficiency for a managed profile, userId = %d",
5263                 userHandle);
5264         enforceUserUnlocked(userHandle);
5265 
5266         synchronized (getLockObject()) {
5267             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(userHandle);
5268 
5269             // Combine password policies across the user and its profiles. Profile admins are
5270             // included if the profile is to be unified or currently has unified challenge
5271             List<ActiveAdmin> admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
5272                     /* shouldIncludeProfileAdmins */ (user) -> user.id == profileUser
5273                     || !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
5274             ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>(admins.size());
5275             int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE;
5276             for (ActiveAdmin admin : admins) {
5277                 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
5278                 maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity);
5279             }
5280             return PasswordMetrics.validatePasswordMetrics(PasswordMetrics.merge(adminMetrics),
5281                     maxRequiredComplexity, metrics).isEmpty();
5282         }
5283     }
5284 
5285     private boolean isActivePasswordSufficientForUserLocked(
5286             boolean passwordValidAtLastCheckpoint, @Nullable PasswordMetrics metrics,
5287             int userHandle) {
5288         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) {
5289             // Before user enters their password for the first time after a reboot, return the
5290             // value of this flag, which tells us whether the password was valid the last time
5291             // settings were saved.  If DPC changes password requirements on boot so that the
5292             // current password no longer meets the requirements, this value will be stale until
5293             // the next time the password is entered.
5294             return passwordValidAtLastCheckpoint;
5295         }
5296 
5297         if (metrics == null) {
5298             // Called on a FBE device when the user password exists but its metrics is unknown.
5299             // This shouldn't happen since we enforce the user to be unlocked (which would result
5300             // in the metrics known to the framework on a FBE device) at all call sites.
5301             throw new IllegalStateException("isActivePasswordSufficient called on FBE-locked user");
5302         }
5303 
5304         return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle);
5305     }
5306 
5307     /**
5308      * Returns {@code true} if the password represented by the {@code metrics} argument
5309      * sufficiently fulfills the password requirements for the user corresponding to
5310      * {@code userId}.
5311      */
5312     private boolean isPasswordSufficientForUserWithoutCheckpointLocked(
5313             @NonNull PasswordMetrics metrics, @UserIdInt int userId) {
5314         final int complexity = getAggregatedPasswordComplexityLocked(userId);
5315         PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userId);
5316         final List<PasswordValidationError> passwordValidationErrors =
5317                 PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics);
5318         return passwordValidationErrors.isEmpty();
5319     }
5320 
5321     @Override
5322     @PasswordComplexity
5323     public int getPasswordComplexity(boolean parent) {
5324         final CallerIdentity caller = getCallerIdentity();
5325         DevicePolicyEventLogger
5326                 .createEvent(DevicePolicyEnums.GET_USER_PASSWORD_COMPLEXITY_LEVEL)
5327                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT,
5328                         mInjector.getPackageManager().getPackagesForUid(caller.getUid()))
5329                 .write();
5330 
5331         enforceUserUnlocked(caller.getUserId());
5332         if (parent) {
5333             Preconditions.checkCallAuthorization(
5334                     isDefaultDeviceOwner(caller) || isProfileOwner(caller) || isSystemUid(caller),
5335                     "Only profile owner, device owner and system may call this method on parent.");
5336         } else {
5337             if (isPermissionCheckFlagEnabled()) {
5338                 Preconditions.checkCallAuthorization(
5339                         hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY)
5340                                 || hasCallingOrSelfPermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS)
5341                                 || isDefaultDeviceOwner(caller) || isProfileOwner(caller),
5342                         "Must have " + REQUEST_PASSWORD_COMPLEXITY + " or " +
5343                                 MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS
5344                                 + " permissions, or be a profile owner or device owner.");
5345             } else {
5346                 Preconditions.checkCallAuthorization(
5347                         hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY)
5348                                 || isDefaultDeviceOwner(caller) || isProfileOwner(caller),
5349                         "Must have " + REQUEST_PASSWORD_COMPLEXITY
5350                                 + " permission, or be a profile owner or device owner.");
5351             }
5352         }
5353 
5354         synchronized (getLockObject()) {
5355             final int credentialOwner = getCredentialOwner(caller.getUserId(), parent);
5356             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
5357             return metrics == null ? PASSWORD_COMPLEXITY_NONE : metrics.determineComplexity();
5358         }
5359     }
5360 
5361     @Override
5362     public void setRequiredPasswordComplexity(
5363             String callerPackageName, int passwordComplexity, boolean calledOnParent) {
5364         if (!mHasFeature) {
5365             return;
5366         }
5367         final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW,
5368                 PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH);
5369         Preconditions.checkArgument(allowedModes.contains(passwordComplexity),
5370                 "Provided complexity is not one of the allowed values.");
5371 
5372         CallerIdentity caller = getCallerIdentity(callerPackageName);
5373         if (!isPermissionCheckFlagEnabled()) {
5374             Preconditions.checkCallAuthorization(
5375                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
5376             Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
5377         }
5378 
5379         synchronized (getLockObject()) {
5380             ActiveAdmin admin;
5381             if (isPermissionCheckFlagEnabled()) {
5382                 // TODO: Make sure this returns the parent of the fake admin
5383                 // TODO: Deal with null componentname
5384                 int affectedUser = calledOnParent
5385                         ? getProfileParentId(caller.getUserId()) : caller.getUserId();
5386                 admin = enforcePermissionAndGetEnforcingAdmin(
5387                         null, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5388                         caller.getPackageName(), affectedUser).getActiveAdmin();
5389             } else {
5390                 admin = getParentOfAdminIfRequired(
5391                         getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), calledOnParent);
5392             }
5393 
5394             if (admin.mPasswordComplexity != passwordComplexity) {
5395                 // We require the caller to explicitly clear any password quality requirements set
5396                 // on the parent DPM instance, to avoid the case where password requirements are
5397                 // specified in the form of quality on the parent but complexity on the profile
5398                 // itself.
5399                 if (!calledOnParent) {
5400                     final boolean hasQualityRequirementsOnParent = admin.hasParentActiveAdmin()
5401                             && admin.getParentActiveAdmin().mPasswordPolicy.quality
5402                             != PASSWORD_QUALITY_UNSPECIFIED;
5403                     Preconditions.checkState(!hasQualityRequirementsOnParent,
5404                             "Password quality is set on the parent when attempting to set password"
5405                             + "complexity. Clear the quality by setting the password quality "
5406                             + "on the parent to PASSWORD_QUALITY_UNSPECIFIED first");
5407                 }
5408 
5409                 mInjector.binderWithCleanCallingIdentity(() -> {
5410                     admin.mPasswordComplexity = passwordComplexity;
5411                     // Reset the password policy.
5412                     admin.mPasswordPolicy = new PasswordPolicy();
5413                     updatePasswordValidityCheckpointLocked(caller.getUserId(), calledOnParent);
5414                     updatePasswordQualityCacheForUserGroup(caller.getUserId());
5415                     saveSettingsLocked(caller.getUserId());
5416                 });
5417 
5418 
5419                 //TODO(b/276855301): caller.getPackageName() will be null when the coexistence flags are
5420                 // turned off. Change back to caller.getPackageName once this API is unflagged.
5421                 DevicePolicyEventLogger
5422                         .createEvent(DevicePolicyEnums.SET_PASSWORD_COMPLEXITY)
5423                         .setAdmin(admin.info.getPackageName())
5424                         .setInt(passwordComplexity)
5425                         .setBoolean(calledOnParent)
5426                         .write();
5427             }
5428             logPasswordComplexityRequiredIfSecurityLogEnabled(caller.getPackageName(),
5429                     caller.getUserId(), calledOnParent, passwordComplexity);
5430         }
5431     }
5432 
5433     private void logPasswordComplexityRequiredIfSecurityLogEnabled(String adminPackageName,
5434             int userId,
5435             boolean parent, int complexity) {
5436         if (SecurityLog.isLoggingEnabled()) {
5437             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
5438             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_REQUIRED,
5439                     adminPackageName, userId, affectedUserId, complexity);
5440         }
5441     }
5442     @GuardedBy("getLockObject()")
5443     private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle) {
5444         return getAggregatedPasswordComplexityLocked(userHandle, false);
5445     }
5446 
5447     @GuardedBy("getLockObject()")
5448     private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle,
5449             boolean deviceWideOnly) {
5450         ensureLocked();
5451         final List<ActiveAdmin> admins;
5452         if (deviceWideOnly) {
5453             admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
5454                     /* shouldIncludeProfileAdmins */ (user) -> false);
5455         } else {
5456             admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
5457         }
5458         int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE;
5459         for (ActiveAdmin admin : admins) {
5460             maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity);
5461         }
5462         return maxRequiredComplexity;
5463     }
5464 
5465     @Override
5466     public int getRequiredPasswordComplexity(String callerPackageName, boolean calledOnParent) {
5467         if (!mHasFeature) {
5468             return PASSWORD_COMPLEXITY_NONE;
5469         }
5470 
5471         final CallerIdentity caller = getCallerIdentity();
5472 
5473         if (isPermissionCheckFlagEnabled()) {
5474             int affectedUser = calledOnParent ? getProfileParentId(caller.getUserId())
5475                     : caller.getUserId();
5476             enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5477                     callerPackageName, affectedUser);
5478         } else {
5479             Preconditions.checkCallAuthorization(
5480                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
5481 
5482             Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
5483         }
5484 
5485         synchronized (getLockObject()) {
5486             final ActiveAdmin requiredAdmin = getParentOfAdminIfRequired(
5487                     getDeviceOrProfileOwnerAdminLocked(caller.getUserId()), calledOnParent);
5488             return requiredAdmin.mPasswordComplexity;
5489         }
5490     }
5491 
5492     @Override
5493     public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
5494         if (!mHasFeature) {
5495             return PASSWORD_COMPLEXITY_NONE;
5496         }
5497 
5498         final CallerIdentity caller = getCallerIdentity();
5499         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
5500 
5501         synchronized (getLockObject()) {
5502             return getAggregatedPasswordComplexityLocked(userId, deviceWideOnly);
5503         }
5504     }
5505 
5506 
5507     @Override
5508     public int getCurrentFailedPasswordAttempts(
5509             String callerPackageName, int userHandle, boolean parent) {
5510         if (!mLockPatternUtils.hasSecureLockScreen()) {
5511             return 0;
5512         }
5513         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5514 
5515         final CallerIdentity caller = getCallerIdentity();
5516         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5517 
5518         synchronized (getLockObject()) {
5519             if (!isSystemUid(caller)) {
5520                 // This API can be called by an active device admin or by keyguard code.
5521                 if (!hasCallingPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)) {
5522                     if (isPermissionCheckFlagEnabled()) {
5523                         int affectedUser = parent ? getProfileParentId(userHandle) : userHandle;
5524                         enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5525                                 callerPackageName, affectedUser);
5526                     } else {
5527                         getActiveAdminForCallerLocked(
5528                                 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
5529                     }
5530                 }
5531             }
5532 
5533             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
5534 
5535             return policy.mFailedPasswordAttempts;
5536         }
5537     }
5538 
5539     @Override
5540     public void setMaximumFailedPasswordsForWipe(
5541             ComponentName who, String callerPackageName, int num, boolean parent) {
5542         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5543             return;
5544         }
5545 
5546         if (!isPermissionCheckFlagEnabled()) {
5547             Objects.requireNonNull(who, "ComponentName is null");
5548         }
5549 
5550 
5551         int userId = mInjector.userHandleGetCallingUserId();
5552         int affectedUserId = parent ? getProfileParentId(userId) : userId;
5553 
5554         synchronized (getLockObject()) {
5555             ActiveAdmin ap;
5556             if (isPermissionCheckFlagEnabled()) {
5557                 CallerIdentity caller = getCallerIdentity(who, callerPackageName);
5558                 ap = enforcePermissionAndGetEnforcingAdmin(
5559                         who,
5560                         /*permission=*/ MANAGE_DEVICE_POLICY_WIPE_DATA,
5561                         /* adminPolicy=*/ DeviceAdminInfo.USES_POLICY_WIPE_DATA,
5562                         caller.getPackageName(), affectedUserId).getActiveAdmin();
5563             } else {
5564                 // This API can only be called by an active device admin,
5565                 // so try to retrieve it to check that the caller is one.
5566                 getActiveAdminForCallerLocked(
5567                         who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
5568                 ap = getActiveAdminForCallerLocked(
5569                         who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
5570             }
5571 
5572             if (ap.maximumFailedPasswordsForWipe != num) {
5573                 ap.maximumFailedPasswordsForWipe = num;
5574                 saveSettingsLocked(userId);
5575             }
5576         }
5577         if (SecurityLog.isLoggingEnabled()) {
5578             SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, callerPackageName,
5579                     userId, affectedUserId, num);
5580         }
5581     }
5582 
5583     @Override
5584     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
5585         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5586             return 0;
5587         }
5588         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5589 
5590         final CallerIdentity caller = getCallerIdentity();
5591         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5592         // System caller can query policy for a particular admin.
5593         Preconditions.checkCallAuthorization(
5594                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
5595                         || canQueryAdminPolicy(caller));
5596 
5597         synchronized (getLockObject()) {
5598             ActiveAdmin admin = (who != null)
5599                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
5600                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
5601             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
5602         }
5603     }
5604 
5605     @Override
5606     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
5607         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5608             return UserHandle.USER_NULL;
5609         }
5610         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5611 
5612         final CallerIdentity caller = getCallerIdentity();
5613         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5614 
5615         synchronized (getLockObject()) {
5616             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5617                     userHandle, parent);
5618             return admin != null ? getUserIdToWipeForFailedPasswords(admin) : UserHandle.USER_NULL;
5619         }
5620     }
5621 
5622     /**
5623      * Returns the admin with the strictest policy on maximum failed passwords for:
5624      * <ul>
5625      *   <li>this user if it has a separate profile challenge, or
5626      *   <li>this user and all profiles that don't have their own challenge otherwise.
5627      * </ul>
5628      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
5629      * the primary profile. Policy of a PO on an organization-owned device applies to the primary
5630      * profile.
5631      * Returns {@code null} if no participating admin has that policy set.
5632      */
5633     @GuardedBy("getLockObject()")
5634     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
5635             int userHandle, boolean parent) {
5636         int count = 0;
5637         ActiveAdmin strictestAdmin = null;
5638 
5639         // Return the strictest policy across all participating admins.
5640         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5641                 getProfileParentUserIfRequested(userHandle, parent));
5642         final int N = admins.size();
5643         for (int i = 0; i < N; i++) {
5644             ActiveAdmin admin = admins.get(i);
5645             if (admin.maximumFailedPasswordsForWipe ==
5646                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
5647                 continue;  // No max number of failed passwords policy set for this profile.
5648             }
5649 
5650             // We always favor the primary profile if several profiles have the same value set.
5651             final int userId = getUserIdToWipeForFailedPasswords(admin);
5652             if (count == 0 ||
5653                     count > admin.maximumFailedPasswordsForWipe ||
5654                     (count == admin.maximumFailedPasswordsForWipe &&
5655                             getUserInfo(userId).isPrimary())) {
5656                 count = admin.maximumFailedPasswordsForWipe;
5657                 strictestAdmin = admin;
5658             }
5659         }
5660         return strictestAdmin;
5661     }
5662 
5663     private UserInfo getUserInfo(@UserIdInt int userId) {
5664         return mInjector.binderWithCleanCallingIdentity(() -> mUserManager.getUserInfo(userId));
5665     }
5666 
5667     private boolean setPasswordPrivileged(@NonNull String password, int flags,
5668             CallerIdentity caller) {
5669         // Only allow setting password on an unsecured user
5670         if (isLockScreenSecureUnchecked(caller.getUserId())) {
5671             throw new SecurityException("Cannot change current password");
5672         }
5673         return resetPasswordInternal(password, 0, null, flags, caller);
5674     }
5675 
5676     @Override
5677     public boolean resetPassword(@Nullable String password, int flags) throws RemoteException {
5678         if (!mLockPatternUtils.hasSecureLockScreen()) {
5679             Slogf.w(LOG_TAG, "Cannot reset password when the device has no lock screen");
5680             return false;
5681         }
5682         if (password == null) password = "";
5683         final CallerIdentity caller = getCallerIdentity();
5684         final int userHandle = caller.getUserId();
5685 
5686         // As of R, only privileged caller holding RESET_PASSWORD can call resetPassword() to
5687         // set password to an unsecured user.
5688         if (hasCallingPermission(permission.RESET_PASSWORD)) {
5689             final boolean result = setPasswordPrivileged(password, flags, caller);
5690             if (result) {
5691                 DevicePolicyEventLogger
5692                         .createEvent(DevicePolicyEnums.RESET_PASSWORD)
5693                         .write();
5694             }
5695             return result;
5696         }
5697 
5698         // If caller has PO (or DO) throw or fail silently depending on its target SDK level.
5699         if (isDefaultDeviceOwner(caller) || isProfileOwner(caller)) {
5700             synchronized (getLockObject()) {
5701                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
5702                 if (getTargetSdk(admin.info.getPackageName(), userHandle) < Build.VERSION_CODES.O) {
5703                     Slogf.e(LOG_TAG, "DPC can no longer call resetPassword()");
5704                     return false;
5705                 }
5706                 throw new SecurityException("Device admin can no longer call resetPassword()");
5707             }
5708         }
5709 
5710         // Caller is not DO or PO, could either be unauthorized or Device Admin.
5711         synchronized (getLockObject()) {
5712             // Legacy device admin cannot call resetPassword either
5713             ActiveAdmin admin = getActiveAdminForCallerLocked(
5714                     null, DeviceAdminInfo.USES_POLICY_RESET_PASSWORD, false);
5715             Preconditions.checkCallAuthorization(admin != null,
5716                     "Unauthorized caller cannot call resetPassword.");
5717             if (getTargetSdk(admin.info.getPackageName(),
5718                     userHandle) <= android.os.Build.VERSION_CODES.M) {
5719                 Slogf.e(LOG_TAG, "Device admin can no longer call resetPassword()");
5720                 return false;
5721             }
5722             throw new SecurityException("Device admin can no longer call resetPassword()");
5723         }
5724     }
5725 
5726     private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
5727             int flags, CallerIdentity caller) {
5728         final int callingUid = caller.getUid();
5729         final int userHandle = UserHandle.getUserId(callingUid);
5730         final boolean isPin = PasswordMetrics.isNumericOnly(password);
5731         synchronized (getLockObject()) {
5732             final PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userHandle);
5733             final List<PasswordValidationError> validationErrors;
5734             final int complexity = getAggregatedPasswordComplexityLocked(userHandle);
5735             // TODO: Consider changing validation API to take LockscreenCredential.
5736             if (password.isEmpty()) {
5737                 validationErrors = PasswordMetrics.validatePasswordMetrics(
5738                         minMetrics, complexity, new PasswordMetrics(CREDENTIAL_TYPE_NONE));
5739             } else {
5740                 // TODO(b/120484642): remove getBytes() below
5741                 validationErrors = PasswordMetrics.validatePassword(
5742                         minMetrics, complexity, isPin, password.getBytes());
5743             }
5744 
5745             if (!validationErrors.isEmpty()) {
5746                 Slogf.w(LOG_TAG, "Failed to reset password due to constraint violation: %s",
5747                         validationErrors.get(0));
5748                 return false;
5749             }
5750         }
5751 
5752         DevicePolicyData policy = getUserData(userHandle);
5753         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
5754             Slogf.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
5755             return false;
5756         }
5757 
5758         boolean callerIsDeviceOwnerAdmin = isDefaultDeviceOwner(caller);
5759         boolean doNotAskCredentialsOnBoot =
5760                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
5761         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
5762             setDoNotAskCredentialsOnBoot();
5763         }
5764 
5765         // Don't do this with the lock held, because it is going to call
5766         // back in to the service.
5767         final long ident = mInjector.binderClearCallingIdentity();
5768         final LockscreenCredential newCredential;
5769         if (isPin) {
5770             newCredential = LockscreenCredential.createPin(password);
5771         } else {
5772             newCredential = LockscreenCredential.createPasswordOrNone(password);
5773         }
5774         try {
5775             if (tokenHandle == 0 || token == null) {
5776                 if (!mLockPatternUtils.setLockCredential(newCredential,
5777                         LockscreenCredential.createNone(), userHandle)) {
5778                     return false;
5779                 }
5780             } else {
5781                 if (!mLockPatternUtils.setLockCredentialWithToken(newCredential, tokenHandle,
5782                         token, userHandle)) {
5783                     return false;
5784                 }
5785             }
5786             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
5787             if (requireEntry) {
5788                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
5789                         UserHandle.USER_ALL);
5790             }
5791             synchronized (getLockObject()) {
5792                 int newOwner = requireEntry ? callingUid : -1;
5793                 if (policy.mPasswordOwner != newOwner) {
5794                     policy.mPasswordOwner = newOwner;
5795                     saveSettingsLocked(userHandle);
5796                 }
5797             }
5798         } finally {
5799             mInjector.binderRestoreCallingIdentity(ident);
5800         }
5801         return true;
5802     }
5803 
5804     private boolean isLockScreenSecureUnchecked(int userId) {
5805         return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.isSecure(userId));
5806     }
5807 
5808     private void setDoNotAskCredentialsOnBoot() {
5809         synchronized (getLockObject()) {
5810             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
5811             if (!policyData.mDoNotAskCredentialsOnBoot) {
5812                 policyData.mDoNotAskCredentialsOnBoot = true;
5813                 saveSettingsLocked(UserHandle.USER_SYSTEM);
5814             }
5815         }
5816     }
5817 
5818     @Override
5819     public boolean getDoNotAskCredentialsOnBoot() {
5820         Preconditions.checkCallAuthorization(
5821                 hasCallingOrSelfPermission(permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT));
5822         synchronized (getLockObject()) {
5823             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
5824             return policyData.mDoNotAskCredentialsOnBoot;
5825         }
5826     }
5827 
5828     @Override
5829     public void setMaximumTimeToLock(ComponentName who, String callerPackageName,
5830             long timeMs, boolean parent) {
5831         if (!mHasFeature) {
5832             return;
5833         }
5834         if (!isPermissionCheckFlagEnabled()) {
5835             Objects.requireNonNull(who, "ComponentName is null");
5836         }
5837         int userHandle = mInjector.userHandleGetCallingUserId();
5838         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
5839         synchronized (getLockObject()) {
5840             ActiveAdmin ap;
5841             if (isPermissionCheckFlagEnabled()) {
5842                 CallerIdentity caller = getCallerIdentity(who, callerPackageName);
5843                 ap = enforcePermissionAndGetEnforcingAdmin(
5844                         who,
5845                         /*permission=*/ MANAGE_DEVICE_POLICY_LOCK,
5846                         /*AdminPolicy=*/DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
5847                         caller.getPackageName(),
5848                         affectedUserId).getActiveAdmin();
5849             } else {
5850                 ap = getActiveAdminForCallerLocked(
5851                         who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
5852             }
5853 
5854             if (ap.maximumTimeToUnlock != timeMs) {
5855                 ap.maximumTimeToUnlock = timeMs;
5856                 saveSettingsLocked(userHandle);
5857                 updateMaximumTimeToLockLocked(userHandle);
5858             }
5859         }
5860         if (SecurityLog.isLoggingEnabled()) {
5861             SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
5862                     callerPackageName, userHandle, affectedUserId, timeMs);
5863         }
5864     }
5865 
5866     @GuardedBy("getLockObject()")
5867     private void updateMaximumTimeToLockLocked(@UserIdInt int userId) {
5868         // Update the profile's timeout
5869         if (isManagedProfile(userId)) {
5870             updateProfileLockTimeoutLocked(userId);
5871         }
5872 
5873         mInjector.binderWithCleanCallingIdentity(() -> {
5874             // Update the device timeout
5875             final int parentId = getProfileParentId(userId);
5876             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(
5877                     getActiveAdminsForLockscreenPoliciesLocked(parentId));
5878 
5879             final DevicePolicyData policy = getUserDataUnchecked(parentId);
5880             if (policy.mLastMaximumTimeToLock == timeMs) {
5881                 return;
5882             }
5883             policy.mLastMaximumTimeToLock = timeMs;
5884 
5885             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
5886                 // Make sure KEEP_SCREEN_ON is disabled, since that
5887                 // would allow bypassing of the maximum time to lock.
5888                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
5889             }
5890             getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(parentId, timeMs);
5891         });
5892     }
5893 
5894     @GuardedBy("getLockObject()")
5895     private void updateProfileLockTimeoutLocked(@UserIdInt int userId) {
5896         final long timeMs;
5897         if (isSeparateProfileChallengeEnabled(userId)) {
5898             timeMs = getMaximumTimeToLockPolicyFromAdmins(
5899                     getActiveAdminsForLockscreenPoliciesLocked(userId));
5900         } else {
5901             timeMs = Long.MAX_VALUE;
5902         }
5903 
5904         final DevicePolicyData policy = getUserDataUnchecked(userId);
5905         if (policy.mLastMaximumTimeToLock == timeMs) {
5906             return;
5907         }
5908         policy.mLastMaximumTimeToLock = timeMs;
5909 
5910         mInjector.binderWithCleanCallingIdentity(() ->
5911                 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
5912                         userId, policy.mLastMaximumTimeToLock));
5913     }
5914 
5915     @Override
5916     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
5917         if (!mHasFeature) {
5918             return 0;
5919         }
5920         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5921 
5922         final CallerIdentity caller = getCallerIdentity();
5923         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5924         // System caller can query policy for a particular admin.
5925         Preconditions.checkCallAuthorization(
5926                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
5927                         || canQueryAdminPolicy(caller));
5928 
5929         synchronized (getLockObject()) {
5930             if (who != null) {
5931                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5932                 return admin != null ? admin.maximumTimeToUnlock : 0;
5933             }
5934             // Return the strictest policy across all participating admins.
5935             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5936                     getProfileParentUserIfRequested(userHandle, parent));
5937             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins);
5938             return timeMs == Long.MAX_VALUE ? 0 : timeMs;
5939         }
5940     }
5941 
5942     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
5943         long time = Long.MAX_VALUE;
5944         for (final ActiveAdmin admin : admins) {
5945             if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) {
5946                 time = admin.maximumTimeToUnlock;
5947             }
5948         }
5949         return time;
5950     }
5951 
5952     @Override
5953     public void setRequiredStrongAuthTimeout(ComponentName who, String callerPackageName, long timeoutMs,
5954             boolean parent) {
5955         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5956             return;
5957         }
5958         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
5959         CallerIdentity caller;
5960         if (isPermissionCheckFlagEnabled()) {
5961             caller = getCallerIdentity(who, callerPackageName);
5962         } else {
5963             caller = getCallerIdentity(who);
5964             Objects.requireNonNull(who, "ComponentName is null");
5965             Preconditions.checkCallAuthorization(
5966                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
5967         }
5968         // timeoutMs with value 0 means that the admin doesn't participate
5969         // timeoutMs is clamped to the interval in case the internal constants change in the future
5970         final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
5971         if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
5972             timeoutMs = minimumStrongAuthTimeout;
5973         }
5974         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
5975             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5976         }
5977 
5978         final int userHandle = caller.getUserId();
5979         boolean changed = false;
5980         synchronized (getLockObject()) {
5981             ActiveAdmin ap;
5982             if (isPermissionCheckFlagEnabled()) {
5983                 int affectedUser = parent
5984                         ? getProfileParentId(caller.getUserId()) : caller.getUserId();
5985                 ap = enforcePermissionAndGetEnforcingAdmin(
5986                         who, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5987                         caller.getPackageName(), affectedUser).getActiveAdmin();
5988             } else {
5989                 ap = getParentOfAdminIfRequired(
5990                         getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
5991             }
5992             if (ap.strongAuthUnlockTimeout != timeoutMs) {
5993                 ap.strongAuthUnlockTimeout = timeoutMs;
5994                 saveSettingsLocked(userHandle);
5995                 changed = true;
5996             }
5997         }
5998         if (changed) {
5999             mLockSettingsInternal.refreshStrongAuthTimeout(userHandle);
6000             // Refreshes the parent if profile has unified challenge, since the timeout would
6001             // also affect the parent user in this case.
6002             if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
6003                 mLockSettingsInternal.refreshStrongAuthTimeout(getProfileParentId(userHandle));
6004             }
6005         }
6006     }
6007 
6008     /**
6009      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
6010      * admins if who is null.
6011      * Returns 0 if not configured for the provided admin.
6012      */
6013     @Override
6014     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
6015         if (!mHasFeature) {
6016             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6017         }
6018         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
6019 
6020         final CallerIdentity caller = getCallerIdentity(who);
6021         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
6022 
6023         if (!mLockPatternUtils.hasSecureLockScreen()) {
6024             // No strong auth timeout on devices not supporting the
6025             // {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature
6026             return 0;
6027         }
6028         synchronized (getLockObject()) {
6029             if (who != null) {
6030                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
6031                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
6032             }
6033 
6034             // Return the strictest policy across all participating admins.
6035             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
6036                     getProfileParentUserIfRequested(userId, parent));
6037 
6038             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6039             for (int i = 0; i < admins.size(); i++) {
6040                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
6041                 if (timeout != 0) { // take only participating admins into account
6042                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
6043                 }
6044             }
6045             return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
6046         }
6047     }
6048 
6049     private long getMinimumStrongAuthTimeoutMs() {
6050         if (!mInjector.isBuildDebuggable()) {
6051             return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
6052         }
6053         // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
6054         // name cannot be longer than 31 characters
6055         return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
6056                 MINIMUM_STRONG_AUTH_TIMEOUT_MS),
6057                 MINIMUM_STRONG_AUTH_TIMEOUT_MS);
6058     }
6059 
6060     @Override
6061     public void lockNow(int flags, String callerPackageName, boolean parent) {
6062         CallerIdentity caller;
6063         if (isUnicornFlagEnabled()) {
6064             caller = getCallerIdentity(callerPackageName);
6065         } else {
6066             caller = getCallerIdentity();
6067         }
6068 
6069         final int callingUserId = caller.getUserId();
6070         ComponentName adminComponent = null;
6071         synchronized (getLockObject()) {
6072             ActiveAdmin admin;
6073             // Make sure the caller has any active admin with the right policy or
6074             // the required permission.
6075             if (isUnicornFlagEnabled()) {
6076                 admin = enforcePermissionAndGetEnforcingAdmin(
6077                         /* admin= */ null,
6078                         /* permission= */ MANAGE_DEVICE_POLICY_LOCK,
6079                         USES_POLICY_FORCE_LOCK,
6080                         caller.getPackageName(),
6081                         getAffectedUser(parent)
6082                  ).getActiveAdmin();
6083             } else {
6084                 admin = getActiveAdminOrCheckPermissionForCallerLocked(
6085                         null,
6086                         DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
6087                         parent,
6088                         LOCK_DEVICE);
6089             }
6090             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOCK_NOW);
6091             final long ident = mInjector.binderClearCallingIdentity();
6092             try {
6093                 adminComponent = admin == null ? null : admin.info.getComponent();
6094                 if (adminComponent != null) {
6095                     // For Profile Owners only, callers with only permission not allowed.
6096                     if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
6097                         // Evict key
6098                         Preconditions.checkCallingUser(isManagedProfile(callingUserId));
6099                         Preconditions.checkArgument(!parent,
6100                                 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
6101                         if (!isProfileOwner(adminComponent, callingUserId)) {
6102                             throw new SecurityException("Only profile owner admins can set "
6103                                     + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
6104                         }
6105                         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
6106                             throw new UnsupportedOperationException(
6107                                     "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE"
6108                                         + " devices");
6109                         }
6110                         mUserManager.evictCredentialEncryptionKey(callingUserId);
6111                     }
6112                 }
6113 
6114                 // Lock all users unless this is a managed profile with a separate challenge
6115                 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
6116                         ? UserHandle.USER_ALL : callingUserId);
6117                 mLockPatternUtils.requireStrongAuth(
6118                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
6119 
6120                 // Require authentication for the device or profile
6121                 if (userToLock == UserHandle.USER_ALL) {
6122                     if (mIsAutomotive) {
6123                         if (VERBOSE_LOG) {
6124                             Slogf.v(LOG_TAG, "lockNow(): not powering off display on automotive"
6125                                     + " build");
6126                         }
6127                     } else {
6128                         // Power off the display
6129                         mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
6130                                 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
6131                     }
6132                     mInjector.getIWindowManager().lockNow(null);
6133                 } else {
6134                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
6135                 }
6136 
6137                 if (SecurityLog.isLoggingEnabled() && adminComponent != null) {
6138                     final int affectedUserId =
6139                             parent ? getProfileParentId(callingUserId) : callingUserId;
6140                     SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK,
6141                             adminComponent.getPackageName(), callingUserId, affectedUserId);
6142                 }
6143             } catch (RemoteException e) {
6144             } finally {
6145                 mInjector.binderRestoreCallingIdentity(ident);
6146             }
6147         }
6148         DevicePolicyEventLogger
6149                 .createEvent(DevicePolicyEnums.LOCK_NOW)
6150                 .setAdmin(adminComponent)
6151                 .setInt(flags)
6152                 .write();
6153     }
6154 
6155     @Override
6156     public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
6157         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6158         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
6159     }
6160 
6161     private boolean canManageCaCerts(CallerIdentity caller) {
6162         return (caller.hasAdminComponent() && (isDefaultDeviceOwner(caller)
6163                 || isProfileOwner(caller)))
6164                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_INSTALL))
6165                 || hasCallingOrSelfPermission(MANAGE_CA_CERTIFICATES);
6166     }
6167 
6168     @Override
6169     public boolean approveCaCert(String alias, int userId, boolean approval) {
6170         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
6171 
6172         synchronized (getLockObject()) {
6173             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
6174             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
6175             if (!changed) {
6176                 return false;
6177             }
6178             saveSettingsLocked(userId);
6179         }
6180         mCertificateMonitor.onCertificateApprovalsChanged(userId);
6181         return true;
6182     }
6183 
6184     @Override
6185     public boolean isCaCertApproved(String alias, int userId) {
6186         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
6187 
6188         synchronized (getLockObject()) {
6189             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
6190         }
6191     }
6192 
6193     private Set<Integer> removeCaApprovalsIfNeeded(int userId) {
6194         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
6195         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
6196             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
6197             if (userInfo.isManagedProfile()){
6198                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
6199             }
6200             if (!isSecure) {
6201                 synchronized (getLockObject()) {
6202                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
6203                     affectedUserIds.add(userInfo.id);
6204                 }
6205                 mCertificateMonitor.onCertificateApprovalsChanged(userId);
6206             }
6207         }
6208         return affectedUserIds;
6209     }
6210 
6211     @Override
6212     public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) {
6213         if (!mHasFeature) {
6214             return false;
6215         }
6216         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
6217         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
6218         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_CA_CERT);
6219 
6220         final String alias = mInjector.binderWithCleanCallingIdentity(() -> {
6221             String installedAlias = mCertificateMonitor.installCaCert(
6222                     caller.getUserHandle(), certBuffer);
6223             DevicePolicyEventLogger
6224                     .createEvent(DevicePolicyEnums.INSTALL_CA_CERT)
6225                     .setAdmin(caller.getPackageName())
6226                     .setBoolean(/* isDelegate */ admin == null)
6227                     .write();
6228             return installedAlias;
6229         });
6230 
6231         if (alias == null) {
6232             Slogf.w(LOG_TAG, "Problem installing cert");
6233             return false;
6234         }
6235 
6236         synchronized (getLockObject()) {
6237             getUserData(caller.getUserId()).mOwnerInstalledCaCerts.add(alias);
6238             saveSettingsLocked(caller.getUserId());
6239         }
6240         return true;
6241     }
6242 
6243     @Override
6244     public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
6245         if (!mHasFeature) {
6246             return;
6247         }
6248         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
6249         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
6250         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_UNINSTALL_CA_CERT);
6251 
6252         mInjector.binderWithCleanCallingIdentity(() -> {
6253             mCertificateMonitor.uninstallCaCerts(caller.getUserHandle(), aliases);
6254             DevicePolicyEventLogger
6255                     .createEvent(DevicePolicyEnums.UNINSTALL_CA_CERTS)
6256                     .setAdmin(caller.getPackageName())
6257                     .setBoolean(/* isDelegate */ admin == null)
6258                     .write();
6259         });
6260 
6261         synchronized (getLockObject()) {
6262             if (getUserData(caller.getUserId()).mOwnerInstalledCaCerts.removeAll(
6263                     Arrays.asList(aliases))) {
6264                 saveSettingsLocked(caller.getUserId());
6265             }
6266         }
6267     }
6268 
6269     @Override
6270     public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
6271             byte[] cert, byte[] chain, String alias, boolean requestAccess,
6272             boolean isUserSelectable) {
6273         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6274         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6275         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6276         if (isPermissionCheckFlagEnabled()) {
6277             Preconditions.checkCallAuthorization(
6278                     hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6279                             caller.getPackageName(), caller.getUserId())
6280                             || isCredentialManagementApp);
6281         }  else {
6282             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6283                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
6284                     || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
6285         }
6286         if (isCredentialManagementApp) {
6287             Preconditions.checkCallAuthorization(!isUserSelectable, "The credential "
6288                     + "management app is not allowed to install a user selectable key pair");
6289             Preconditions.checkCallAuthorization(
6290                     isAliasInCredentialManagementAppPolicy(caller, alias),
6291                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6292         }
6293         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_KEY_PAIR);
6294 
6295         final long id = mInjector.binderClearCallingIdentity();
6296         try {
6297             final KeyChainConnection keyChainConnection =
6298                     KeyChain.bindAsUser(mContext, caller.getUserHandle());
6299             try {
6300                 IKeyChainService keyChain = keyChainConnection.getService();
6301                 if (!keyChain.installKeyPair(privKey, cert, chain, alias, KeyStore.UID_SELF)) {
6302                     logInstallKeyPairFailure(caller, isCredentialManagementApp);
6303                     return false;
6304                 }
6305                 if (requestAccess) {
6306                     keyChain.setGrant(caller.getUid(), alias, true);
6307                 }
6308                 keyChain.setUserSelectable(alias, isUserSelectable);
6309                 DevicePolicyEventLogger
6310                         .createEvent(DevicePolicyEnums.INSTALL_KEY_PAIR)
6311                         .setAdmin(caller.getPackageName())
6312                         .setBoolean(/* isDelegate */ isCallerDelegate)
6313                         .setStrings(isCredentialManagementApp
6314                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6315                         .write();
6316                 return true;
6317             } catch (RemoteException e) {
6318                 Slogf.e(LOG_TAG, "Installing certificate", e);
6319             } finally {
6320                 keyChainConnection.close();
6321             }
6322         } catch (InterruptedException e) {
6323             Slogf.w(LOG_TAG, "Interrupted while installing certificate", e);
6324             Thread.currentThread().interrupt();
6325         } finally {
6326             mInjector.binderRestoreCallingIdentity(id);
6327         }
6328         logInstallKeyPairFailure(caller, isCredentialManagementApp);
6329         return false;
6330     }
6331 
6332     private void logInstallKeyPairFailure(CallerIdentity caller,
6333             boolean isCredentialManagementApp) {
6334         if (!isCredentialManagementApp) {
6335             return;
6336         }
6337         DevicePolicyEventLogger
6338                 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_INSTALL_KEY_PAIR_FAILED)
6339                 .setStrings(caller.getPackageName())
6340                 .write();
6341     }
6342 
6343     @Override
6344     public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
6345         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6346         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6347         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6348         if (isPermissionCheckFlagEnabled()) {
6349             Preconditions.checkCallAuthorization(
6350                     hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6351                             caller.getPackageName(), caller.getUserId())
6352                             || isCredentialManagementApp);
6353         }  else {
6354             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6355                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
6356                     || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
6357         }
6358         if (isCredentialManagementApp) {
6359             Preconditions.checkCallAuthorization(
6360                     isAliasInCredentialManagementAppPolicy(caller, alias),
6361                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6362         }
6363         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_KEY_PAIR);
6364 
6365         final long id = Binder.clearCallingIdentity();
6366         try {
6367             final KeyChainConnection keyChainConnection =
6368                     KeyChain.bindAsUser(mContext, caller.getUserHandle());
6369             try {
6370                 IKeyChainService keyChain = keyChainConnection.getService();
6371                 DevicePolicyEventLogger
6372                         .createEvent(DevicePolicyEnums.REMOVE_KEY_PAIR)
6373                         .setAdmin(caller.getPackageName())
6374                         .setBoolean(/* isDelegate */ isCallerDelegate)
6375                         .setStrings(isCredentialManagementApp
6376                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6377                         .write();
6378                 return keyChain.removeKeyPair(alias);
6379             } catch (RemoteException e) {
6380                 Slogf.e(LOG_TAG, "Removing keypair", e);
6381             } finally {
6382                 keyChainConnection.close();
6383             }
6384         } catch (InterruptedException e) {
6385             Slogf.w(LOG_TAG, "Interrupted while removing keypair", e);
6386             Thread.currentThread().interrupt();
6387         } finally {
6388             Binder.restoreCallingIdentity(id);
6389         }
6390         return false;
6391     }
6392 
6393     @Override
6394     public boolean hasKeyPair(String callerPackage, String alias) {
6395         final CallerIdentity caller = getCallerIdentity(callerPackage);
6396         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6397         Preconditions.checkCallAuthorization(canInstallCertificates(caller)
6398                 || isCredentialManagementApp);
6399         if (isCredentialManagementApp) {
6400             Preconditions.checkCallAuthorization(
6401                     isAliasInCredentialManagementAppPolicy(caller, alias),
6402                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6403         }
6404 
6405         return mInjector.binderWithCleanCallingIdentity(() -> {
6406             try (KeyChainConnection keyChainConnection =
6407                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6408                 return keyChainConnection.getService().containsKeyPair(alias);
6409             } catch (RemoteException e) {
6410                 Slogf.e(LOG_TAG, "Querying keypair", e);
6411             } catch (InterruptedException e) {
6412                 Slogf.w(LOG_TAG, "Interrupted while querying keypair", e);
6413                 Thread.currentThread().interrupt();
6414             }
6415             return false;
6416         });
6417     }
6418 
6419     private boolean canInstallCertificates(CallerIdentity caller) {
6420         if (isPermissionCheckFlagEnabled()) {
6421             return hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6422                     caller.getPackageName(), caller.getUserId());
6423         }  else {
6424             return isProfileOwner(caller) || isDefaultDeviceOwner(caller)
6425                     || isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6426         }
6427     }
6428 
6429     private boolean canChooseCertificates(CallerIdentity caller) {
6430         return isProfileOwner(caller) || isDefaultDeviceOwner(caller)
6431                 || isCallerDelegate(caller, DELEGATION_CERT_SELECTION);
6432     }
6433 
6434     @Override
6435     public boolean setKeyGrantToWifiAuth(String callerPackage, String alias, boolean hasGrant) {
6436         Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty");
6437 
6438         final CallerIdentity caller = getCallerIdentity(callerPackage);
6439         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
6440         try {
6441             return setKeyChainGrantInternal(
6442                     alias, hasGrant, Process.WIFI_UID, caller.getUserHandle());
6443         } catch (IllegalArgumentException e) {
6444             if (mInjector.isChangeEnabled(THROW_EXCEPTION_WHEN_KEY_MISSING, caller.getPackageName(),
6445                     caller.getUserId())) {
6446                 throw e;
6447             }
6448             return false;
6449         }
6450     }
6451 
6452     @Override
6453     public boolean isKeyPairGrantedToWifiAuth(String callerPackage, String alias) {
6454         Preconditions.checkStringNotEmpty(alias, "Alias to check cannot be empty");
6455 
6456         final CallerIdentity caller = getCallerIdentity(callerPackage);
6457         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
6458 
6459         return mInjector.binderWithCleanCallingIdentity(() -> {
6460             try (KeyChainConnection keyChainConnection =
6461                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6462                 final List<String> result = new ArrayList<>();
6463                 final int[] granteeUids = keyChainConnection.getService().getGrants(alias);
6464 
6465                 for (final int uid : granteeUids) {
6466                     if (uid == Process.WIFI_UID) {
6467                         return true;
6468                     }
6469                 }
6470                 return false;
6471             } catch (RemoteException e) {
6472                 Slogf.e(LOG_TAG, "Querying grant to wifi auth.", e);
6473                 return false;
6474             }
6475         });
6476     }
6477 
6478     @Override
6479     public boolean setKeyGrantForApp(ComponentName who, String callerPackage, String alias,
6480             String packageName, boolean hasGrant) {
6481         Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty");
6482         Preconditions.checkStringNotEmpty(packageName, "Package to grant to cannot be empty");
6483 
6484         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6485         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6486                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
6487                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_SELECTION)));
6488 
6489         final int granteeUid;
6490         try {
6491             ApplicationInfo ai = mInjector.getIPackageManager().getApplicationInfo(
6492                     packageName, 0, caller.getUserId());
6493             Preconditions.checkArgument(ai != null,
6494                     "Provided package %s is not installed", packageName);
6495             granteeUid = ai.uid;
6496         } catch (RemoteException e) {
6497             throw new IllegalStateException("Failure getting grantee uid", e);
6498         }
6499         try {
6500             return setKeyChainGrantInternal(alias, hasGrant, granteeUid, caller.getUserHandle());
6501         } catch (IllegalArgumentException e) {
6502             if (mInjector.isChangeEnabled(THROW_EXCEPTION_WHEN_KEY_MISSING, callerPackage,
6503                     caller.getUserId())) {
6504                 throw e;
6505             }
6506             return false;
6507         }
6508     }
6509 
6510     private boolean setKeyChainGrantInternal(String alias, boolean hasGrant, int granteeUid,
6511             UserHandle userHandle) {
6512         final long id = mInjector.binderClearCallingIdentity();
6513         try {
6514             try (KeyChainConnection keyChainConnection =
6515                          KeyChain.bindAsUser(mContext, userHandle)) {
6516                 IKeyChainService keyChain = keyChainConnection.getService();
6517                 return keyChain.setGrant(granteeUid, alias, hasGrant);
6518             } catch (RemoteException | AssertionError e) {
6519                 Slogf.e(LOG_TAG, "Setting grant for package.", e);
6520                 return false;
6521             }
6522         } catch (InterruptedException e) {
6523             Slogf.w(LOG_TAG, "Interrupted while setting key grant", e);
6524             Thread.currentThread().interrupt();
6525         } finally {
6526             mInjector.binderRestoreCallingIdentity(id);
6527         }
6528         return false;
6529     }
6530 
6531     @Override
6532     public ParcelableGranteeMap getKeyPairGrants(String callerPackage, String alias) {
6533         final CallerIdentity caller = getCallerIdentity(callerPackage);
6534         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
6535 
6536         final ArrayMap<Integer, Set<String>> result = new ArrayMap<>();
6537         mInjector.binderWithCleanCallingIdentity(() -> {
6538             try (KeyChainConnection keyChainConnection =
6539                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6540                 final int[] granteeUids = keyChainConnection.getService().getGrants(alias);
6541                 final PackageManager pm = mInjector.getPackageManager(caller.getUserId());
6542 
6543                 for (final int uid : granteeUids) {
6544                     final String[] packages = pm.getPackagesForUid(uid);
6545                     if (packages == null) {
6546                         Slogf.wtf(LOG_TAG, "No packages found for uid " + uid);
6547                         continue;
6548                     }
6549                     result.put(uid, new ArraySet<String>(packages));
6550                 }
6551             } catch (RemoteException e) {
6552                 Slogf.e(LOG_TAG, "Querying keypair grants", e);
6553             } catch (InterruptedException e) {
6554                 Slogf.w(LOG_TAG, "Interrupted while querying keypair grants", e);
6555                 Thread.currentThread().interrupt();
6556             }
6557         });
6558         return new ParcelableGranteeMap(result);
6559     }
6560 
6561     @VisibleForTesting
6562     public static int[] translateIdAttestationFlags(
6563             int idAttestationFlags) {
6564         Map<Integer, Integer> idTypeToAttestationFlag = new HashMap();
6565         idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
6566         idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
6567         idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
6568         idTypeToAttestationFlag.put(
6569                 ID_TYPE_INDIVIDUAL_ATTESTATION, USE_INDIVIDUAL_ATTESTATION);
6570 
6571         int numFlagsSet = Integer.bitCount(idAttestationFlags);
6572         // No flags are set - return null to indicate no device ID attestation information should
6573         // be included in the attestation record.
6574         if (numFlagsSet == 0) {
6575             return null;
6576         }
6577 
6578         // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if
6579         // no other flag is set. That will lead to inclusion of general device make data in the
6580         // attestation record, but no specific device identifiers.
6581         if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) {
6582             numFlagsSet -= 1;
6583             idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO);
6584         }
6585 
6586         int[] attestationUtilsFlags = new int[numFlagsSet];
6587         int i = 0;
6588         for (Integer idType: idTypeToAttestationFlag.keySet()) {
6589             if ((idType & idAttestationFlags) != 0) {
6590                 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType);
6591             }
6592         }
6593 
6594         return attestationUtilsFlags;
6595     }
6596 
6597     @Override
6598     public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
6599             ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags,
6600             KeymasterCertificateChain attestationChain) {
6601         // Get attestation flags, if any.
6602         final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags);
6603         final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
6604         KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
6605         final String alias = keySpec.getKeystoreAlias();
6606         Preconditions.checkStringNotEmpty(alias, "Empty alias provided");
6607         Preconditions.checkArgument(
6608                 !deviceIdAttestationRequired || keySpec.getAttestationChallenge() != null,
6609                 "Requested Device ID attestation but challenge is empty");
6610 
6611         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6612         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6613         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6614         if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) {
6615             Preconditions.checkCallAuthorization(hasDeviceIdAccessUnchecked(
6616                     caller.getPackageName(), caller.getUid()));
6617             enforceIndividualAttestationSupportedIfRequested(attestationUtilsFlags);
6618         } else {
6619             if (isPermissionCheckFlagEnabled()) {
6620                 Preconditions.checkCallAuthorization(
6621                         hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6622                                 caller.getPackageName(), caller.getUserId())
6623                                 || isCredentialManagementApp);
6624             }  else {
6625                 Preconditions.checkCallAuthorization((caller.hasAdminComponent() && (isProfileOwner(
6626                         caller) || isDefaultDeviceOwner(caller))) || (caller.hasPackage() && (
6627                         isCallerDelegate || isCredentialManagementApp)));
6628             }
6629             if (isCredentialManagementApp) {
6630                 Preconditions.checkCallAuthorization(
6631                         isAliasInCredentialManagementAppPolicy(caller, alias),
6632                         CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6633             }
6634         }
6635 
6636         if (TextUtils.isEmpty(alias)) {
6637             throw new IllegalArgumentException("Empty alias provided.");
6638         }
6639         // As the caller will be granted access to the key, ensure no UID was specified, as
6640         // it will not have the desired effect.
6641         if (keySpec.getUid() != KeyStore.UID_SELF) {
6642             Slogf.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
6643             logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6644             return false;
6645         }
6646 
6647         if (deviceIdAttestationRequired) {
6648             if (keySpec.getAttestationChallenge() == null) {
6649                 throw new IllegalArgumentException(
6650                         "Requested Device ID attestation but challenge is empty.");
6651             }
6652             KeyGenParameterSpec.Builder specBuilder = new KeyGenParameterSpec.Builder(keySpec);
6653             specBuilder.setAttestationIds(attestationUtilsFlags);
6654             specBuilder.setDevicePropertiesAttestationIncluded(true);
6655             keySpec = specBuilder.build();
6656         }
6657 
6658         final long id = mInjector.binderClearCallingIdentity();
6659         try {
6660             try (KeyChainConnection keyChainConnection =
6661                     KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6662                 IKeyChainService keyChain = keyChainConnection.getService();
6663 
6664                 final int generationResult = keyChain.generateKeyPair(algorithm,
6665                         new ParcelableKeyGenParameterSpec(keySpec));
6666                 if (generationResult != KeyChain.KEY_GEN_SUCCESS) {
6667                     Slogf.e(LOG_TAG, "KeyChain failed to generate a keypair, error %d.",
6668                             generationResult);
6669                     logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6670                     switch (generationResult) {
6671                         case KeyChain.KEY_GEN_STRONGBOX_UNAVAILABLE:
6672                             throw new ServiceSpecificException(
6673                                     DevicePolicyManager.KEY_GEN_STRONGBOX_UNAVAILABLE,
6674                                     String.format("KeyChain error: %d", generationResult));
6675                         case KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS:
6676                             throw new UnsupportedOperationException(
6677                                 "Device does not support Device ID attestation.");
6678                         default:
6679                             return false;
6680                     }
6681                 }
6682 
6683                 // Set a grant for the caller here so that when the client calls
6684                 // requestPrivateKey, it will be able to get the key from Keystore.
6685                 // Note the use of the calling  UID, since the request for the private
6686                 // key will come from the client's process, so the grant has to be for
6687                 // that UID.
6688                 keyChain.setGrant(caller.getUid(), alias, true);
6689 
6690                 try {
6691                     final List<byte[]> encodedCerts = new ArrayList();
6692                     final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
6693                     final byte[] certChainBytes = keyChain.getCaCertificates(alias);
6694                     encodedCerts.add(keyChain.getCertificate(alias));
6695                     if (certChainBytes != null) {
6696                         final Collection<X509Certificate> certs =
6697                                 (Collection<X509Certificate>) certFactory.generateCertificates(
6698                                     new ByteArrayInputStream(certChainBytes));
6699                         for (X509Certificate cert : certs) {
6700                             encodedCerts.add(cert.getEncoded());
6701                         }
6702                     }
6703 
6704                     attestationChain.shallowCopyFrom(new KeymasterCertificateChain(encodedCerts));
6705                 } catch (CertificateException e) {
6706                     logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6707                     Slogf.e(LOG_TAG, "While retrieving certificate chain.", e);
6708                     return false;
6709                 }
6710 
6711                 DevicePolicyEventLogger
6712                         .createEvent(DevicePolicyEnums.GENERATE_KEY_PAIR)
6713                         .setAdmin(caller.getPackageName())
6714                         .setBoolean(/* isDelegate */ isCallerDelegate)
6715                         .setInt(idAttestationFlags)
6716                         .setStrings(algorithm, isCredentialManagementApp
6717                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6718                         .write();
6719                 return true;
6720             }
6721         } catch (RemoteException e) {
6722             Slogf.e(LOG_TAG, "KeyChain error while generating a keypair", e);
6723         } catch (InterruptedException e) {
6724             Slogf.w(LOG_TAG, "Interrupted while generating keypair", e);
6725             Thread.currentThread().interrupt();
6726         } finally {
6727             mInjector.binderRestoreCallingIdentity(id);
6728         }
6729         logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6730         return false;
6731     }
6732 
6733     private void logGenerateKeyPairFailure(CallerIdentity caller,
6734             boolean isCredentialManagementApp) {
6735         if (!isCredentialManagementApp) {
6736             return;
6737         }
6738         DevicePolicyEventLogger
6739                 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_GENERATE_KEY_PAIR_FAILED)
6740                 .setStrings(caller.getPackageName())
6741                 .write();
6742     }
6743 
6744     private void enforceIndividualAttestationSupportedIfRequested(int[] attestationUtilsFlags) {
6745         for (int attestationFlag : attestationUtilsFlags) {
6746             if (attestationFlag == USE_INDIVIDUAL_ATTESTATION
6747                     && !mInjector.getPackageManager().hasSystemFeature(
6748                     PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION)) {
6749                 throw new UnsupportedOperationException("Device Individual attestation is not "
6750                         + "supported on this device.");
6751             }
6752         }
6753     }
6754 
6755     @Override
6756     public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias,
6757             byte[] cert, byte[] chain, boolean isUserSelectable) {
6758         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6759         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6760         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6761         if (isPermissionCheckFlagEnabled()) {
6762             Preconditions.checkCallAuthorization(
6763                     hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6764                             caller.getPackageName(), caller.getUserId())
6765                             || isCredentialManagementApp);
6766         } else {
6767             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6768                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
6769                     || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
6770         }
6771         if (isCredentialManagementApp) {
6772             Preconditions.checkCallAuthorization(
6773                     isAliasInCredentialManagementAppPolicy(caller, alias),
6774                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6775         }
6776 
6777         final long id = mInjector.binderClearCallingIdentity();
6778         try (final KeyChainConnection keyChainConnection =
6779                 KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6780             IKeyChainService keyChain = keyChainConnection.getService();
6781             if (!keyChain.setKeyPairCertificate(alias, cert, chain)) {
6782                 return false;
6783             }
6784             keyChain.setUserSelectable(alias, isUserSelectable);
6785             DevicePolicyEventLogger
6786                     .createEvent(DevicePolicyEnums.SET_KEY_PAIR_CERTIFICATE)
6787                     .setAdmin(caller.getPackageName())
6788                     .setBoolean(/* isDelegate */ isCallerDelegate)
6789                     .setStrings(isCredentialManagementApp
6790                             ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6791                     .write();
6792             return true;
6793         } catch (InterruptedException e) {
6794             Slogf.w(LOG_TAG, "Interrupted while setting keypair certificate", e);
6795             Thread.currentThread().interrupt();
6796         } catch (RemoteException e) {
6797             Slogf.e(LOG_TAG, "Failed setting keypair certificate", e);
6798         } finally {
6799             mInjector.binderRestoreCallingIdentity(id);
6800         }
6801         return false;
6802     }
6803 
6804     @Override
6805     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
6806             final IBinder response) {
6807         final CallerIdentity caller = getCallerIdentity();
6808         Preconditions.checkCallAuthorization(isSystemUid(caller),
6809                 String.format(NOT_SYSTEM_CALLER_MSG, "choose private key alias"));
6810 
6811         // If there is a profile owner, redirect to that; otherwise query the device owner.
6812         ComponentName aliasChooser = getProfileOwnerAsUser(caller.getUserId());
6813         if (aliasChooser == null && caller.getUserHandle().isSystem()) {
6814             synchronized (getLockObject()) {
6815                 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
6816                 if (deviceOwnerAdmin != null) {
6817                     aliasChooser = deviceOwnerAdmin.info.getComponent();
6818                 }
6819             }
6820         }
6821         if (aliasChooser == null) {
6822             sendPrivateKeyAliasResponse(null, response);
6823             return;
6824         }
6825 
6826         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
6827         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
6828         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
6829         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
6830         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
6831         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
6832 
6833         final ComponentName delegateReceiver;
6834         delegateReceiver = resolveDelegateReceiver(DELEGATION_CERT_SELECTION,
6835                 DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS, caller.getUserId());
6836 
6837         final boolean isDelegate;
6838         if (delegateReceiver != null) {
6839             intent.setComponent(delegateReceiver);
6840             isDelegate = true;
6841         } else {
6842             intent.setComponent(aliasChooser);
6843             isDelegate = false;
6844         }
6845 
6846         mInjector.binderWithCleanCallingIdentity(() -> {
6847             mContext.sendOrderedBroadcastAsUser(intent, caller.getUserHandle(), null,
6848                     new BroadcastReceiver() {
6849                 @Override
6850                 public void onReceive(Context context, Intent intent) {
6851                     final String chosenAlias = getResultData();
6852                     sendPrivateKeyAliasResponse(chosenAlias, response);
6853                 }
6854             }, null, Activity.RESULT_OK, null, null);
6855             DevicePolicyEventLogger
6856                     .createEvent(DevicePolicyEnums.CHOOSE_PRIVATE_KEY_ALIAS)
6857                     .setAdmin(intent.getComponent())
6858                     .setBoolean(isDelegate)
6859                     .write();
6860         });
6861     }
6862 
6863     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
6864         final IKeyChainAliasCallback keyChainAliasResponse =
6865                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
6866         // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
6867         // is oneway, which means it won't block if the recipient lives in another process.
6868         try {
6869             keyChainAliasResponse.alias(alias);
6870         } catch (Exception e) {
6871             // Caller could throw RuntimeException or RemoteException back across processes. Catch
6872             // everything just to be sure.
6873             Slogf.e(LOG_TAG, "error while responding to callback", e);
6874         }
6875     }
6876 
6877     /**
6878      * Determine whether DPMS should check if a delegate package is already installed before
6879      * granting it new delegations via {@link #setDelegatedScopes}.
6880      */
6881     private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
6882             int targetSdk, List<String> scopes) {
6883         // 1) Never skip is installed check from N.
6884         if (targetSdk >= Build.VERSION_CODES.N) {
6885             return true;
6886         }
6887         // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
6888         if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
6889             return false;
6890         }
6891         // 3) Skip if all previously granted scopes are being cleared.
6892         if (scopes.isEmpty()) {
6893             return false;
6894         }
6895         // Otherwise it should check that delegatePackage is installed.
6896         return true;
6897     }
6898 
6899     /**
6900      * Set the scopes of a device owner or profile owner delegate.
6901      *
6902      * @param who the device owner or profile owner.
6903      * @param delegatePackage the name of the delegate package.
6904      * @param scopeList the list of delegation scopes to be given to the delegate package.
6905      */
6906     @Override
6907     public void setDelegatedScopes(ComponentName who, String delegatePackage,
6908             List<String> scopeList) throws SecurityException {
6909         Objects.requireNonNull(who, "ComponentName is null");
6910         Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
6911         Preconditions.checkCollectionElementsNotNull(scopeList, "Scopes");
6912         final CallerIdentity caller = getCallerIdentity(who);
6913 
6914         // Remove possible duplicates.
6915         final ArrayList<String> scopes = new ArrayList(new ArraySet(scopeList));
6916         // Ensure given scopes are valid.
6917         if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
6918             throw new IllegalArgumentException("Unexpected delegation scopes");
6919         }
6920         // Retrieve the user ID of the calling process.
6921         final int userId = caller.getUserId();
6922         // Ensure calling process is device/profile owner.
6923         if (!Collections.disjoint(scopes, DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS)) {
6924             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
6925                     || (isProfileOwner(caller) && isManagedProfile(caller.getUserId())));
6926         } else if (!Collections.disjoint(
6927                 scopes, DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS)) {
6928             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
6929                     || isProfileOwnerOfOrganizationOwnedDevice(caller));
6930         } else {
6931             Preconditions.checkCallAuthorization(
6932                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
6933         }
6934 
6935         synchronized (getLockObject()) {
6936             // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
6937             if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
6938                         getTargetSdk(who.getPackageName(), userId), scopes)) {
6939                 // Throw when the delegate package is not installed.
6940                 if (!isPackageInstalledForUser(delegatePackage, userId)) {
6941                     throw new IllegalArgumentException("Package " + delegatePackage
6942                             + " is not installed on the current user");
6943                 }
6944             }
6945 
6946             // Set the new delegate in user policies.
6947             final DevicePolicyData policy = getUserData(userId);
6948             List<String> exclusiveScopes = null;
6949             if (!scopes.isEmpty()) {
6950                 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
6951                 exclusiveScopes = new ArrayList<>(scopes);
6952                 exclusiveScopes.retainAll(EXCLUSIVE_DELEGATIONS);
6953             } else {
6954                 // Remove any delegation info if the given scopes list is empty.
6955                 policy.mDelegationMap.remove(delegatePackage);
6956             }
6957             sendDelegationChangedBroadcast(delegatePackage, scopes, userId);
6958 
6959             // If set, remove exclusive scopes from all other delegates
6960             if (exclusiveScopes != null && !exclusiveScopes.isEmpty()) {
6961                 for (int i = policy.mDelegationMap.size() - 1; i >= 0; --i) {
6962                     final String currentPackage = policy.mDelegationMap.keyAt(i);
6963                     final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
6964 
6965                     if (!currentPackage.equals(delegatePackage)) {
6966                         // Iterate through all other delegates
6967                         if (currentScopes.removeAll(exclusiveScopes)) {
6968                             // And if this delegate had some exclusive scopes which are now moved
6969                             // to the new delegate, notify about its delegation changes.
6970                             if (currentScopes.isEmpty()) {
6971                                 policy.mDelegationMap.removeAt(i);
6972                             }
6973                             sendDelegationChangedBroadcast(currentPackage,
6974                                     new ArrayList<>(currentScopes), userId);
6975                         }
6976                     }
6977                 }
6978             }
6979             // Persist updates.
6980             saveSettingsLocked(userId);
6981         }
6982     }
6983 
6984     private void sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes,
6985             int userId) {
6986         // Notify delegate package of updates.
6987         final Intent intent = new Intent(
6988                 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
6989         // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
6990         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
6991         // Limit components this intent resolves to to the delegate package.
6992         intent.setPackage(delegatePackage);
6993         // Include the list of delegated scopes as an extra.
6994         intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes);
6995         // Send the broadcast.
6996         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
6997     }
6998 
6999     /**
7000      * Get the delegation scopes given to a delegate package by a device owner or profile owner.
7001      *
7002      * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
7003      * passing in {@code null} as the {@code who} parameter and its own name as the
7004      * {@code delegatepackage}.
7005      *
7006      * @param who the device owner or profile owner, or {@code null} if the caller is
7007      *            {@code delegatePackage}.
7008      * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
7009      * @return a list of the delegation scopes currently given to {@code delegatePackage}.
7010      */
7011     @Override
7012     @NonNull
7013     public List<String> getDelegatedScopes(ComponentName who,
7014             String delegatePackage) throws SecurityException {
7015         Objects.requireNonNull(delegatePackage, "Delegate package is null");
7016         final CallerIdentity caller = getCallerIdentity(who);
7017 
7018         // Ensure the caller may call this method:
7019         // * Either it's a profile owner / device owner, if componentName is provided
7020         // * Or it's an app querying its own delegation scopes
7021         if (caller.hasAdminComponent()) {
7022             Preconditions.checkCallAuthorization(
7023                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
7024         } else {
7025             Preconditions.checkCallAuthorization(isPackage(caller, delegatePackage),
7026                     String.format("Caller with uid %d is not %s", caller.getUid(),
7027                             delegatePackage));
7028         }
7029         synchronized (getLockObject()) {
7030             final DevicePolicyData policy = getUserData(caller.getUserId());
7031             // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
7032             final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
7033             return scopes == null ? Collections.EMPTY_LIST : scopes;
7034         }
7035     }
7036 
7037     /**
7038      * Get a list of  packages that were given a specific delegation scopes by a device owner or
7039      * profile owner.
7040      *
7041      * @param who the device owner or profile owner.
7042      * @param scope the scope whose delegates are to be retrieved.
7043      * @return a list of the delegate packages currently given the {@code scope} delegation.
7044      */
7045     @NonNull
7046     public List<String> getDelegatePackages(ComponentName who, String scope)
7047             throws SecurityException {
7048         Objects.requireNonNull(who, "ComponentName is null");
7049         Objects.requireNonNull(scope, "Scope is null");
7050         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
7051             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
7052         }
7053 
7054         // Retrieve the user ID of the calling process.
7055         final CallerIdentity caller = getCallerIdentity(who);
7056         Preconditions.checkCallAuthorization(
7057                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7058         synchronized (getLockObject()) {
7059             return getDelegatePackagesInternalLocked(scope, caller.getUserId());
7060         }
7061     }
7062 
7063     private List<String> getDelegatePackagesInternalLocked(String scope, int userId) {
7064         final DevicePolicyData policy = getUserData(userId);
7065 
7066         // Create a list to hold the resulting delegate packages.
7067         final List<String> delegatePackagesWithScope = new ArrayList<>();
7068         // Add all delegations containing scope to the result list.
7069         for (int i = 0; i < policy.mDelegationMap.size(); i++) {
7070             if (policy.mDelegationMap.valueAt(i).contains(scope)) {
7071                 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
7072             }
7073         }
7074         return delegatePackagesWithScope;
7075     }
7076 
7077     /**
7078      * Return the ComponentName of the receiver that handles the given broadcast action, from
7079      * the app that holds the given delegation capability. If the app defines multiple receivers
7080      * with the same intent action filter, will return any one of them nondeterministically.
7081      *
7082      * @return ComponentName of the receiver or {@null} if none exists.
7083      */
7084     private ComponentName resolveDelegateReceiver(String scope, String action, int userId) {
7085 
7086         final List<String> delegates;
7087         synchronized (getLockObject()) {
7088             delegates = getDelegatePackagesInternalLocked(scope, userId);
7089         }
7090         if (delegates.size() == 0) {
7091             return null;
7092         } else if (delegates.size() > 1) {
7093             Slogf.wtf(LOG_TAG, "More than one delegate holds " + scope);
7094             return null;
7095         }
7096         final String pkg = delegates.get(0);
7097         Intent intent = new Intent(action);
7098         intent.setPackage(pkg);
7099         final List<ResolveInfo> receivers;
7100         try {
7101             receivers = mIPackageManager.queryIntentReceivers(
7102                     intent, null, 0, userId).getList();
7103         } catch (RemoteException e) {
7104             return null;
7105         }
7106         final int count = receivers.size();
7107         if (count >= 1) {
7108             if (count > 1) {
7109                 Slogf.w(LOG_TAG, pkg + " defines more than one delegate receiver for " + action);
7110             }
7111             return receivers.get(0).activityInfo.getComponentName();
7112         } else {
7113             return null;
7114         }
7115     }
7116 
7117     /**
7118      * Check whether a caller application has been delegated a given scope via
7119      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
7120      * device owner.
7121      * <p>
7122      * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
7123      * then comparing the calling UID with the UID of {@code callerPackage} as reported by
7124      * {@link PackageManager#getPackageUidAsUser}.
7125      *
7126      * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
7127      * @param scope the delegation scope to be checked.
7128      * @return {@code true} if the calling process is a delegate of {@code scope}.
7129      */
7130     private boolean isCallerDelegate(String callerPackage, int callerUid, String scope) {
7131         Objects.requireNonNull(callerPackage, "callerPackage is null");
7132         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
7133             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
7134         }
7135 
7136         // Retrieve the UID and user ID of the calling process.
7137         final int userId = UserHandle.getUserId(callerUid);
7138         synchronized (getLockObject()) {
7139             // Retrieve user policy data.
7140             final DevicePolicyData policy = getUserData(userId);
7141             // Retrieve the list of delegation scopes granted to callerPackage.
7142             final List<String> scopes = policy.mDelegationMap.get(callerPackage);
7143             // Check callingUid only if callerPackage has the required scope delegation.
7144             if (scopes != null && scopes.contains(scope)) {
7145                 // Return true if the caller is actually callerPackage.
7146                 return isCallingFromPackage(callerPackage, callerUid);
7147             }
7148             return false;
7149         }
7150     }
7151 
7152     /**
7153      * Check whether a caller application has been delegated a given scope via
7154      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
7155      * device owner.
7156      * <p>
7157      * This is done by checking that the calling package was granted {@code scope} delegation and
7158      * then comparing the calling UID with the UID of the calling package as reported by
7159      * {@link PackageManager#getPackageUidAsUser}.
7160      *
7161      * @param caller the calling identity
7162      * @param scope the delegation scope to be checked.
7163      * @return {@code true} if the calling process is a delegate of {@code scope}.
7164      */
7165     private boolean isCallerDelegate(CallerIdentity caller, String scope) {
7166         if (caller.getPackageName() == null) {
7167             return false;
7168         }
7169         Preconditions.checkArgument(Arrays.asList(DELEGATIONS).contains(scope),
7170                 "Unexpected delegation scope: %s", scope);
7171 
7172         synchronized (getLockObject()) {
7173             // Retrieve user policy data.
7174             final DevicePolicyData policy = getUserData(caller.getUserId());
7175             // Retrieve the list of delegation scopes granted to callerPackage.
7176             final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName());
7177             // Check callingUid only if callerPackage has the required scope delegation.
7178             return scopes != null && scopes.contains(scope);
7179         }
7180     }
7181 
7182     /**
7183      * Check whether a caller application has been delegated any scope via
7184      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
7185      * device owner.
7186      * <p>
7187      * This is done by checking that the calling package was granted any scope delegations and
7188      * then comparing the calling UID with the UID of the calling package as reported by
7189      * {@link PackageManager#getPackageUidAsUser}.
7190      *
7191      * @param caller the calling identity
7192      * @return {@code true} if the calling process is a delegate of any scope.
7193      */
7194     private boolean isCallerDelegate(CallerIdentity caller) {
7195         Objects.requireNonNull(caller.getPackageName(), "callerPackage is null");
7196 
7197         synchronized (getLockObject()) {
7198             // Retrieve user policy data.
7199             final DevicePolicyData policy = getUserData(caller.getUserId());
7200             // Retrieve the list of delegation scopes granted to callerPackage.
7201             final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName());
7202             // Check callingUid only if callerPackage has the required scope delegation.
7203             return scopes != null;
7204         }
7205     }
7206 
7207     /**
7208      * Helper function to preserve delegation behavior pre-O when using the deprecated functions
7209      * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
7210      */
7211     private void setDelegatedScopePreO(ComponentName who,
7212             String delegatePackage, String scope) {
7213         Objects.requireNonNull(who, "ComponentName is null");
7214 
7215         final CallerIdentity caller = getCallerIdentity(who);
7216         // Ensure calling process is device/profile owner.
7217         Preconditions.checkCallAuthorization(
7218                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
7219 
7220         synchronized (getLockObject()) {
7221             final DevicePolicyData policy = getUserData(caller.getUserId());
7222 
7223             if (delegatePackage != null) {
7224                 // Set package as a delegate for scope if it is not already one.
7225                 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
7226                 if (scopes == null) {
7227                     scopes = new ArrayList<>();
7228                 }
7229                 if (!scopes.contains(scope)) {
7230                     scopes.add(scope);
7231                     setDelegatedScopes(who, delegatePackage, scopes);
7232                 }
7233             }
7234 
7235             // Clear any existing scope delegates.
7236             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
7237                 final String currentPackage = policy.mDelegationMap.keyAt(i);
7238                 final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
7239 
7240                 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
7241                     final List<String> newScopes = new ArrayList(currentScopes);
7242                     newScopes.remove(scope);
7243                     setDelegatedScopes(who, currentPackage, newScopes);
7244                 }
7245             }
7246         }
7247     }
7248 
7249     /**
7250      * Check whether a caller application is the credential management app, which can access
7251      * privileged APIs.
7252      * <p>
7253      * This is done by checking that the calling package is authorized to perform the app operation
7254      * {@link android.app.AppOpsManager#OP_MANAGE_CREDENTIALS}.
7255      *
7256      * @param caller the calling identity
7257      * @return {@code true} if the calling process is the credential management app.
7258      */
7259     private boolean isCredentialManagementApp(CallerIdentity caller) {
7260         return mInjector.binderWithCleanCallingIdentity(() -> {
7261             AppOpsManager appOpsManager = mInjector.getAppOpsManager();
7262             if (appOpsManager == null) return false;
7263             return appOpsManager.noteOpNoThrow(AppOpsManager.OP_MANAGE_CREDENTIALS, caller.getUid(),
7264                     caller.getPackageName(), null, null) == AppOpsManager.MODE_ALLOWED;
7265         });
7266     }
7267 
7268     /**
7269      * If the caller is the credential management app, the alias provided must be contained
7270      * in the aliases specified in the credential management app's authentication policy.
7271      */
7272     private boolean isAliasInCredentialManagementAppPolicy(CallerIdentity caller, String alias) {
7273         return mInjector.binderWithCleanCallingIdentity(() -> {
7274             try (KeyChainConnection connection = KeyChain.bindAsUser(mContext,
7275                     caller.getUserHandle())) {
7276                 // The policy will be null if there is no credential management app
7277                 AppUriAuthenticationPolicy policy =
7278                         connection.getService().getCredentialManagementAppPolicy();
7279                 return policy != null && !policy.getAppAndUriMappings().isEmpty()
7280                         && containsAlias(policy, alias);
7281             } catch (RemoteException | InterruptedException e) {
7282                 return false;
7283             }
7284         });
7285     }
7286 
7287     private static boolean containsAlias(AppUriAuthenticationPolicy policy, String alias) {
7288         for (Map.Entry<String, Map<Uri, String>> appsToUris :
7289                 policy.getAppAndUriMappings().entrySet()) {
7290             for (Map.Entry<Uri, String> urisToAliases : appsToUris.getValue().entrySet()) {
7291                 if (urisToAliases.getValue().equals(alias)) {
7292                     return true;
7293                 }
7294             }
7295         }
7296         return false;
7297     }
7298 
7299     @Override
7300     public void setCertInstallerPackage(ComponentName who, String installerPackage)
7301             throws SecurityException {
7302         setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
7303         DevicePolicyEventLogger
7304                 .createEvent(DevicePolicyEnums.SET_CERT_INSTALLER_PACKAGE)
7305                 .setAdmin(who)
7306                 .setStrings(installerPackage)
7307                 .write();
7308     }
7309 
7310     @Override
7311     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
7312         final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
7313         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
7314     }
7315 
7316     /**
7317      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
7318      * not installed and therefore not available.
7319      *
7320      * @throws SecurityException if the caller is not a profile or device owner.
7321      * @throws UnsupportedOperationException if the package does not support being set as always-on.
7322      */
7323     @Override
7324     public boolean setAlwaysOnVpnPackage(ComponentName who, String vpnPackage, boolean lockdown,
7325             List<String> lockdownAllowlist)
7326             throws SecurityException {
7327         Objects.requireNonNull(who, "ComponentName is null");
7328 
7329         final CallerIdentity caller = getCallerIdentity(who);
7330         Preconditions.checkCallAuthorization(
7331                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7332         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_ALWAYS_ON_VPN_PACKAGE);
7333 
7334         if (vpnPackage == null) {
7335             final String prevVpnPackage;
7336             synchronized (getLockObject()) {
7337                 prevVpnPackage = getProfileOwnerOrDeviceOwnerLocked(
7338                         caller.getUserId()).mAlwaysOnVpnPackage;
7339                 // If the admin is clearing VPN package but hasn't configure any VPN previously,
7340                 // ignore it so that it doesn't interfere with user-configured VPNs.
7341                 if (TextUtils.isEmpty(prevVpnPackage)) {
7342                     return true;
7343                 }
7344             }
7345             revokeVpnAuthorizationForPackage(prevVpnPackage, caller.getUserId());
7346         }
7347 
7348         final int userId = caller.getUserId();
7349         mInjector.binderWithCleanCallingIdentity(() -> {
7350             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
7351                 Slogf.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage);
7352                 throw new ServiceSpecificException(
7353                         DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage);
7354             }
7355 
7356             if (vpnPackage != null && lockdown && lockdownAllowlist != null) {
7357                 for (String packageName : lockdownAllowlist) {
7358                     if (!isPackageInstalledForUser(packageName, userId)) {
7359                         Slogf.w(LOG_TAG, "Non-existent package in VPN allowlist: " + packageName);
7360                         throw new ServiceSpecificException(
7361                                 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName);
7362                     }
7363                 }
7364             }
7365             // If some package is uninstalled after the check above, it will be ignored by CM.
7366             if (!mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(
7367                     userId, vpnPackage, lockdown, lockdownAllowlist)) {
7368                 throw new UnsupportedOperationException();
7369             }
7370         });
7371         DevicePolicyEventLogger
7372                 .createEvent(DevicePolicyEnums.SET_ALWAYS_ON_VPN_PACKAGE)
7373                 .setAdmin(caller.getComponentName())
7374                 .setStrings(vpnPackage)
7375                 .setBoolean(lockdown)
7376                 .setInt(lockdownAllowlist != null ? lockdownAllowlist.size() : 0)
7377                 .write();
7378         synchronized (getLockObject()) {
7379             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
7380             if (!TextUtils.equals(vpnPackage, admin.mAlwaysOnVpnPackage)
7381                     || lockdown != admin.mAlwaysOnVpnLockdown) {
7382                 admin.mAlwaysOnVpnPackage = vpnPackage;
7383                 admin.mAlwaysOnVpnLockdown = lockdown;
7384                 saveSettingsLocked(userId);
7385             }
7386         }
7387         return true;
7388     }
7389 
7390     private void revokeVpnAuthorizationForPackage(String vpnPackage, int userId) {
7391         mInjector.binderWithCleanCallingIdentity(() -> {
7392             try {
7393                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
7394                         vpnPackage, /* flags= */ 0, userId);
7395                 if (ai == null) {
7396                     Slogf.w(LOG_TAG, "Non-existent VPN package: " + vpnPackage);
7397                 } else {
7398                     mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN,
7399                             ai.uid, vpnPackage, MODE_DEFAULT);
7400                 }
7401             } catch (RemoteException e) {
7402                 Slogf.e(LOG_TAG, "Can't talk to package managed", e);
7403             }
7404         });
7405     }
7406 
7407     @Override
7408     public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException {
7409         Objects.requireNonNull(admin, "ComponentName is null");
7410 
7411         final CallerIdentity caller = getCallerIdentity(admin);
7412         Preconditions.checkCallAuthorization(
7413                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7414 
7415         return mInjector.binderWithCleanCallingIdentity(
7416                 () -> mInjector.getVpnManager().getAlwaysOnVpnPackageForUser(caller.getUserId()));
7417     }
7418 
7419     @Override
7420     public String getAlwaysOnVpnPackageForUser(int userHandle) {
7421         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
7422                 String.format(NOT_SYSTEM_CALLER_MSG, "call getAlwaysOnVpnPackageForUser"));
7423         synchronized (getLockObject()) {
7424             ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle);
7425             return admin != null ? admin.mAlwaysOnVpnPackage : null;
7426         }
7427     }
7428 
7429     @Override
7430     public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException {
7431         final CallerIdentity caller;
7432         if (hasCallingPermission(PERMISSION_MAINLINE_NETWORK_STACK)) {
7433             // TODO: CaptivePortalLoginActivity erroneously calls this method with a non-admin
7434             // ComponentName, so we have to use a separate code path for it:
7435             // getCallerIdentity(admin) will throw if the admin is not in the known admin list.
7436             caller = getCallerIdentity();
7437         } else {
7438             caller = getCallerIdentity(admin);
7439             Preconditions.checkCallAuthorization(
7440                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7441         }
7442 
7443         return mInjector.binderWithCleanCallingIdentity(
7444                 () -> mInjector.getVpnManager().isVpnLockdownEnabled(caller.getUserId()));
7445     }
7446 
7447     @Override
7448     public boolean isAlwaysOnVpnLockdownEnabledForUser(int userHandle) {
7449         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
7450                 String.format(NOT_SYSTEM_CALLER_MSG, "call isAlwaysOnVpnLockdownEnabledForUser"));
7451         synchronized (getLockObject()) {
7452             ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle);
7453             return admin != null && admin.mAlwaysOnVpnLockdown;
7454         }
7455     }
7456 
7457     @Override
7458     public List<String> getAlwaysOnVpnLockdownAllowlist(ComponentName admin)
7459             throws SecurityException {
7460         Objects.requireNonNull(admin, "ComponentName is null");
7461 
7462         final CallerIdentity caller = getCallerIdentity(admin);
7463         Preconditions.checkCallAuthorization(
7464                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7465 
7466         return mInjector.binderWithCleanCallingIdentity(
7467                 () -> mInjector.getVpnManager().getVpnLockdownAllowlist(caller.getUserId()));
7468     }
7469 
7470     private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc,
7471             boolean wipeResetProtectionData) {
7472         wtfIfInLock();
7473         boolean success = false;
7474 
7475         try {
7476             boolean delayed = !mInjector.recoverySystemRebootWipeUserData(
7477                     /* shutdown= */ false, reason, /* force= */ true, /* wipeEuicc= */ wipeEuicc,
7478                     wipeExtRequested, wipeResetProtectionData);
7479             if (delayed) {
7480                 // Persist the request so the device is automatically factory-reset on next start if
7481                 // the system crashes or reboots before the {@code DevicePolicySafetyChecker} calls
7482                 // its callback.
7483                 Slogf.i(LOG_TAG, "Persisting factory reset request as it could be delayed by %s",
7484                         mSafetyChecker);
7485                 synchronized (getLockObject()) {
7486                     DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
7487                     policy.setDelayedFactoryReset(reason, wipeExtRequested, wipeEuicc,
7488                             wipeResetProtectionData);
7489                     saveSettingsLocked(UserHandle.USER_SYSTEM);
7490                 }
7491             }
7492             success = true;
7493         } catch (IOException | SecurityException e) {
7494             Slogf.w(LOG_TAG, "Failed requesting data wipe", e);
7495         } finally {
7496             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
7497         }
7498     }
7499 
7500     private void factoryResetIfDelayedEarlier() {
7501         synchronized (getLockObject()) {
7502             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
7503 
7504             if (policy.mFactoryResetFlags == 0) return;
7505 
7506             if (policy.mFactoryResetReason == null) {
7507                 // Shouldn't happen.
7508                 Slogf.e(LOG_TAG, "no persisted reason for factory resetting");
7509                 policy.mFactoryResetReason = "requested before boot";
7510             }
7511             FactoryResetter factoryResetter = FactoryResetter.newBuilder(mContext)
7512                     .setReason(policy.mFactoryResetReason).setForce(true)
7513                     .setWipeEuicc((policy.mFactoryResetFlags & DevicePolicyData
7514                             .FACTORY_RESET_FLAG_WIPE_EUICC) != 0)
7515                     .setWipeAdoptableStorage((policy.mFactoryResetFlags & DevicePolicyData
7516                             .FACTORY_RESET_FLAG_WIPE_EXTERNAL_STORAGE) != 0)
7517                     .setWipeFactoryResetProtection((policy.mFactoryResetFlags & DevicePolicyData
7518                             .FACTORY_RESET_FLAG_WIPE_FACTORY_RESET_PROTECTION) != 0)
7519                     .build();
7520             Slogf.i(LOG_TAG, "Factory resetting on boot using " + factoryResetter);
7521             try {
7522                 if (!factoryResetter.factoryReset()) {
7523                     // Shouldn't happen because FactoryResetter was created without a
7524                     // DevicePolicySafetyChecker.
7525                     Slogf.wtf(LOG_TAG, "Factory reset using " + factoryResetter + " failed.");
7526                 }
7527             } catch (IOException e) {
7528                 // Shouldn't happen.
7529                 Slogf.wtf(LOG_TAG, "Could not factory reset using " + factoryResetter, e);
7530             }
7531         }
7532     }
7533 
7534     private void forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently) {
7535         boolean success = false;
7536         try {
7537             if (getCurrentForegroundUserId() == userId) {
7538                 // TODO: We need to special case headless here as we can't switch to the system user
7539                 mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM);
7540             }
7541 
7542             success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
7543             if (!success) {
7544                 Slogf.w(LOG_TAG, "Couldn't remove user " + userId);
7545             } else if (isManagedProfile(userId) && !wipeSilently) {
7546                 sendWipeProfileNotification(wipeReasonForUser,
7547                         UserHandle.of(getProfileParentId(userId)));
7548             }
7549         } catch (RemoteException re) {
7550             // Shouldn't happen
7551             Slogf.wtf(LOG_TAG, "Error forcing wipe user", re);
7552         } finally {
7553             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
7554         }
7555     }
7556 
7557     @Override
7558     public void wipeDataWithReason(String callerPackageName, int flags,
7559             @NonNull String wipeReasonForUser, boolean calledOnParentInstance,
7560             boolean factoryReset) {
7561         if (!mHasFeature && !hasCallingOrSelfPermission(permission.MASTER_CLEAR)) {
7562             return;
7563         }
7564         CallerIdentity caller;
7565         if (isPolicyEngineForFinanceFlagEnabled()) {
7566             caller = getCallerIdentity(callerPackageName);
7567         }  else {
7568             caller = getCallerIdentity();
7569         }
7570         ActiveAdmin admin;
7571 
7572         boolean calledByProfileOwnerOnOrgOwnedDevice =
7573                 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId());
7574         if (isPolicyEngineForFinanceFlagEnabled()) {
7575             EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
7576                     /*admin=*/ null,
7577                     /*permission=*/ new String[]{MANAGE_DEVICE_POLICY_WIPE_DATA, MASTER_CLEAR},
7578                     USES_POLICY_WIPE_DATA,
7579                     caller.getPackageName(),
7580                     factoryReset ? UserHandle.USER_ALL : getAffectedUser(calledOnParentInstance));
7581             admin = enforcingAdmin.getActiveAdmin();
7582         } else {
7583             if (calledOnParentInstance) {
7584                 Preconditions.checkCallAuthorization(calledByProfileOwnerOnOrgOwnedDevice,
7585                         "Wiping the entire device can only be done by a profile owner on "
7586                                 + "organization-owned device.");
7587             }
7588             if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
7589                 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
7590                                 || calledByProfileOwnerOnOrgOwnedDevice
7591                                 || isFinancedDeviceOwner(caller),
7592                         "Only device owners or profile owners of organization-owned device can set "
7593                                 + "WIPE_RESET_PROTECTION_DATA");
7594             }
7595             synchronized (getLockObject()) {
7596                 admin = getActiveAdminWithPolicyForUidLocked(/* who= */ null,
7597                         DeviceAdminInfo.USES_POLICY_WIPE_DATA, caller.getUid());
7598             }
7599             Preconditions.checkCallAuthorization(
7600                     (admin != null) || hasCallingOrSelfPermission(permission.MASTER_CLEAR),
7601                     "No active admin for user %d and caller %d does not hold MASTER_CLEAR "
7602                             + "permission",
7603                     caller.getUserId(), caller.getUid());
7604         }
7605 
7606         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_WIPE_DATA);
7607 
7608         if (TextUtils.isEmpty(wipeReasonForUser)) {
7609             wipeReasonForUser = getGenericWipeReason(
7610                     calledByProfileOwnerOnOrgOwnedDevice, calledOnParentInstance);
7611         }
7612 
7613         int userId = admin != null ? admin.getUserHandle().getIdentifier()
7614                 : caller.getUserId();
7615         Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser, admin,
7616                 userId);
7617         if (calledByProfileOwnerOnOrgOwnedDevice) {
7618             // When wipeData is called on the parent instance, it implies wiping the entire device.
7619             if (calledOnParentInstance) {
7620                 userId = UserHandle.USER_SYSTEM;
7621             } else {
7622                 // when wipeData is _not_ called on the parent instance, it implies relinquishing
7623                 // control over the device, wiping only the work profile. So the user restriction
7624                 // on profile removal needs to be removed first.
7625                 final UserHandle parentUser = UserHandle.of(getProfileParentId(userId));
7626                 mInjector.binderWithCleanCallingIdentity(
7627                         () -> clearOrgOwnedProfileOwnerUserRestrictions(parentUser));
7628             }
7629         }
7630         DevicePolicyEventLogger event = DevicePolicyEventLogger
7631                 .createEvent(DevicePolicyEnums.WIPE_DATA_WITH_REASON)
7632                 .setInt(flags)
7633                 .setStrings(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT);
7634 
7635         final String adminName;
7636         final ComponentName adminComp;
7637         if (admin != null) {
7638             if (admin.isPermissionBased) {
7639                 adminComp = null;
7640                 adminName = caller.getPackageName();
7641                 event.setAdmin(adminName);
7642             } else {
7643                 adminComp = admin.info.getComponent();
7644                 adminName = adminComp.flattenToShortString();
7645                 event.setAdmin(adminComp);
7646             }
7647         } else {
7648             adminComp = null;
7649             adminName = mInjector.getPackageManager().getPackagesForUid(caller.getUid())[0];
7650             Slogf.i(LOG_TAG, "Logging wipeData() event admin as " + adminName);
7651             event.setAdmin(adminName);
7652             if (mInjector.userManagerIsHeadlessSystemUserMode()) {
7653                 // On headless system user mode, the call is meant to factory reset the whole
7654                 // device, otherwise the caller could simply remove the current user.
7655                 userId = UserHandle.USER_SYSTEM;
7656             }
7657         }
7658         event.write();
7659 
7660         String internalReason = String.format(
7661                 "DevicePolicyManager.wipeDataWithReason() from %s, organization-owned? %s",
7662                 adminName, calledByProfileOwnerOnOrgOwnedDevice);
7663 
7664         wipeDataNoLock(adminComp, flags, internalReason, wipeReasonForUser, userId,
7665                 calledOnParentInstance, factoryReset);
7666     }
7667 
7668     private String getGenericWipeReason(
7669             boolean calledByProfileOwnerOnOrgOwnedDevice, boolean calledOnParentInstance) {
7670         return calledByProfileOwnerOnOrgOwnedDevice && !calledOnParentInstance
7671                 ? getUpdatableString(
7672                         WORK_PROFILE_DELETED_ORG_OWNED_MESSAGE,
7673                         R.string.device_ownership_relinquished)
7674                 : getUpdatableString(
7675                         WORK_PROFILE_DELETED_GENERIC_MESSAGE,
7676                         R.string.work_profile_deleted_description_dpm_wipe);
7677     }
7678 
7679     /**
7680      * Clears device wide policies enforced by COPE PO when relinquishing the device. This method
7681      * should be invoked once the admin is gone, so that all methods that rely on calculating
7682      * aggregate policy (e.g. strong auth timeout) from all admins aren't affected by its policies.
7683      * This method assumes that there is no other device or profile owners left on the device.
7684      * Shouldn't be called from binder thread without clearing identity.
7685      */
7686     private void clearOrgOwnedProfileOwnerDeviceWidePolicies(@UserIdInt int parentId) {
7687         Slogf.i(LOG_TAG, "Cleaning up device-wide policies left over from org-owned profile...");
7688         // Lockscreen message
7689         mLockPatternUtils.setDeviceOwnerInfo(null);
7690         // Wifi config lockdown
7691         mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
7692         // Security logging
7693         if (mInjector.securityLogGetLoggingEnabledProperty()) {
7694             mSecurityLogMonitor.stop();
7695             mInjector.securityLogSetLoggingEnabledProperty(false);
7696         }
7697         // Network logging
7698         setNetworkLoggingActiveInternal(false);
7699 
7700         // System update policy.
7701         final boolean hasSystemUpdatePolicy;
7702         synchronized (getLockObject()) {
7703             hasSystemUpdatePolicy = mOwners.getSystemUpdatePolicy() != null;
7704             if (hasSystemUpdatePolicy) {
7705                 mOwners.clearSystemUpdatePolicy();
7706                 mOwners.writeDeviceOwner();
7707             }
7708         }
7709         if (hasSystemUpdatePolicy) {
7710             mContext.sendBroadcastAsUser(
7711                     new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM);
7712         }
7713 
7714         // Unsuspend personal apps if needed.
7715         suspendPersonalAppsInternal(parentId, getManagedUserId(parentId), false);
7716 
7717         // Notify FRP agent, LSS and WindowManager to ensure they don't hold on to stale policies.
7718         final int frpAgentUid = getFrpManagementAgentUid();
7719         if (frpAgentUid > 0) {
7720             notifyResetProtectionPolicyChanged(frpAgentUid);
7721         }
7722         mLockSettingsInternal.refreshStrongAuthTimeout(parentId);
7723 
7724         clearManagedSubscriptionsPolicy();
7725         clearLauncherShortcutOverrides();
7726         updateTelephonyCrossProfileIntentFilters(parentId, UserHandle.USER_NULL, false);
7727 
7728         Slogf.i(LOG_TAG, "Cleaning up device-wide policies done.");
7729     }
7730 
7731     private void clearManagedSubscriptionsPolicy() {
7732         unregisterOnSubscriptionsChangedListener();
7733 
7734         SubscriptionManager subscriptionManager = mContext.getSystemService(
7735                 SubscriptionManager.class);
7736         //Iterate over all the subscriptions and remove association with any user.
7737         int[] subscriptionIds = subscriptionManager.getActiveSubscriptionIdList(false);
7738         for (int subId : subscriptionIds) {
7739             subscriptionManager.setSubscriptionUserHandle(subId, null);
7740         }
7741     }
7742 
7743     private void clearLauncherShortcutOverrides() {
7744         mPolicyCache.setLauncherShortcutOverrides(new ArrayMap<>());
7745     }
7746 
7747     private void updateTelephonyCrossProfileIntentFilters(int parentUserId, int profileUserId,
7748             boolean enableWorkTelephony) {
7749         try {
7750             // This should only occur when managed profile is being removed.
7751             if (!enableWorkTelephony && profileUserId == UserHandle.USER_NULL) {
7752                 mIPackageManager.clearCrossProfileIntentFilters(parentUserId,
7753                         mContext.getPackageName());
7754                 return;
7755             }
7756             for (DefaultCrossProfileIntentFilter filter :
7757                     DefaultCrossProfileIntentFiltersUtils
7758                             .getDefaultCrossProfileTelephonyIntentFilters(!enableWorkTelephony)) {
7759                 if (removeCrossProfileIntentFilter(filter, parentUserId, profileUserId)) {
7760                     Slogf.w(LOG_TAG,
7761                             "Failed to remove cross-profile intent filter: "
7762                                     + filter.filter.getIntentFilter() + ", enableWorkTelephony: "
7763                                     + enableWorkTelephony);
7764                 }
7765             }
7766             for (DefaultCrossProfileIntentFilter filter :
7767                     DefaultCrossProfileIntentFiltersUtils
7768                             .getDefaultCrossProfileTelephonyIntentFilters(enableWorkTelephony)) {
7769                 addCrossProfileIntentFilter(filter, parentUserId, profileUserId);
7770             }
7771         } catch (RemoteException re) {
7772             Slogf.wtf(LOG_TAG, "Error updating telephony cross profile intent filters", re);
7773         }
7774     }
7775 
7776     void addCrossProfileIntentFilter(DefaultCrossProfileIntentFilter filter, int parentUserId,
7777             int profileUserId)
7778             throws RemoteException {
7779         if (filter.direction == DefaultCrossProfileIntentFilter.Direction.TO_PROFILE) {
7780             mIPackageManager.addCrossProfileIntentFilter(
7781                     filter.filter.getIntentFilter(),
7782                     mContext.getOpPackageName(),
7783                     parentUserId,
7784                     profileUserId,
7785                     filter.flags);
7786         } else {
7787             mIPackageManager.addCrossProfileIntentFilter(
7788                     filter.filter.getIntentFilter(),
7789                     mContext.getOpPackageName(),
7790                     profileUserId,
7791                     parentUserId,
7792                     filter.flags);
7793         }
7794     }
7795 
7796     boolean removeCrossProfileIntentFilter(DefaultCrossProfileIntentFilter filter, int parentUserId,
7797             int profileUserId)
7798             throws RemoteException {
7799         if (filter.direction == DefaultCrossProfileIntentFilter.Direction.TO_PROFILE) {
7800             return mIPackageManager.removeCrossProfileIntentFilter(
7801                     filter.filter.getIntentFilter(),
7802                     mContext.getOpPackageName(),
7803                     parentUserId,
7804                     profileUserId,
7805                     filter.flags);
7806         } else {
7807             return mIPackageManager.removeCrossProfileIntentFilter(
7808                     filter.filter.getIntentFilter(),
7809                     mContext.getOpPackageName(),
7810                     profileUserId,
7811                     parentUserId,
7812                     filter.flags);
7813         }
7814     }
7815 
7816     /**
7817      * @param factoryReset null: legacy behaviour, false: attempt to remove user, true: attempt to
7818      *                     factory reset
7819      */
7820     private void wipeDataNoLock(@Nullable ComponentName admin, int flags, String internalReason,
7821             String wipeReasonForUser, int userId, boolean calledOnParentInstance,
7822             @Nullable Boolean factoryReset) {
7823         wtfIfInLock();
7824         final String adminPackage;
7825         if (admin != null) {
7826             adminPackage = admin.getPackageName();
7827         } else {
7828             int callerId = mInjector.binderGetCallingUid();
7829             String[] adminPackages = mInjector.getPackageManager().getPackagesForUid(callerId);
7830             Preconditions.checkState(adminPackages.length > 0,
7831                     "Caller %s does not have any associated packages", callerId);
7832             adminPackage = adminPackages[0];
7833         }
7834         mInjector.binderWithCleanCallingIdentity(() -> {
7835             // First check whether the admin is allowed to wipe the device/user/profile.
7836             final String restriction;
7837             if (userId == UserHandle.USER_SYSTEM) {
7838                 restriction = UserManager.DISALLOW_FACTORY_RESET;
7839             } else if (isManagedProfile(userId)) {
7840                 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
7841             } else {
7842                 restriction = UserManager.DISALLOW_REMOVE_USER;
7843             }
7844             if (isAdminAffectedByRestriction(admin, restriction, userId)) {
7845                 throw new SecurityException("Cannot wipe data. " + restriction
7846                         + " restriction is set for user " + userId);
7847             }
7848         });
7849 
7850         boolean isSystemUser = userId == UserHandle.USER_SYSTEM;
7851         boolean wipeDevice;
7852         if (factoryReset == null || !mInjector.isChangeEnabled(EXPLICIT_WIPE_BEHAVIOUR,
7853                 adminPackage,
7854                 userId)) {
7855             // Legacy mode
7856             wipeDevice = isSystemUser;
7857         } else {
7858             // Explicit behaviour
7859             if (factoryReset) {
7860                 EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
7861                         /*admin=*/ null,
7862                         /*permission=*/ new String[]{MANAGE_DEVICE_POLICY_WIPE_DATA,
7863                                 MASTER_CLEAR},
7864                         USES_POLICY_WIPE_DATA,
7865                         adminPackage,
7866                         factoryReset ? UserHandle.USER_ALL :
7867                                 getAffectedUser(calledOnParentInstance));
7868                 wipeDevice = true;
7869             } else {
7870                 mInjector.binderWithCleanCallingIdentity(() -> {
7871                     Preconditions.checkCallAuthorization(!isSystemUser,
7872                             "User %s is a system user and cannot be removed", userId);
7873                     boolean isLastNonHeadlessUser = getUserInfo(userId).isFull()
7874                             && mUserManager.getAliveUsers().stream()
7875                             .filter((it) -> it.getUserHandle().getIdentifier() != userId)
7876                             .noneMatch(UserInfo::isFull);
7877                     Preconditions.checkState(!isLastNonHeadlessUser,
7878                             "Removing user %s would leave the device without any active users. "
7879                                     + "Consider factory resetting the device instead.",
7880                             userId);
7881                 });
7882                 wipeDevice = false;
7883             }
7884         }
7885         mInjector.binderWithCleanCallingIdentity(() -> {
7886             if (wipeDevice) {
7887                 forceWipeDeviceNoLock(
7888                         (flags & WIPE_EXTERNAL_STORAGE) != 0,
7889                         internalReason,
7890                         (flags & WIPE_EUICC) != 0,
7891                         (flags & WIPE_RESET_PROTECTION_DATA) != 0);
7892             } else {
7893                 forceWipeUser(userId, wipeReasonForUser, (flags & WIPE_SILENTLY) != 0);
7894             }
7895         });
7896     }
7897 
7898     private void sendWipeProfileNotification(String wipeReasonForUser, UserHandle user) {
7899         Notification notification =
7900                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
7901                         .setSmallIcon(android.R.drawable.stat_sys_warning)
7902                         .setContentTitle(getWorkProfileDeletedTitle())
7903                         .setContentText(wipeReasonForUser)
7904                         .setColor(mContext.getColor(R.color.system_notification_accent_color))
7905                         .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
7906                         .build();
7907         mInjector.getNotificationManager().notifyAsUser(
7908                 /* tag= */ null, SystemMessage.NOTE_PROFILE_WIPED, notification, user);
7909     }
7910 
7911     private String getWorkProfileDeletedTitle() {
7912         return getUpdatableString(WORK_PROFILE_DELETED_TITLE, R.string.work_profile_deleted);
7913     }
7914 
7915     private void clearWipeProfileNotification() {
7916         mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
7917     }
7918 
7919     @Override
7920     public void setFactoryResetProtectionPolicy(ComponentName who, String callerPackageName,
7921             @Nullable FactoryResetProtectionPolicy policy) {
7922         if (!mHasFeature) {
7923             return;
7924         }
7925         if (!isPermissionCheckFlagEnabled()) {
7926             Preconditions.checkNotNull(who, "ComponentName is null");
7927         }
7928         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
7929         if (!isPermissionCheckFlagEnabled()) {
7930             Preconditions.checkCallAuthorization(
7931                     isDefaultDeviceOwner(caller)
7932                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
7933         }
7934         checkCanExecuteOrThrowUnsafe(DevicePolicyManager
7935                 .OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY);
7936 
7937         final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow();
7938         synchronized (getLockObject()) {
7939             ActiveAdmin admin;
7940             if (isPermissionCheckFlagEnabled()) {
7941                 admin = enforcePermissionAndGetEnforcingAdmin(
7942                         who, MANAGE_DEVICE_POLICY_FACTORY_RESET, caller.getPackageName(),
7943                         UserHandle.USER_ALL)
7944                         .getActiveAdmin();
7945             } else {
7946                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
7947             }
7948             admin.mFactoryResetProtectionPolicy = policy;
7949             saveSettingsLocked(caller.getUserId());
7950         }
7951 
7952         mInjector.binderWithCleanCallingIdentity(
7953                 () -> notifyResetProtectionPolicyChanged(frpManagementAgentUid));
7954 
7955         DevicePolicyEventLogger
7956                 .createEvent(DevicePolicyEnums.SET_FACTORY_RESET_PROTECTION)
7957                 .setAdmin(caller.getPackageName())
7958                 .write();
7959     }
7960 
7961     // Shouldn't be called from binder thread without clearing identity.
7962     private void notifyResetProtectionPolicyChanged(int frpManagementAgentUid) {
7963         final Intent intent = new Intent(
7964                 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED).addFlags(
7965                 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND | Intent.FLAG_RECEIVER_FOREGROUND);
7966         mContext.sendBroadcastAsUser(intent,
7967                 UserHandle.getUserHandleForUid(frpManagementAgentUid),
7968                 permission.MANAGE_FACTORY_RESET_PROTECTION);
7969     }
7970 
7971     @Override
7972     public FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
7973             @Nullable ComponentName who) {
7974         if (!mHasFeature) {
7975             return null;
7976         }
7977 
7978         final CallerIdentity caller = getCallerIdentity(who);
7979         final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow();
7980         final ActiveAdmin admin;
7981         synchronized (getLockObject()) {
7982             if (who == null) {
7983                 Preconditions.checkCallAuthorization(frpManagementAgentUid == caller.getUid()
7984                                 || hasCallingPermission(permission.MASTER_CLEAR)
7985                                 || hasCallingPermission(MANAGE_DEVICE_POLICY_FACTORY_RESET),
7986                         "Must be called by the FRP management agent on device");
7987                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked();
7988             } else {
7989                 Preconditions.checkCallAuthorization(
7990                         isDefaultDeviceOwner(caller)
7991                                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
7992                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
7993             }
7994         }
7995 
7996         return admin != null ? admin.mFactoryResetProtectionPolicy : null;
7997     }
7998 
7999     private int getFrpManagementAgentUid() {
8000         PersistentDataBlockManagerInternal pdb = mInjector.getPersistentDataBlockManagerInternal();
8001         return pdb != null ? pdb.getAllowedUid() : -1;
8002     }
8003 
8004     private int getFrpManagementAgentUidOrThrow() {
8005         int uid = getFrpManagementAgentUid();
8006         if (uid == -1) {
8007             throw new UnsupportedOperationException(
8008                     "The persistent data block service is not supported on this device");
8009         }
8010         return uid;
8011     }
8012 
8013     @Override
8014     public boolean isFactoryResetProtectionPolicySupported() {
8015         return getFrpManagementAgentUid() != -1;
8016     }
8017 
8018     @Override
8019     public void sendLostModeLocationUpdate(AndroidFuture<Boolean> future) {
8020         if (!mHasFeature) {
8021             future.complete(false);
8022             return;
8023         }
8024         Preconditions.checkCallAuthorization(
8025                 hasCallingOrSelfPermission(permission.TRIGGER_LOST_MODE));
8026 
8027         synchronized (getLockObject()) {
8028             // TODO(b/261999445): Remove
8029             ActiveAdmin admin;
8030             if (isHeadlessFlagEnabled()) {
8031                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
8032             } else {
8033                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
8034                         UserHandle.USER_SYSTEM);
8035             }
8036             Preconditions.checkState(admin != null,
8037                     "Lost mode location updates can only be sent on an organization-owned device.");
8038             mInjector.binderWithCleanCallingIdentity(() -> {
8039                 String[] providers = {LocationManager.FUSED_PROVIDER,
8040                         LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER};
8041                 tryRetrieveAndSendLocationUpdate(admin, future, providers, /* index= */ 0);
8042             });
8043         }
8044     }
8045 
8046     /** Send lost mode location updates recursively, in order of the list of location providers. */
8047     private void tryRetrieveAndSendLocationUpdate(ActiveAdmin admin,
8048             AndroidFuture<Boolean> future, String[] providers, int index) {
8049         // None of the providers were able to get location, return false
8050         if (index == providers.length) {
8051             future.complete(false);
8052             return;
8053         }
8054         if (mInjector.getLocationManager().isProviderEnabled(providers[index])) {
8055             mInjector.getLocationManager().getCurrentLocation(providers[index],
8056                     /* cancellationSignal= */ null, mContext.getMainExecutor(), location -> {
8057                         if (location != null) {
8058                             mContext.sendBroadcastAsUser(
8059                                     newLostModeLocationUpdateIntent(admin, location),
8060                                     admin.getUserHandle());
8061                             future.complete(true);
8062                         } else {
8063                             tryRetrieveAndSendLocationUpdate(admin, future, providers, index + 1);
8064                         }
8065                     }
8066             );
8067         } else {
8068            tryRetrieveAndSendLocationUpdate(admin, future, providers, index + 1);
8069         }
8070     }
8071 
8072     private Intent newLostModeLocationUpdateIntent(ActiveAdmin admin, Location location) {
8073         final Intent intent = new Intent(
8074                 DevicePolicyManager.ACTION_LOST_MODE_LOCATION_UPDATE);
8075         intent.putExtra(DevicePolicyManager.EXTRA_LOST_MODE_LOCATION, location);
8076         intent.setPackage(admin.info.getPackageName());
8077         return intent;
8078     }
8079 
8080     /**
8081      * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
8082      * the remove warning for the given device admin.
8083      */
8084     @Override
8085     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
8086         if (!mHasFeature) {
8087             return;
8088         }
8089         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8090 
8091         final CallerIdentity caller = getCallerIdentity();
8092         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8093         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8094 
8095         synchronized (getLockObject()) {
8096             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
8097             if (admin == null) {
8098                 result.sendResult(null);
8099                 return;
8100             }
8101             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
8102             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8103             intent.setComponent(admin.info.getComponent());
8104             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
8105                     null, new BroadcastReceiver() {
8106                 @Override
8107                 public void onReceive(Context context, Intent intent) {
8108                     result.sendResult(getResultExtras(false));
8109                 }
8110             }, null, Activity.RESULT_OK, null, null);
8111         }
8112     }
8113 
8114     @Override
8115     public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) {
8116         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
8117             return;
8118         }
8119 
8120         final CallerIdentity caller = getCallerIdentity();
8121         Preconditions.checkCallAuthorization(isSystemUid(caller));
8122         // Managed Profile password can only be changed when it has a separate challenge.
8123         if (!isSeparateProfileChallengeEnabled(userId)) {
8124             Preconditions.checkCallAuthorization(!isManagedProfile(userId), "You can "
8125                     + "not set the active password for a managed profile, userId = %d", userId);
8126         }
8127 
8128         DevicePolicyData policy = getUserData(userId);
8129         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
8130 
8131         synchronized (getLockObject()) {
8132             policy.mFailedPasswordAttempts = 0;
8133             affectedUserIds.add(userId);
8134             affectedUserIds.addAll(updatePasswordValidityCheckpointLocked(
8135                     userId, /* parent */ false));
8136             affectedUserIds.addAll(updatePasswordExpirationsLocked(userId));
8137             setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
8138 
8139             // Send a broadcast to each profile using this password as its primary unlock.
8140             sendAdminCommandForLockscreenPoliciesLocked(
8141                     DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
8142                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
8143 
8144             affectedUserIds.addAll(removeCaApprovalsIfNeeded(userId));
8145             saveSettingsForUsersLocked(affectedUserIds);
8146         }
8147         if (mInjector.securityLogIsLoggingEnabled()) {
8148             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_CHANGED,
8149                     /* complexity */ metrics.determineComplexity(), /*user*/ userId);
8150         }
8151     }
8152 
8153     /**
8154      * Called any time the device password is updated. Resets all password expiration clocks.
8155      *
8156      * @return the set of user IDs that have been affected
8157      */
8158     @GuardedBy("getLockObject()")
8159     private Set<Integer> updatePasswordExpirationsLocked(int userHandle) {
8160         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
8161         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
8162         for (int i = 0; i < admins.size(); i++) {
8163             ActiveAdmin admin = admins.get(i);
8164             if (admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
8165                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
8166                 long timeout = admin.passwordExpirationTimeout;
8167                 admin.passwordExpirationDate =
8168                         timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
8169             }
8170         }
8171         return affectedUserIds;
8172     }
8173 
8174     @Override
8175     public void reportFailedPasswordAttempt(int userHandle, boolean parent) {
8176         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8177 
8178         final CallerIdentity caller = getCallerIdentity();
8179         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8180         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8181         if (!isSeparateProfileChallengeEnabled(userHandle)) {
8182             Preconditions.checkCallAuthorization(!isManagedProfile(userHandle),
8183                     "You can not report failed password attempt if separate profile challenge is "
8184                             + "not in place for a managed profile, userId = %d", userHandle);
8185         }
8186 
8187         boolean wipeData = false;
8188         ActiveAdmin strictestAdmin = null;
8189         final long ident = mInjector.binderClearCallingIdentity();
8190         try {
8191             synchronized (getLockObject()) {
8192                 DevicePolicyData policy = getUserData(userHandle);
8193                 policy.mFailedPasswordAttempts++;
8194                 saveSettingsLocked(userHandle);
8195                 if (mHasFeature) {
8196                     strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
8197                             userHandle, /* parent= */ false);
8198                     int max = strictestAdmin != null
8199                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
8200                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
8201                         wipeData = true;
8202                     }
8203 
8204                     sendAdminCommandForLockscreenPoliciesLocked(
8205                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
8206                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
8207                 }
8208             }
8209         } finally {
8210             mInjector.binderRestoreCallingIdentity(ident);
8211         }
8212 
8213         if (wipeData && strictestAdmin != null) {
8214             final int userId = getUserIdToWipeForFailedPasswords(strictestAdmin);
8215             Slogf.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
8216                     + strictestAdmin.info.getComponent().flattenToShortString()
8217                     + ". Calling wipeData for user " + userId);
8218 
8219             // Attempt to wipe the device/user/profile associated with the admin, as if the
8220             // admin had called wipeData(). That way we can check whether the admin is actually
8221             // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
8222             // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
8223             // able to do so).
8224             // IMPORTANT: Call without holding the lock to prevent deadlock.
8225             try {
8226                 wipeDataNoLock(strictestAdmin.info.getComponent(),
8227                         /* flags= */ 0,
8228                         /* reason= */ "reportFailedPasswordAttempt()",
8229                         getFailedPasswordAttemptWipeMessage(),
8230                         userId,
8231                         /* calledOnParentInstance= */ parent,
8232                         // factoryReset=null to enable U- behaviour
8233                         /* factoryReset= */ null);
8234             } catch (SecurityException e) {
8235                 Slogf.w(LOG_TAG, "Failed to wipe user " + userId
8236                         + " after max failed password attempts reached.", e);
8237             }
8238         }
8239 
8240         if (mInjector.securityLogIsLoggingEnabled()) {
8241             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
8242                     /* result= */ 0, /* method strength= */ 1);
8243         }
8244     }
8245 
8246     private String getFailedPasswordAttemptWipeMessage() {
8247         return getUpdatableString(
8248                 WORK_PROFILE_DELETED_FAILED_PASSWORD_ATTEMPTS_MESSAGE,
8249                R.string.work_profile_deleted_reason_maximum_password_failure);
8250     }
8251 
8252     /**
8253      * Returns which user should be wiped if this admin's maximum filed password attempts policy is
8254      * violated.
8255      */
8256     private int getUserIdToWipeForFailedPasswords(ActiveAdmin admin) {
8257         final int userId = admin.getUserHandle().getIdentifier();
8258         if (admin.isPermissionBased) {
8259             return userId;
8260         }
8261         final ComponentName component = admin.info.getComponent();
8262         return isProfileOwnerOfOrganizationOwnedDevice(component, userId)
8263                 ? getProfileParentId(userId) : userId;
8264     }
8265 
8266     @Override
8267     public void reportSuccessfulPasswordAttempt(int userHandle) {
8268         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8269 
8270         final CallerIdentity caller = getCallerIdentity();
8271         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8272         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8273 
8274         synchronized (getLockObject()) {
8275             DevicePolicyData policy = getUserData(userHandle);
8276             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
8277                 mInjector.binderWithCleanCallingIdentity(() -> {
8278                     policy.mFailedPasswordAttempts = 0;
8279                     policy.mPasswordOwner = -1;
8280                     saveSettingsLocked(userHandle);
8281                     if (mHasFeature) {
8282                         sendAdminCommandForLockscreenPoliciesLocked(
8283                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
8284                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
8285                     }
8286                 });
8287             }
8288         }
8289 
8290         if (mInjector.securityLogIsLoggingEnabled()) {
8291             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
8292                     /*method strength*/ 1);
8293         }
8294     }
8295 
8296     @Override
8297     public void reportFailedBiometricAttempt(int userHandle) {
8298         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8299 
8300         final CallerIdentity caller = getCallerIdentity();
8301         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8302         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8303 
8304         if (mInjector.securityLogIsLoggingEnabled()) {
8305             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
8306                     /*method strength*/ 0);
8307         }
8308     }
8309 
8310     @Override
8311     public void reportSuccessfulBiometricAttempt(int userHandle) {
8312         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8313 
8314         final CallerIdentity caller = getCallerIdentity();
8315         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8316         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8317 
8318         if (mInjector.securityLogIsLoggingEnabled()) {
8319             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
8320                     /*method strength*/ 0);
8321         }
8322     }
8323 
8324     @Override
8325     public void reportKeyguardDismissed(int userHandle) {
8326         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8327 
8328         final CallerIdentity caller = getCallerIdentity();
8329         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8330         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8331 
8332         if (mInjector.securityLogIsLoggingEnabled()) {
8333             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
8334         }
8335     }
8336 
8337     @Override
8338     public void reportKeyguardSecured(int userHandle) {
8339         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8340 
8341         final CallerIdentity caller = getCallerIdentity();
8342         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8343         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8344 
8345         if (mInjector.securityLogIsLoggingEnabled()) {
8346             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
8347         }
8348     }
8349 
8350     @Override
8351     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
8352             String exclusionList) {
8353         if (!mHasFeature) {
8354             return null;
8355         }
8356         synchronized (getLockObject()) {
8357             Objects.requireNonNull(who, "ComponentName is null");
8358 
8359             // Only check if system user has set global proxy. We don't allow other users to set it.
8360             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
8361             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8362                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
8363 
8364             // Scan through active admins and find if anyone has already
8365             // set the global proxy.
8366             Set<ComponentName> compSet = policy.mAdminMap.keySet();
8367             for (ComponentName component : compSet) {
8368                 ActiveAdmin ap = policy.mAdminMap.get(component);
8369                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
8370                     // Another admin already sets the global proxy
8371                     // Return it to the caller.
8372                     return component;
8373                 }
8374             }
8375 
8376             // If the user is not system, don't set the global proxy. Fail silently.
8377             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8378                 Slogf.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
8379                         + UserHandle.getCallingUserId() + " is not permitted.");
8380                 return null;
8381             }
8382             if (proxySpec == null) {
8383                 admin.specifiesGlobalProxy = false;
8384                 admin.globalProxySpec = null;
8385                 admin.globalProxyExclusionList = null;
8386             } else {
8387 
8388                 admin.specifiesGlobalProxy = true;
8389                 admin.globalProxySpec = proxySpec;
8390                 admin.globalProxyExclusionList = exclusionList;
8391             }
8392 
8393             // Reset the global proxy accordingly
8394             // Do this using system permissions, as apps cannot write to secure settings
8395             mInjector.binderWithCleanCallingIdentity(() -> resetGlobalProxyLocked(policy));
8396             return null;
8397         }
8398     }
8399 
8400     @Override
8401     public ComponentName getGlobalProxyAdmin(int userHandle) {
8402         if (!mHasFeature) {
8403             return null;
8404         }
8405         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8406 
8407         final CallerIdentity caller = getCallerIdentity();
8408         Preconditions.checkCallAuthorization(
8409                 hasFullCrossUsersPermission(caller, userHandle) && canQueryAdminPolicy(caller));
8410 
8411         synchronized (getLockObject()) {
8412             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
8413             // Scan through active admins and find if anyone has already
8414             // set the global proxy.
8415             final int N = policy.mAdminList.size();
8416             for (int i = 0; i < N; i++) {
8417                 ActiveAdmin ap = policy.mAdminList.get(i);
8418                 if (ap.specifiesGlobalProxy) {
8419                     // Device admin sets the global proxy
8420                     // Return it to the caller.
8421                     return ap.info.getComponent();
8422                 }
8423             }
8424         }
8425         // No device admin sets the global proxy.
8426         return null;
8427     }
8428 
8429     @Override
8430     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
8431         Objects.requireNonNull(who, "ComponentName is null");
8432         final CallerIdentity caller = getCallerIdentity(who);
8433         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
8434         checkAllUsersAreAffiliatedWithDevice();
8435         mInjector.binderWithCleanCallingIdentity(
8436                 () -> mInjector.getConnectivityManager().setGlobalProxy(proxyInfo));
8437     }
8438 
8439     private void resetGlobalProxyLocked(DevicePolicyData policy) {
8440         final int N = policy.mAdminList.size();
8441         for (int i = 0; i < N; i++) {
8442             ActiveAdmin ap = policy.mAdminList.get(i);
8443             if (ap.specifiesGlobalProxy) {
8444                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
8445                 return;
8446             }
8447         }
8448         // No device admins defining global proxies - reset global proxy settings to none
8449         saveGlobalProxyLocked(null, null);
8450     }
8451 
8452     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
8453         if (exclusionList == null) {
8454             exclusionList = "";
8455         }
8456         if (proxySpec == null) {
8457             proxySpec = "";
8458         }
8459         // Remove white spaces
8460         proxySpec = proxySpec.trim();
8461         String data[] = proxySpec.split(":");
8462         int proxyPort = 8080;
8463         if (data.length > 1) {
8464             try {
8465                 proxyPort = Integer.parseInt(data[1]);
8466             } catch (NumberFormatException e) {}
8467         }
8468         exclusionList = exclusionList.trim();
8469 
8470         ProxyInfo proxyProperties = ProxyInfo.buildDirectProxy(data[0], proxyPort,
8471                 ProxyUtils.exclusionStringAsList(exclusionList));
8472         if (!proxyProperties.isValid()) {
8473             Slogf.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
8474             return;
8475         }
8476         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
8477         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
8478         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
8479                 exclusionList);
8480     }
8481 
8482     /**
8483      * Called by an application that is administering the device to request that the storage system
8484      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
8485      *
8486      * @return the new total request status (for all admins), or {@link
8487      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user
8488      */
8489     @Override
8490     public int setStorageEncryption(ComponentName who, boolean encrypt) {
8491         if (!mHasFeature) {
8492             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8493         }
8494         Objects.requireNonNull(who, "ComponentName is null");
8495         final int userHandle = UserHandle.getCallingUserId();
8496         synchronized (getLockObject()) {
8497             // Check for permissions
8498             // Only system user can set storage encryption
8499             if (userHandle != UserHandle.USER_SYSTEM) {
8500                 Slogf.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. "
8501                         + "User " + UserHandle.getCallingUserId() + " is not permitted.");
8502                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8503             }
8504 
8505             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
8506                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
8507 
8508             // Quick exit:  If the filesystem does not support encryption, we can exit early.
8509             if (!isEncryptionSupported()) {
8510                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8511             }
8512 
8513             // (1) Record the value for the admin so it's sticky
8514             if (ap.encryptionRequested != encrypt) {
8515                 ap.encryptionRequested = encrypt;
8516                 saveSettingsLocked(userHandle);
8517             }
8518 
8519             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
8520             // (2) Compute "max" for all admins
8521             boolean newRequested = false;
8522             final int N = policy.mAdminList.size();
8523             for (int i = 0; i < N; i++) {
8524                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
8525             }
8526 
8527             // Notify OS of new request
8528             setEncryptionRequested(newRequested);
8529 
8530             // Return the new global request status
8531             return newRequested
8532                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
8533                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
8534         }
8535     }
8536 
8537     /**
8538      * Get the current storage encryption request status for a given admin, or aggregate of all
8539      * active admins.
8540      */
8541     @Override
8542     public boolean getStorageEncryption(@Nullable ComponentName who, int userHandle) {
8543         if (!mHasFeature) {
8544             return false;
8545         }
8546         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8547 
8548         final CallerIdentity caller = getCallerIdentity(who);
8549         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8550 
8551         synchronized (getLockObject()) {
8552             // Check for permissions if a particular caller is specified
8553             if (caller.hasAdminComponent()) {
8554                 // When checking for a single caller, status is based on caller's request
8555                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
8556                 return ap != null ? ap.encryptionRequested : false;
8557             }
8558 
8559             // If no particular caller is specified, return the aggregate set of requests.
8560             // This is short circuited by returning true on the first hit.
8561             DevicePolicyData policy = getUserData(userHandle);
8562             final int N = policy.mAdminList.size();
8563             for (int i = 0; i < N; i++) {
8564                 if (policy.mAdminList.get(i).encryptionRequested) {
8565                     return true;
8566                 }
8567             }
8568             return false;
8569         }
8570     }
8571 
8572     /**
8573      * Get the current encryption status of the device.
8574      */
8575     @Override
8576     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
8577         if (!mHasFeature) {
8578             // Ok to return current status.
8579         }
8580         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8581 
8582         final CallerIdentity caller = getCallerIdentity(callerPackage);
8583         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8584 
8585 
8586         final ApplicationInfo ai;
8587         try {
8588             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
8589         } catch (RemoteException e) {
8590             throw new SecurityException(e);
8591         }
8592 
8593         boolean legacyApp = false;
8594         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
8595             legacyApp = true;
8596         }
8597 
8598         final int rawStatus = getEncryptionStatus();
8599         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
8600             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
8601         }
8602         return rawStatus;
8603     }
8604 
8605     /**
8606      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
8607      */
8608     private boolean isEncryptionSupported() {
8609         // Note, this can be implemented as
8610         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8611         // But is provided as a separate internal method if there's a faster way to do a
8612         // simple check for supported-or-not.
8613         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8614     }
8615 
8616     /**
8617      * Hook to low-levels:  Reporting the current status of encryption.
8618      * @return Either {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}
8619      * or {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}.
8620      */
8621     private int getEncryptionStatus() {
8622         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
8623             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
8624         } else {
8625             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8626         }
8627     }
8628 
8629     /**
8630      * Hook to low-levels:  If needed, record the new admin setting for encryption.
8631      */
8632     private void setEncryptionRequested(boolean encrypt) {
8633     }
8634 
8635     /**
8636      * Set whether the screen capture is disabled for the user managed by the specified admin.
8637      */
8638     @Override
8639     public void setScreenCaptureDisabled(
8640             ComponentName who, String callerPackage, boolean disabled, boolean parent) {
8641         if (!mHasFeature) {
8642             return;
8643         }
8644 
8645         CallerIdentity caller;
8646         if (isPolicyEngineForFinanceFlagEnabled()) {
8647             caller = getCallerIdentity(who, callerPackage);
8648         } else {
8649             Objects.requireNonNull(who, "ComponentName is null");
8650             caller = getCallerIdentity(who);
8651             if (parent) {
8652                 Preconditions.checkCallAuthorization(
8653                         isProfileOwnerOfOrganizationOwnedDevice(caller));
8654             } else {
8655                 Preconditions.checkCallAuthorization(isProfileOwner(caller)
8656                         || isDefaultDeviceOwner(caller));
8657             }
8658         }
8659 
8660         if (isPolicyEngineForFinanceFlagEnabled()) {
8661             int callerUserId = Binder.getCallingUserHandle().getIdentifier();
8662             int targetUserId = parent ? getProfileParentId(callerUserId) : callerUserId;
8663             EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
8664                     who, MANAGE_DEVICE_POLICY_SCREEN_CAPTURE, caller.getPackageName(),
8665                     targetUserId);
8666             if ((parent && isProfileOwnerOfOrganizationOwnedDevice(caller))
8667                     || isDefaultDeviceOwner(caller)) {
8668                 if (disabled) {
8669                     mDevicePolicyEngine.setGlobalPolicy(
8670                             PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8671                             admin,
8672                             new BooleanPolicyValue(disabled));
8673                 } else {
8674                     mDevicePolicyEngine.removeGlobalPolicy(
8675                             PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8676                             admin);
8677                 }
8678             } else {
8679                 if (disabled) {
8680                     mDevicePolicyEngine.setLocalPolicy(
8681                             PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8682                             admin,
8683                             new BooleanPolicyValue(disabled),
8684                             callerUserId);
8685                 } else {
8686                     mDevicePolicyEngine.removeLocalPolicy(
8687                             PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8688                             admin,
8689                             callerUserId);
8690                 }
8691             }
8692         } else {
8693             synchronized (getLockObject()) {
8694                 ActiveAdmin ap = getParentOfAdminIfRequired(
8695                         getProfileOwnerOrDefaultDeviceOwnerLocked(caller.getUserId()), parent);
8696                 if (ap.disableScreenCapture != disabled) {
8697                     ap.disableScreenCapture = disabled;
8698                     saveSettingsLocked(caller.getUserId());
8699                     pushScreenCapturePolicy(caller.getUserId());
8700                 }
8701             }
8702         }
8703         DevicePolicyEventLogger
8704                 .createEvent(DevicePolicyEnums.SET_SCREEN_CAPTURE_DISABLED)
8705                 .setAdmin(caller.getPackageName())
8706                 .setBoolean(disabled)
8707                 .write();
8708     }
8709 
8710     // Push the screen capture policy for a given userId. If screen capture is disabled by the
8711     // DO or COPE PO on the parent profile, then this takes precedence as screen capture will
8712     // be disabled device-wide.
8713     private void pushScreenCapturePolicy(int adminUserId) {
8714         if (isPolicyEngineForFinanceFlagEnabled()) {
8715             return;
8716         }
8717         // Update screen capture device-wide if disabled by the DO or COPE PO on the parent profile.
8718         // TODO(b/261999445): remove
8719         ActiveAdmin admin;
8720         if (isHeadlessFlagEnabled()) {
8721             admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceParentLocked(
8722                     mUserManagerInternal.getProfileParentId(adminUserId));
8723         } else {
8724             admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceParentLocked(
8725                     UserHandle.USER_SYSTEM);
8726         }
8727         if (admin != null && admin.disableScreenCapture) {
8728             setScreenCaptureDisabled(UserHandle.USER_ALL);
8729             return;
8730         }
8731         // Otherwise, update screen capture only for the calling user.
8732         admin = getProfileOwnerAdminLocked(adminUserId);
8733         if (admin != null && admin.disableScreenCapture) {
8734             setScreenCaptureDisabled(adminUserId);
8735             return;
8736         }
8737         // If the admin is permission based, update only for the calling user.
8738         admin = getUserData(adminUserId).createOrGetPermissionBasedAdmin(adminUserId);
8739         if (admin != null && admin.disableScreenCapture) {
8740             setScreenCaptureDisabled(adminUserId);
8741             return;
8742         }
8743         setScreenCaptureDisabled(UserHandle.USER_NULL);
8744     }
8745 
8746     // Set the latest screen capture policy, overriding any existing ones.
8747     // userHandle can be one of USER_ALL, USER_NULL or a concrete userId.
8748     private void setScreenCaptureDisabled(int userHandle) {
8749         int current = mPolicyCache.getScreenCaptureDisallowedUser();
8750         if (userHandle == current) {
8751             return;
8752         }
8753         mPolicyCache.setScreenCaptureDisallowedUser(userHandle);
8754         updateScreenCaptureDisabled();
8755     }
8756 
8757     /**
8758      * Returns whether or not screen capture is disabled for  any active admin.
8759      */
8760     @Override
8761     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle, boolean parent) {
8762         if (!mHasFeature) {
8763             return false;
8764         }
8765         final CallerIdentity caller = getCallerIdentity(who);
8766         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8767 
8768         if (parent) {
8769             Preconditions.checkCallAuthorization(
8770                     isProfileOwnerOfOrganizationOwnedDevice(getCallerIdentity().getUserId()));
8771         }
8772         if (isPolicyEngineForFinanceFlagEnabled()) {
8773             Boolean disallowed = mDevicePolicyEngine.getResolvedPolicy(
8774                     PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8775                     userHandle);
8776             return disallowed != null && disallowed;
8777         } else {
8778             return !mPolicyCache.isScreenCaptureAllowed(userHandle);
8779         }
8780     }
8781 
8782     private void updateScreenCaptureDisabled() {
8783         mHandler.post(() -> {
8784             try {
8785                 mInjector.getIWindowManager().refreshScreenCaptureDisabled();
8786             } catch (RemoteException e) {
8787                 Slogf.w(LOG_TAG, "Unable to notify WindowManager.", e);
8788             }
8789         });
8790     }
8791 
8792     @Override
8793     public void setNearbyNotificationStreamingPolicy(int policy) {
8794         if (!mHasFeature) {
8795             return;
8796         }
8797 
8798         final CallerIdentity caller = getCallerIdentity();
8799         Preconditions.checkCallAuthorization(
8800                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
8801 
8802         synchronized (getLockObject()) {
8803             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
8804             if (admin.mNearbyNotificationStreamingPolicy != policy) {
8805                 admin.mNearbyNotificationStreamingPolicy = policy;
8806                 saveSettingsLocked(caller.getUserId());
8807             }
8808         }
8809     }
8810 
8811     @Override
8812     public int getNearbyNotificationStreamingPolicy(final int userId) {
8813         if (!mHasFeature) {
8814             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8815         }
8816 
8817         final CallerIdentity caller = getCallerIdentity();
8818         Preconditions.checkCallAuthorization(
8819                 isProfileOwner(caller) || isDefaultDeviceOwner(caller)
8820                         || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY));
8821         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
8822 
8823         synchronized (getLockObject()) {
8824             final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
8825             return admin != null
8826                     ? admin.mNearbyNotificationStreamingPolicy
8827                     : NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8828         }
8829     }
8830 
8831     @Override
8832     public void setNearbyAppStreamingPolicy(int policy) {
8833         if (!mHasFeature) {
8834             return;
8835         }
8836 
8837         final CallerIdentity caller = getCallerIdentity();
8838         Preconditions.checkCallAuthorization(
8839                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
8840 
8841         synchronized (getLockObject()) {
8842             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
8843             if (admin.mNearbyAppStreamingPolicy != policy) {
8844                 admin.mNearbyAppStreamingPolicy = policy;
8845                 saveSettingsLocked(caller.getUserId());
8846             }
8847         }
8848     }
8849 
8850     @Override
8851     public int getNearbyAppStreamingPolicy(final int userId) {
8852         if (!mHasFeature) {
8853             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8854         }
8855 
8856         final CallerIdentity caller = getCallerIdentity();
8857         Preconditions.checkCallAuthorization(
8858                 isProfileOwner(caller) || isDefaultDeviceOwner(caller)
8859                         || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY));
8860         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
8861 
8862         synchronized (getLockObject()) {
8863             final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
8864             return admin != null
8865                     ? admin.mNearbyAppStreamingPolicy
8866                     : NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8867         }
8868     }
8869 
8870     /**
8871      * Set whether auto time is required by the specified admin (must be device or profile owner).
8872      */
8873     @Override
8874     public void setAutoTimeRequired(ComponentName who, boolean required) {
8875         if (!mHasFeature) {
8876             return;
8877         }
8878         Objects.requireNonNull(who, "ComponentName is null");
8879         final CallerIdentity caller = getCallerIdentity(who);
8880         Preconditions.checkCallAuthorization(
8881                 isDeviceOwner(caller) || isProfileOwner(caller));
8882 
8883         boolean requireAutoTimeChanged = false;
8884         synchronized (getLockObject()) {
8885             Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
8886                     "Managed profile cannot set auto time required");
8887 
8888             if (isPolicyEngineForFinanceFlagEnabled()) {
8889                 EnforcingAdmin admin = getEnforcingAdminForCaller(who, who.getPackageName());
8890                 setGlobalUserRestrictionInternal(
8891                         admin, UserManager.DISALLOW_CONFIG_DATE_TIME, required);
8892             } else {
8893                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
8894                 if (admin.requireAutoTime != required) {
8895                     admin.requireAutoTime = required;
8896                     saveSettingsLocked(caller.getUserId());
8897                     requireAutoTimeChanged = true;
8898                 }
8899                 // requireAutoTime is now backed by DISALLOW_CONFIG_DATE_TIME restriction, so
8900                 // propagate updated restrictions to the framework.
8901                 if (requireAutoTimeChanged) {
8902                     pushUserRestrictions(caller.getUserId());
8903                 }
8904             }
8905         }
8906         // Turn AUTO_TIME on in settings if it is required
8907         if (required) {
8908             mInjector.binderWithCleanCallingIdentity(
8909                     () -> mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME,
8910                             1 /* AUTO_TIME on */));
8911         }
8912         DevicePolicyEventLogger
8913                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_REQUIRED)
8914                 .setAdmin(who)
8915                 .setBoolean(required)
8916                 .write();
8917     }
8918 
8919     /**
8920      * Returns whether or not auto time is required by the device owner or any profile owner.
8921      */
8922     @Override
8923     public boolean getAutoTimeRequired() {
8924         if (!mHasFeature) {
8925             return false;
8926         }
8927         if (isPolicyEngineForFinanceFlagEnabled()) {
8928             Boolean required = mDevicePolicyEngine.getResolvedPolicy(
8929                     PolicyDefinition.getPolicyDefinitionForUserRestriction(
8930                             UserManager.DISALLOW_CONFIG_DATE_TIME),
8931                     mInjector.binderGetCallingUserHandle().getIdentifier());
8932             return required != null && required;
8933         } else {
8934             synchronized (getLockObject()) {
8935                 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
8936                 if (deviceOwner != null && deviceOwner.requireAutoTime) {
8937                     // If the device owner enforces auto time, we don't need to check the PO's
8938                     return true;
8939                 }
8940 
8941                 // Now check to see if any profile owner on any user enforces auto time
8942                 for (Integer userId : mOwners.getProfileOwnerKeys()) {
8943                     ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8944                     if (profileOwner != null && profileOwner.requireAutoTime) {
8945                         return true;
8946                     }
8947                 }
8948 
8949                 return false;
8950             }
8951         }
8952     }
8953 
8954     /**
8955      * Set whether auto time is enabled on the device.
8956      */
8957     @Override
8958     public void setAutoTimeEnabled(@Nullable ComponentName who, String callerPackageName,
8959             boolean enabled) {
8960         if (!mHasFeature) {
8961             return;
8962         }
8963 
8964         CallerIdentity caller;
8965         if (isUnicornFlagEnabled()) {
8966             caller = getCallerIdentity(who, callerPackageName);
8967         } else {
8968             caller = getCallerIdentity(who);
8969         }
8970 
8971         if (isUnicornFlagEnabled()) {
8972             // The effect of this policy is device-wide.
8973             enforcePermission(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
8974         } else {
8975             Objects.requireNonNull(who, "ComponentName is null");
8976             Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
8977                     || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
8978                     caller));
8979         }
8980         mInjector.binderWithCleanCallingIdentity(() ->
8981                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, enabled ? 1 : 0));
8982 
8983         DevicePolicyEventLogger
8984                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME)
8985                 .setAdmin(caller.getPackageName())
8986                 .setBoolean(enabled)
8987                 .write();
8988     }
8989 
8990     /**
8991      * Returns whether auto time is used on the device or not.
8992      */
8993     @Override
8994     public boolean getAutoTimeEnabled(@Nullable ComponentName who, String callerPackageName) {
8995         if (!mHasFeature) {
8996             return false;
8997         }
8998         CallerIdentity caller;
8999         if (isUnicornFlagEnabled()) {
9000             caller = getCallerIdentity(who, callerPackageName);
9001         } else {
9002             caller = getCallerIdentity(who);
9003         }
9004 
9005         if (isUnicornFlagEnabled()) {
9006             enforceCanQuery(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
9007         } else {
9008             Objects.requireNonNull(who, "ComponentName is null");
9009             Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
9010                     || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
9011                     caller));
9012         }
9013 
9014         return mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) > 0;
9015     }
9016 
9017     /**
9018      * Set whether auto time zone is enabled on the device.
9019      */
9020     @Override
9021     public void setAutoTimeZoneEnabled(@Nullable ComponentName who, String callerPackageName,
9022             boolean enabled) {
9023         if (!mHasFeature) {
9024             return;
9025         }
9026 
9027         CallerIdentity caller;
9028         if (isUnicornFlagEnabled()) {
9029             caller = getCallerIdentity(who, callerPackageName);
9030         } else {
9031             caller = getCallerIdentity(who);
9032         }
9033 
9034         if (isUnicornFlagEnabled()) {
9035             // The effect of this policy is device-wide.
9036             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
9037                     who,
9038                     SET_TIME_ZONE,
9039                     caller.getPackageName(),
9040                     UserHandle.USER_ALL
9041             );
9042             mDevicePolicyEngine.setGlobalPolicy(
9043                     PolicyDefinition.AUTO_TIMEZONE,
9044                     // TODO(b/260573124): add correct enforcing admin when permission changes are
9045                     //  merged.
9046                     enforcingAdmin,
9047                     new BooleanPolicyValue(enabled));
9048         } else {
9049             Objects.requireNonNull(who, "ComponentName is null");
9050             Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
9051                     || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
9052                     caller));
9053             mInjector.binderWithCleanCallingIdentity(() ->
9054                     mInjector.settingsGlobalPutInt(Global.AUTO_TIME_ZONE, enabled ? 1 : 0));
9055         }
9056 
9057         DevicePolicyEventLogger
9058                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_ZONE)
9059                 .setAdmin(caller.getPackageName())
9060                 .setBoolean(enabled)
9061                 .write();
9062     }
9063 
9064     /**
9065      * Returns whether auto time zone is used on the device or not.
9066      */
9067     @Override
9068     public boolean getAutoTimeZoneEnabled(@Nullable ComponentName who, String callerPackageName) {
9069         if (!mHasFeature) {
9070             return false;
9071         }
9072 
9073         CallerIdentity caller;
9074         if (isUnicornFlagEnabled()) {
9075             caller = getCallerIdentity(who, callerPackageName);
9076         } else {
9077             caller = getCallerIdentity(who);
9078         }
9079 
9080         if (isUnicornFlagEnabled()) {
9081             // The effect of this policy is device-wide.
9082             enforceCanQuery(SET_TIME_ZONE, caller.getPackageName(), UserHandle.USER_ALL);
9083         } else {
9084             Objects.requireNonNull(who, "ComponentName is null");
9085             Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
9086                     || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
9087                     caller));
9088         }
9089 
9090         return mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) > 0;
9091     }
9092 
9093     // TODO (b/137101239): remove this method in follow-up CL
9094     // since it's only used for split system user.
9095     @Override
9096     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
9097         throw new UnsupportedOperationException("This method was used by split system user only.");
9098     }
9099 
9100     // TODO (b/137101239): remove this method in follow-up CL
9101     // since it's only used for split system user.
9102     @Override
9103     public boolean getForceEphemeralUsers(ComponentName who) {
9104         throw new UnsupportedOperationException("This method was used by split system user only.");
9105     }
9106 
9107     @Override
9108     public boolean requestBugreport(ComponentName who) {
9109         if (!mHasFeature) {
9110             return false;
9111         }
9112         Objects.requireNonNull(who, "ComponentName is null");
9113         // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
9114         // which could still contain data related to that user. Should we disallow that, e.g. until
9115         // next boot? Might not be needed given that this still requires user consent.
9116         final CallerIdentity caller = getCallerIdentity(who);
9117         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
9118         checkAllUsersAreAffiliatedWithDevice();
9119         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REQUEST_BUGREPORT);
9120 
9121         if (mBugreportCollectionManager.requestBugreport()) {
9122             DevicePolicyEventLogger
9123                     .createEvent(DevicePolicyEnums.REQUEST_BUGREPORT)
9124                     .setAdmin(who)
9125                     .write();
9126 
9127             final long currentTime = System.currentTimeMillis();
9128             synchronized (getLockObject()) {
9129                 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
9130                 if (currentTime > policyData.mLastBugReportRequestTime) {
9131                     policyData.mLastBugReportRequestTime = currentTime;
9132                     saveSettingsLocked(UserHandle.USER_SYSTEM);
9133                 }
9134             }
9135 
9136             return true;
9137         } else {
9138             return false;
9139         }
9140     }
9141 
9142     void sendDeviceOwnerCommand(String action, Bundle extras) {
9143         final int deviceOwnerUserId;
9144         final ComponentName receiverComponent;
9145         synchronized (getLockObject()) {
9146             deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
9147             receiverComponent = mOwners.getDeviceOwnerComponent();
9148         }
9149         sendActiveAdminCommand(action, extras, deviceOwnerUserId, receiverComponent,
9150                 /* inForeground */ false);
9151     }
9152 
9153     void sendDeviceOwnerOrProfileOwnerCommand(String action, Bundle extras, int userId) {
9154         if (userId == UserHandle.USER_ALL) {
9155             userId = UserHandle.USER_SYSTEM;
9156         }
9157         boolean inForeground = false;
9158         ComponentName receiverComponent = null;
9159         if (action.equals(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE)) {
9160             inForeground = true;
9161             receiverComponent = resolveDelegateReceiver(DELEGATION_NETWORK_LOGGING, action, userId);
9162         }
9163         if (action.equals(DeviceAdminReceiver.ACTION_SECURITY_LOGS_AVAILABLE)) {
9164             inForeground = true;
9165             receiverComponent = resolveDelegateReceiver(
9166                 DELEGATION_SECURITY_LOGGING, action, userId);
9167         }
9168         if (receiverComponent == null) {
9169             receiverComponent = getOwnerComponent(userId);
9170         }
9171         sendActiveAdminCommand(action, extras, userId, receiverComponent, inForeground);
9172     }
9173 
9174     private void sendProfileOwnerCommand(String action, Bundle extras, @UserIdInt int userId) {
9175         sendActiveAdminCommand(action, extras, userId, mOwners.getProfileOwnerComponent(userId),
9176                 /* inForeground */ false);
9177     }
9178 
9179     private void sendActiveAdminCommand(String action, Bundle extras,
9180             @UserIdInt int userId, ComponentName receiverComponent, boolean inForeground) {
9181         final Intent intent = new Intent(action);
9182         intent.setComponent(receiverComponent);
9183         if (extras != null) {
9184             intent.putExtras(extras);
9185         }
9186         if (inForeground) {
9187             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9188         }
9189 
9190         if (VERBOSE_LOG) {
9191             Slogf.v(LOG_TAG, "sendActiveAdminCommand(): broadcasting " + action + " to "
9192                     + receiverComponent.flattenToShortString() + " on user " + userId);
9193         }
9194         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9195     }
9196 
9197     private void sendOwnerChangedBroadcast(String broadcast, int userId) {
9198         final Intent intent = new Intent(broadcast)
9199                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
9200         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9201     }
9202 
9203     void sendBugreportToDeviceOwner(Uri bugreportUri, String bugreportHash) {
9204         synchronized (getLockObject()) {
9205             final Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
9206             intent.setComponent(mOwners.getDeviceOwnerComponent());
9207             intent.setDataAndType(bugreportUri, RemoteBugreportManager.BUGREPORT_MIMETYPE);
9208             intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
9209             intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9210 
9211             final UriGrantsManagerInternal ugm = LocalServices
9212                     .getService(UriGrantsManagerInternal.class);
9213             final NeededUriGrants needed = ugm.checkGrantUriPermissionFromIntent(intent,
9214                     Process.SHELL_UID, mOwners.getDeviceOwnerComponent().getPackageName(),
9215                     mOwners.getDeviceOwnerUserId());
9216             ugm.grantUriPermissionUncheckedFromIntent(needed, null);
9217 
9218             mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
9219         }
9220     }
9221 
9222     void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash) {
9223         synchronized (getLockObject()) {
9224             mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
9225         }
9226     }
9227 
9228     Pair<String, String> getDeviceOwnerRemoteBugreportUriAndHash() {
9229         synchronized (getLockObject()) {
9230             final String uri = mOwners.getDeviceOwnerRemoteBugreportUri();
9231             return uri == null ? null
9232                     : new Pair<>(uri, mOwners.getDeviceOwnerRemoteBugreportHash());
9233         }
9234     }
9235 
9236     /**
9237      * Disables all device cameras according to the specified admin.
9238      */
9239     @Override
9240     public void setCameraDisabled(ComponentName who, String callerPackageName, boolean disabled,
9241             boolean parent) {
9242         if (!mHasFeature) {
9243             return;
9244         }
9245 
9246         CallerIdentity caller;
9247         if (isPolicyEngineForFinanceFlagEnabled()) {
9248             caller = getCallerIdentity(who, callerPackageName);
9249         } else {
9250             caller = getCallerIdentity(who);
9251         }
9252         final int userId = caller.getUserId();
9253 
9254         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_CAMERA_DISABLED);
9255 
9256         if (isPolicyEngineForFinanceFlagEnabled()) {
9257             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
9258                     who,
9259                     MANAGE_DEVICE_POLICY_CAMERA,
9260                     caller.getPackageName(),
9261                     getProfileParentUserIfRequested(userId, parent));
9262             try {
9263                 setBackwardCompatibleUserRestriction(
9264                         caller, enforcingAdmin, UserManager.DISALLOW_CAMERA, disabled, parent);
9265             } catch (IllegalStateException e) {
9266                 throw new IllegalStateException(
9267                         "Please use addUserRestriction or addUserRestrictionGlobally using the key"
9268                                 + " UserManager.DISALLOW_CAMERA to disable the camera locally or"
9269                                 + " globally, respectively");
9270             }
9271         } else {
9272             Objects.requireNonNull(who, "ComponentName is null");
9273             if (parent) {
9274                 Preconditions.checkCallAuthorization(
9275                         isProfileOwnerOfOrganizationOwnedDevice(caller));
9276             }
9277             synchronized (getLockObject()) {
9278                 ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9279                         DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA, parent);
9280                 if (admin.disableCamera != disabled) {
9281                     admin.disableCamera = disabled;
9282                     saveSettingsLocked(userId);
9283                 }
9284             }
9285             // Tell the user manager that the restrictions have changed.
9286             pushUserRestrictions(userId);
9287         }
9288 
9289         final int affectedUserId = parent ? getProfileParentId(userId) : userId;
9290         if (SecurityLog.isLoggingEnabled() && who != null) {
9291             SecurityLog.writeEvent(SecurityLog.TAG_CAMERA_POLICY_SET,
9292                     who.getPackageName(), userId, affectedUserId, disabled ? 1 : 0);
9293         }
9294         DevicePolicyEventLogger
9295                 .createEvent(DevicePolicyEnums.SET_CAMERA_DISABLED)
9296                 .setAdmin(caller.getPackageName())
9297                 .setBoolean(disabled)
9298                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
9299                 .write();
9300     }
9301 
9302     /**
9303      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
9304      * active admins.
9305      */
9306     @Override
9307     public boolean getCameraDisabled(ComponentName who, String callerPackageName, int userHandle,
9308             boolean parent) {
9309         if (!mHasFeature) {
9310             return false;
9311         }
9312         CallerIdentity caller;
9313         if (isPolicyEngineForFinanceFlagEnabled()) {
9314             caller = getCallerIdentity(who, callerPackageName);
9315         } else {
9316             caller = getCallerIdentity(who);
9317         }
9318         if (isPolicyEngineForFinanceFlagEnabled()) {
9319             Preconditions.checkCallAuthorization(
9320                     hasFullCrossUsersPermission(caller, userHandle)
9321                             || isCameraServerUid(caller)
9322                             || hasPermission(MANAGE_DEVICE_POLICY_CAMERA,
9323                                 caller.getPackageName(), userHandle)
9324                             || hasPermission(QUERY_ADMIN_POLICY, caller.getPackageName()));
9325         } else {
9326             Preconditions.checkCallAuthorization(
9327                     hasFullCrossUsersPermission(caller, userHandle) || isCameraServerUid(caller));
9328             if (parent) {
9329                 Preconditions.checkCallAuthorization(
9330                         isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()));
9331             }
9332         }
9333 
9334         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
9335         if (isPolicyEngineForFinanceFlagEnabled()) {
9336             PolicyDefinition<Boolean> policy =
9337                     PolicyDefinition.getPolicyDefinitionForUserRestriction(
9338                             UserManager.DISALLOW_CAMERA);
9339             if (who != null) {
9340                 EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackageName);
9341                 Boolean value = null;
9342                 if (isDeviceOwner(caller)) {
9343                     value = mDevicePolicyEngine.getGlobalPolicySetByAdmin(policy, admin);
9344                 } else {
9345                     value = mDevicePolicyEngine.getLocalPolicySetByAdmin(
9346                             policy, admin, affectedUserId);
9347                 }
9348                 return Boolean.TRUE.equals(value);
9349             } else {
9350                 return Boolean.TRUE.equals(
9351                         mDevicePolicyEngine.getResolvedPolicy(policy, affectedUserId));
9352             }
9353         } else {
9354             synchronized (getLockObject()) {
9355                 if (who != null) {
9356                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
9357                     return (admin != null) && admin.disableCamera;
9358                 }
9359                 // First, see if DO has set it.  If so, it's device-wide.
9360                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9361                 if (deviceOwner != null && deviceOwner.disableCamera) {
9362                     return true;
9363                 }
9364 
9365                 // Return the strictest policy across all participating admins.
9366                 List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(affectedUserId);
9367 
9368                 // Determine whether or not the device camera is disabled for any active admins.
9369                 for (ActiveAdmin activeAdmin : admins) {
9370                     if (activeAdmin.disableCamera) {
9371                         return true;
9372                     }
9373                 }
9374                 return false;
9375             }
9376         }
9377     }
9378 
9379     @Override
9380     public void setKeyguardDisabledFeatures(
9381             ComponentName who, String callerPackageName, int which, boolean parent) {
9382         if (!mHasFeature) {
9383             return;
9384         }
9385 
9386         CallerIdentity caller;
9387         if (isUnicornFlagEnabled()) {
9388             caller = getCallerIdentity(who, callerPackageName);
9389         } else {
9390             caller = getCallerIdentity(who);
9391             Objects.requireNonNull(who, "ComponentName is null");
9392         }
9393 
9394         final int userHandle = caller.getUserId();
9395         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
9396         synchronized (getLockObject()) {
9397             if (isUnicornFlagEnabled()) {
9398                 // SUPPORT USES_POLICY_DISABLE_KEYGUARD_FEATURES
9399                 EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
9400                         who, MANAGE_DEVICE_POLICY_KEYGUARD, caller.getPackageName(),
9401                         affectedUserId);
9402                 if (which == 0) {
9403                     mDevicePolicyEngine.removeLocalPolicy(
9404                             PolicyDefinition.KEYGUARD_DISABLED_FEATURES, admin, affectedUserId);
9405                 } else {
9406                     // TODO(b/273723433): revisit silent masking of features
9407                     if (isManagedProfile(userHandle)) {
9408                         if (parent) {
9409                             if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
9410                                 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
9411                             } else {
9412                                 which = which
9413                                         & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
9414                             }
9415                         } else {
9416                             which = which & PROFILE_KEYGUARD_FEATURES;
9417                         }
9418                     }
9419                     mDevicePolicyEngine.setLocalPolicy(PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
9420                             admin, new IntegerPolicyValue(which), affectedUserId);
9421                 }
9422                 invalidateBinderCaches();
9423             } else {
9424                 ActiveAdmin ap = getActiveAdminForCallerLocked(
9425                         who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
9426                 if (isManagedProfile(userHandle)) {
9427                     if (parent) {
9428                         if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
9429                             which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
9430                         } else {
9431                             which = which & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
9432                         }
9433                     } else {
9434                         which = which & PROFILE_KEYGUARD_FEATURES;
9435                     }
9436                 }
9437                 if (ap.disabledKeyguardFeatures != which) {
9438                     ap.disabledKeyguardFeatures = which;
9439                     saveSettingsLocked(userHandle);
9440                 }
9441             }
9442         }
9443         if (SecurityLog.isLoggingEnabled()) {
9444             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET,
9445                     caller.getPackageName(), userHandle, affectedUserId, which);
9446         }
9447         DevicePolicyEventLogger
9448                 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED_FEATURES)
9449                 .setAdmin(caller.getPackageName())
9450                 .setInt(which)
9451                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
9452                 .write();
9453     }
9454 
9455     /**
9456      * Gets the disabled state for features in keyguard for the given admin,
9457      * or the aggregate of all active admins if who is null.
9458      * This API is cached: invalidate with invalidateBinderCaches().
9459      */
9460     @Override
9461     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
9462         if (!mHasFeature) {
9463             return 0;
9464         }
9465         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
9466 
9467         final CallerIdentity caller = getCallerIdentity();
9468         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
9469         Preconditions.checkCallAuthorization(
9470                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
9471                         || isSystemUid(caller));
9472         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
9473 
9474         synchronized (getLockObject()) {
9475             if (who != null) {
9476                 if (isUnicornFlagEnabled()) {
9477                     EnforcingAdmin admin = getEnforcingAdminForPackage(
9478                             who, who.getPackageName(), userHandle);
9479                     Integer features = mDevicePolicyEngine.getLocalPolicySetByAdmin(
9480                             PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
9481                             admin,
9482                             affectedUserId);
9483 
9484                     return features == null ? 0 : features;
9485                 } else {
9486                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
9487                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
9488                 }
9489             }
9490 
9491             if (isUnicornFlagEnabled()) {
9492                 Integer features = mDevicePolicyEngine.getResolvedPolicy(
9493                         PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
9494                         affectedUserId);
9495 
9496                 return Binder.withCleanCallingIdentity(() -> {
9497                     int combinedFeatures = features == null ? 0 : features;
9498                     List<UserInfo> profiles = mUserManager.getProfiles(affectedUserId);
9499                     for (UserInfo profile : profiles) {
9500                         int profileId = profile.id;
9501                         if (profileId == affectedUserId) {
9502                             continue;
9503                         }
9504                         Integer profileFeatures = mDevicePolicyEngine.getResolvedPolicy(
9505                                 PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
9506                                 profileId);
9507                         if (profileFeatures != null) {
9508                             combinedFeatures |= (profileFeatures
9509                                     & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
9510                         }
9511                     }
9512                     return combinedFeatures;
9513                 });
9514             }
9515 
9516             final long ident = mInjector.binderClearCallingIdentity();
9517             try {
9518                 final List<ActiveAdmin> admins;
9519                 if (!parent && isManagedProfile(userHandle)) {
9520                     // If we are being asked about a managed profile, just return keyguard features
9521                     // disabled by admins in the profile.
9522                     admins = getUserDataUnchecked(userHandle).mAdminList;
9523                 } else {
9524                     // Otherwise return those set by admins in the user and its profiles.
9525                     admins = getActiveAdminsForLockscreenPoliciesLocked(
9526                             getProfileParentUserIfRequested(userHandle, parent));
9527                 }
9528 
9529                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
9530                 final int N = admins.size();
9531                 for (int i = 0; i < N; i++) {
9532                     ActiveAdmin admin = admins.get(i);
9533                     int userId = admin.getUserHandle().getIdentifier();
9534                     boolean isRequestedUser = !parent && (userId == userHandle);
9535                     if (isRequestedUser || !isManagedProfile(userId)) {
9536                         // If we are being asked explicitly about this user
9537                         // return all disabled features even if its a managed profile.
9538                         which |= admin.disabledKeyguardFeatures;
9539                     } else {
9540                         // Otherwise a managed profile is only allowed to disable
9541                         // some features on the parent user.
9542                         which |= (admin.disabledKeyguardFeatures
9543                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
9544                     }
9545                 }
9546                 return which;
9547             } finally {
9548                 mInjector.binderRestoreCallingIdentity(ident);
9549             }
9550         }
9551     }
9552 
9553     @Override
9554     public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
9555             List<String> packageList) {
9556         if (!mHasFeature) {
9557             return;
9558         }
9559         Objects.requireNonNull(packageList, "packageList is null");
9560         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
9561         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
9562                 &&  isDefaultDeviceOwner(caller))
9563                 || (caller.hasPackage()
9564                 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES)));
9565         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEEP_UNINSTALLED_PACKAGES);
9566 
9567         synchronized (getLockObject()) {
9568             // Get the device owner
9569             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9570             // Set list of packages to be kept even if uninstalled.
9571             deviceOwner.keepUninstalledPackages = packageList;
9572             // Save settings.
9573             saveSettingsLocked(caller.getUserId());
9574             // Notify package manager.
9575             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
9576         }
9577         DevicePolicyEventLogger
9578                 .createEvent(DevicePolicyEnums.SET_KEEP_UNINSTALLED_PACKAGES)
9579                 .setAdmin(caller.getPackageName())
9580                 .setBoolean(/* isDelegate */ who == null)
9581                 .setStrings(packageList.toArray(new String[0]))
9582                 .write();
9583     }
9584 
9585     @Override
9586     public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
9587         if (!mHasFeature) {
9588             return null;
9589         }
9590         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
9591         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
9592                 &&  isDefaultDeviceOwner(caller))
9593                 || (caller.hasPackage()
9594                 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES)));
9595 
9596         synchronized (getLockObject()) {
9597             return getKeepUninstalledPackagesLocked();
9598         }
9599     }
9600 
9601     private List<String> getKeepUninstalledPackagesLocked() {
9602         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9603         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
9604     }
9605 
9606     /**
9607      * Logs a warning when the device doesn't have {@code PackageManager.FEATURE_DEVICE_ADMIN}.
9608      *
9609      * @param message action that was not executed; should not end with a period because the missing
9610      * feature will be appended to it.
9611      */
9612     private void logMissingFeatureAction(String message) {
9613         Slogf.w(LOG_TAG, message + " because device does not have the "
9614                 + PackageManager.FEATURE_DEVICE_ADMIN + " feature.");
9615     }
9616 
9617     @Override
9618     public boolean setDeviceOwner(ComponentName admin, int userId,
9619             boolean setProfileOwnerOnCurrentUserIfNecessary) {
9620         if (!mHasFeature) {
9621             logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(admin)
9622                     + " as device owner for user " + userId);
9623             return false;
9624         }
9625         Preconditions.checkArgument(admin != null);
9626 
9627         final CallerIdentity caller = getCallerIdentity();
9628 
9629         boolean hasIncompatibleAccountsOrNonAdb =
9630                 !isAdb(caller) || hasIncompatibleAccountsOnAnyUser();
9631 
9632         if (!hasIncompatibleAccountsOrNonAdb) {
9633             synchronized (getLockObject()) {
9634                 if (!isAdminTestOnlyLocked(admin, userId) && hasAccountsOnAnyUser()) {
9635                     Slogf.w(LOG_TAG,
9636                             "Non test-only owner can't be installed with existing accounts.");
9637                     return false;
9638                 }
9639             }
9640         }
9641 
9642         synchronized (getLockObject()) {
9643             enforceCanSetDeviceOwnerLocked(caller, admin, userId, hasIncompatibleAccountsOrNonAdb);
9644 
9645             Preconditions.checkArgument(isPackageInstalledForUser(admin.getPackageName(), userId),
9646                     "Invalid component " + admin + " for device owner");
9647             final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
9648             Preconditions.checkArgument(activeAdmin != null && !getUserData(
9649                     userId).mRemovingAdmins.contains(admin), "Not active admin: " + admin);
9650 
9651             // Shutting down backup manager service permanently.
9652             toggleBackupServiceActive(UserHandle.USER_SYSTEM, /* makeActive= */ false);
9653             if (isAdb(caller)) {
9654                 // Log device owner provisioning was started using adb.
9655                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
9656                 DevicePolicyEventLogger
9657                         .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
9658                         .setAdmin(admin)
9659                         .setStrings(LOG_TAG_DEVICE_OWNER)
9660                         .write();
9661             }
9662 
9663             mOwners.setDeviceOwner(admin, userId);
9664             mOwners.writeDeviceOwner();
9665             setDeviceOwnershipSystemPropertyLocked();
9666 
9667             //TODO(b/180371154): when provisionFullyManagedDevice is used in tests, remove this
9668             // hard-coded default value setting.
9669             if (isAdb(caller)) {
9670                 activeAdmin.mAdminCanGrantSensorsPermissions = true;
9671                 mPolicyCache.setAdminCanGrantSensorsPermissions(true);
9672                 saveSettingsLocked(userId);
9673             }
9674 
9675             mInjector.binderWithCleanCallingIdentity(() -> {
9676                 // Restrict adding a managed profile when a device owner is set on the device.
9677                 // That is to prevent the co-existence of a managed profile and a device owner
9678                 // on the same device.
9679                 // Instead, the device may be provisioned with an organization-owned managed
9680                 // profile, such that the admin on that managed profile has extended management
9681                 // capabilities that can affect the entire device (but not access private data
9682                 // on the primary profile).
9683                 if (isHeadlessFlagEnabled()) {
9684                     for (int u : mUserManagerInternal.getUserIds()) {
9685                         mUserManager.setUserRestriction(
9686                                 UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
9687                                 UserHandle.of(u));
9688                         // Restrict adding a clone profile when a device owner is set on the device.
9689                         // That is to prevent the co-existence of a clone profile and a device owner
9690                         // on the same device.
9691                         // CDD for reference : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support
9692                         mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
9693                                 true,
9694                                 UserHandle.of(u));
9695                     }
9696                 } else {
9697                     mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
9698                             true,
9699                             UserHandle.of(userId));
9700                     // Restrict adding a clone profile when a device owner is set on the device.
9701                     // That is to prevent the co-existence of a clone profile and a device owner
9702                     // on the same device.
9703                     // CDD for reference : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support
9704                     mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
9705                             true,
9706                             UserHandle.of(userId));
9707                 }
9708                 // TODO Send to system too?
9709                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId);
9710             });
9711             mDeviceAdminServiceController.startServiceForAdmin(
9712                     admin.getPackageName(), userId, "set-device-owner");
9713 
9714             Slogf.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
9715         }
9716 
9717         if (setProfileOwnerOnCurrentUserIfNecessary
9718                 && mInjector.userManagerIsHeadlessSystemUserMode()) {
9719             int currentForegroundUser;
9720             synchronized (getLockObject()) {
9721                 currentForegroundUser = getCurrentForegroundUserId();
9722             }
9723             Slogf.i(LOG_TAG, "setDeviceOwner(): setting " + admin
9724                     + " as profile owner on user " + currentForegroundUser);
9725             // Sets profile owner on current foreground user since
9726             // the human user will complete the DO setup workflow from there.
9727             manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin,
9728                     /* managedUser= */ currentForegroundUser, /* adminExtras= */ null,
9729                     /* showDisclaimer= */ false);
9730         }
9731         return true;
9732     }
9733 
9734     /**
9735      * This API is cached: invalidate with invalidateBinderCaches().
9736      */
9737     @Override
9738     public boolean hasDeviceOwner() {
9739         final CallerIdentity caller = getCallerIdentity();
9740         Preconditions.checkCallAuthorization(
9741                 isDefaultDeviceOwner(caller) || canManageUsers(caller) || isFinancedDeviceOwner(
9742                         caller) || hasCallingOrSelfPermission(
9743                         MANAGE_PROFILE_AND_DEVICE_OWNERS));
9744         return mOwners.hasDeviceOwner();
9745     }
9746 
9747     boolean isDeviceOwner(ActiveAdmin admin) {
9748         return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
9749     }
9750 
9751     /**
9752      * Check if the user is a Device Owner
9753      *
9754      * @param who    component to check against
9755      * @param userId user to check
9756      * @return if the user is a Device Owner
9757      */
9758     public boolean isDeviceOwner(@Nullable ComponentName who, int userId) {
9759         synchronized (getLockObject()) {
9760             return mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userId
9761                     && mOwners.getDeviceOwnerComponent().equals(who);
9762         }
9763     }
9764 
9765     /**
9766      * Returns {@code true} <b>only if</b> the caller is the device owner and the device owner type
9767      * is {@link DevicePolicyManager#DEVICE_OWNER_TYPE_DEFAULT}. {@code false} is returned for the
9768      * case where the caller is not the device owner, there is no device owner, or the device owner
9769      * type is not {@link DevicePolicyManager#DEVICE_OWNER_TYPE_DEFAULT}.
9770      *
9771      */
9772     private boolean isDefaultDeviceOwner(CallerIdentity caller) {
9773         synchronized (getLockObject()) {
9774             return isDeviceOwnerLocked(caller) && getDeviceOwnerTypeLocked(
9775                     mOwners.getDeviceOwnerPackageName()) == DEVICE_OWNER_TYPE_DEFAULT;
9776         }
9777     }
9778 
9779     /**
9780      * Returns {@code true} if the provided caller identity is of a device owner.
9781      * @param caller identity of caller.
9782      * @return true if {@code identity} is a device owner, false otherwise.
9783      */
9784     public boolean isDeviceOwner(CallerIdentity caller) {
9785         synchronized (getLockObject()) {
9786             return isDeviceOwnerLocked(caller);
9787         }
9788     }
9789 
9790     private boolean isDeviceOwnerLocked(CallerIdentity caller) {
9791         if (!mOwners.hasDeviceOwner() || mOwners.getDeviceOwnerUserId() != caller.getUserId()) {
9792             return false;
9793         }
9794 
9795         if (caller.hasAdminComponent()) {
9796             return mOwners.getDeviceOwnerComponent().equals(caller.getComponentName());
9797         } else {
9798             return isUidDeviceOwnerLocked(caller.getUid());
9799         }
9800     }
9801 
9802     private boolean isDeviceOwnerUserId(int userId) {
9803         synchronized (getLockObject()) {
9804             return mOwners.getDeviceOwnerComponent() != null
9805                     && mOwners.getDeviceOwnerUserId() == userId;
9806         }
9807     }
9808 
9809     /**
9810      * Check if {@link userId} is a Profile Owner
9811      *
9812      * @param who    component to check against
9813      * @param userId user to check
9814      * @return if the user is a Profile Owner
9815      */
9816     public boolean isProfileOwner(@Nullable ComponentName who, int userId) {
9817         final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(
9818                 () -> getProfileOwnerAsUser(userId));
9819         return who != null && who.equals(profileOwner);
9820     }
9821 
9822     /**
9823      * Returns {@code true} if the provided caller identity is of a profile owner.
9824      * @param caller identity of caller.
9825      * @return true if {@code identity} is a profile owner, false otherwise.
9826      */
9827     public boolean isProfileOwner(CallerIdentity caller) {
9828         synchronized (getLockObject()) {
9829             final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() ->
9830                     getProfileOwnerAsUser(caller.getUserId()));
9831             // No profile owner.
9832             if (profileOwner == null) {
9833                 return false;
9834             }
9835             // The admin ComponentName was specified, check it directly.
9836             if (caller.hasAdminComponent()) {
9837                 return profileOwner.equals(caller.getComponentName());
9838             } else {
9839                 return isUidProfileOwnerLocked(caller.getUid());
9840             }
9841         }
9842     }
9843 
9844     /**
9845      * Checks if the app uid provided is the profile owner. This method should only be called
9846      * if no componentName is available.
9847      *
9848      * @param appUid UID of the caller.
9849      * @return true if the caller is the profile owner
9850      */
9851     private boolean isUidProfileOwnerLocked(int appUid) {
9852         ensureLocked();
9853 
9854         final int userId = UserHandle.getUserId(appUid);
9855         final ComponentName profileOwnerComponent = mOwners.getProfileOwnerComponent(userId);
9856         if (profileOwnerComponent == null) {
9857             return false;
9858         }
9859         for (ActiveAdmin admin : getUserData(userId).mAdminList) {
9860             final ComponentName currentAdminComponent = admin.info.getComponent();
9861             if (admin.getUid() == appUid && profileOwnerComponent.equals(currentAdminComponent)) {
9862                 return true;
9863             }
9864         }
9865         return false;
9866     }
9867 
9868     private boolean hasProfileOwner(int userId) {
9869         synchronized (getLockObject()) {
9870             return mOwners.hasProfileOwner(userId);
9871         }
9872     }
9873 
9874     /**
9875      * Returns {@code true} if the provided caller identity is of a profile owner of an organization
9876      * owned device.
9877      *
9878      * @param caller identity of caller
9879      * @return true if {@code identity} is a profile owner of an organization owned device, false
9880      * otherwise.
9881      */
9882     private boolean isProfileOwnerOfOrganizationOwnedDevice(CallerIdentity caller) {
9883         return isProfileOwner(caller) && isProfileOwnerOfOrganizationOwnedDevice(
9884                 caller.getUserId());
9885     }
9886 
9887     private boolean isProfileOwnerOfOrganizationOwnedDevice(int userId) {
9888         synchronized (getLockObject()) {
9889             return mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId);
9890         }
9891     }
9892 
9893     private boolean isProfileOwnerOfOrganizationOwnedDevice(ComponentName who, int userId) {
9894         return isProfileOwner(who, userId) && isProfileOwnerOfOrganizationOwnedDevice(userId);
9895     }
9896 
9897     private boolean isProfileOwnerOnUser0(CallerIdentity caller) {
9898         return isProfileOwner(caller) && caller.getUserHandle().isSystem();
9899     }
9900 
9901     private boolean isPackage(CallerIdentity caller, String packageName) {
9902         return isCallingFromPackage(packageName, caller.getUid());
9903     }
9904 
9905     @Override
9906     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
9907         if (!mHasFeature) {
9908             return null;
9909         }
9910         if (!callingUserOnly) {
9911             Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
9912                     || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
9913         }
9914         synchronized (getLockObject()) {
9915             if (!mOwners.hasDeviceOwner()) {
9916                 return null;
9917             }
9918             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
9919                     mOwners.getDeviceOwnerUserId()) {
9920                 return null;
9921             }
9922             return mOwners.getDeviceOwnerComponent();
9923         }
9924     }
9925 
9926     private int getDeviceOwnerUserIdUncheckedLocked() {
9927         return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
9928     }
9929 
9930     @Override
9931     public int getDeviceOwnerUserId() {
9932         if (!mHasFeature) {
9933             return UserHandle.USER_NULL;
9934         }
9935         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
9936 
9937         synchronized (getLockObject()) {
9938             return getDeviceOwnerUserIdUncheckedLocked();
9939         }
9940     }
9941 
9942     private @UserIdInt int getMainUserId() {
9943         int mainUserId = mUserManagerInternal.getMainUserId();
9944         if (mainUserId == UserHandle.USER_NULL) {
9945             Slogf.d(LOG_TAG, "getMainUserId(): no main user, returning USER_SYSTEM");
9946             return UserHandle.USER_SYSTEM;
9947         }
9948         return mainUserId;
9949     }
9950 
9951     // TODO(b/240562946): Remove api as owner name is not used.
9952     /**
9953      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
9954      * MANAGE_USERS.
9955      */
9956     @Override
9957     public String getDeviceOwnerName() {
9958         if (!mHasFeature) {
9959             return null;
9960         }
9961         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
9962                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
9963 
9964         synchronized (getLockObject()) {
9965             if (!mOwners.hasDeviceOwner()) {
9966                 return null;
9967             }
9968             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
9969             // Should setDeviceOwner/ProfileOwner still take a name?
9970             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
9971             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
9972         }
9973     }
9974 
9975     /** Returns the active device owner or {@code null} if there is no device owner. */
9976     @VisibleForTesting
9977     ActiveAdmin getDeviceOwnerAdminLocked() {
9978         ensureLocked();
9979         ComponentName component = mOwners.getDeviceOwnerComponent();
9980         if (component == null) {
9981             return null;
9982         }
9983 
9984         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
9985         final int n = policy.mAdminList.size();
9986         for (int i = 0; i < n; i++) {
9987             ActiveAdmin admin = policy.mAdminList.get(i);
9988             if (component.equals(admin.info.getComponent())) {
9989                 return admin;
9990             }
9991         }
9992         Slogf.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
9993         return null;
9994     }
9995 
9996     /**
9997      * @deprecated Use the version which does not take a user id.
9998      */
9999     @Deprecated
10000     ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(int userId) {
10001         ensureLocked();
10002         ActiveAdmin admin = getDeviceOwnerAdminLocked();
10003         if (admin == null) {
10004             admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
10005         }
10006         return admin;
10007     }
10008 
10009     ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked() {
10010         ensureLocked();
10011         ActiveAdmin admin = getDeviceOwnerAdminLocked();
10012         if (admin == null) {
10013             admin = getProfileOwnerOfOrganizationOwnedDeviceLocked();
10014         }
10015         return admin;
10016     }
10017 
10018     ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked() {
10019         ensureLocked();
10020         ActiveAdmin doOrPo = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
10021         if (isPermissionCheckFlagEnabled() && doOrPo == null) {
10022             return getUserData(0).mPermissionBasedAdmin;
10023         }
10024         return doOrPo;
10025     }
10026 
10027     ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceParentLocked(int userId) {
10028         ensureLocked();
10029         ActiveAdmin admin = getDeviceOwnerAdminLocked();
10030         if (admin != null) {
10031             return admin;
10032         }
10033         admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
10034         return admin != null ? admin.getParentActiveAdmin() : null;
10035     }
10036 
10037     @Override
10038     public void clearDeviceOwner(String packageName) {
10039         Objects.requireNonNull(packageName, "packageName is null");
10040 
10041         final CallerIdentity caller = getCallerIdentity(packageName);
10042         synchronized (getLockObject()) {
10043             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
10044             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
10045             if (!mOwners.hasDeviceOwner()
10046                     || !deviceOwnerComponent.getPackageName().equals(packageName)
10047                     || (deviceOwnerUserId != caller.getUserId())) {
10048                 throw new SecurityException(
10049                         "clearDeviceOwner can only be called by the device owner");
10050             }
10051             enforceUserUnlocked(deviceOwnerUserId);
10052 
10053             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
10054             mInjector.binderWithCleanCallingIdentity(() -> {
10055                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
10056                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
10057                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED,
10058                         deviceOwnerUserId);
10059             });
10060             Slogf.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
10061         }
10062     }
10063 
10064     private void clearOverrideApnUnchecked() {
10065         if (!mHasTelephonyFeature) {
10066             return;
10067         }
10068         // Disable Override APNs and remove them from database.
10069         setOverrideApnsEnabledUnchecked(false);
10070         final List<ApnSetting> apns = getOverrideApnsUnchecked();
10071         for (int i = 0; i < apns.size(); i ++) {
10072             removeOverrideApnUnchecked(apns.get(i).getId());
10073         }
10074     }
10075 
10076     private void clearManagedProfileApnUnchecked() {
10077         if (!mHasTelephonyFeature) {
10078             return;
10079         }
10080         if (!LocalServices.getService(SystemServiceManager.class).isBootCompleted()) {
10081             Slogf.i(LOG_TAG, "Skip clearing managed profile Apn before boot completed");
10082             // Cannot talk to APN content provider before system boots
10083             // Ideally we should delay the cleanup post boot_completed, not just
10084             // skipping  it altogether.
10085             return;
10086         }
10087         final List<ApnSetting> apns = getOverrideApnsUnchecked();
10088         for (ApnSetting apn : apns) {
10089             if (apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
10090                 removeOverrideApnUnchecked(apn.getId());
10091             }
10092         }
10093     }
10094 
10095     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
10096         String ownersPackage = mOwners.getDeviceOwnerPackageName();
10097         if (ownersPackage != null) {
10098             mDeviceAdminServiceController.stopServiceForAdmin(
10099                     ownersPackage, userId, "clear-device-owner");
10100         }
10101 
10102         if (admin != null) {
10103             admin.disableCamera = false;
10104             admin.userRestrictions = null;
10105             admin.defaultEnabledRestrictionsAlreadySet.clear();
10106             admin.forceEphemeralUsers = false;
10107             admin.isNetworkLoggingEnabled = false;
10108             admin.requireAutoTime = false;
10109             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
10110         }
10111         final DevicePolicyData policyData = getUserData(userId);
10112         policyData.mCurrentInputMethodSet = false;
10113         if (policyData.mPasswordTokenHandle != 0) {
10114             mLockPatternUtils.removeEscrowToken(policyData.mPasswordTokenHandle, userId);
10115             policyData.mPasswordTokenHandle = 0;
10116         }
10117         saveSettingsLocked(userId);
10118         mPolicyCache.onUserRemoved(userId);
10119         final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
10120         systemPolicyData.mLastSecurityLogRetrievalTime = -1;
10121         systemPolicyData.mLastBugReportRequestTime = -1;
10122         systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
10123         saveSettingsLocked(UserHandle.USER_SYSTEM);
10124         clearUserPoliciesLocked(userId);
10125         clearOverrideApnUnchecked();
10126         clearApplicationRestrictions(userId);
10127         if (!isPolicyEngineForFinanceFlagEnabled()) {
10128             mInjector.getPackageManagerInternal().clearBlockUninstallForUser(userId);
10129         }
10130 
10131         mOwners.clearDeviceOwner();
10132         mOwners.writeDeviceOwner();
10133 
10134         updateAdminCanGrantSensorsPermissionCache(userId);
10135         clearDeviceOwnerUserRestriction(UserHandle.of(userId));
10136         mInjector.securityLogSetLoggingEnabledProperty(false);
10137         mSecurityLogMonitor.stop();
10138         setNetworkLoggingActiveInternal(false);
10139         deleteTransferOwnershipBundleLocked(userId);
10140         toggleBackupServiceActive(UserHandle.USER_SYSTEM, true);
10141         if (!isPolicyEngineForFinanceFlagEnabled()) {
10142             pushUserControlDisabledPackagesLocked(userId);
10143         }
10144         setGlobalSettingDeviceOwnerType(DEVICE_OWNER_TYPE_DEFAULT);
10145 
10146         if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
10147             mDevicePolicyEngine.removePoliciesForAdmin(
10148                     EnforcingAdmin.createEnterpriseEnforcingAdmin(
10149                             admin.info.getComponent(), userId, admin));
10150         }
10151     }
10152 
10153     private void clearApplicationRestrictions(int userId) {
10154         // Changing app restrictions involves disk IO, offload it to the background thread.
10155         mBackgroundHandler.post(() -> {
10156             final List<PackageInfo> installedPackageInfos = mInjector.getPackageManager(userId)
10157                     .getInstalledPackages(MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
10158             final UserHandle userHandle = UserHandle.of(userId);
10159             for (final PackageInfo packageInfo : installedPackageInfos) {
10160                 mInjector.getUserManager().setApplicationRestrictions(
10161                         packageInfo.packageName, null /* restrictions */, userHandle);
10162             }
10163         });
10164     }
10165 
10166     @Override
10167     public boolean setProfileOwner(ComponentName who, int userHandle) {
10168         if (!mHasFeature) {
10169             logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(who)
10170                     + " as profile owner for user " + userHandle);
10171             return false;
10172         }
10173         Preconditions.checkArgument(who != null);
10174 
10175         final CallerIdentity caller = getCallerIdentity();
10176         // Cannot be called while holding the lock:
10177         final boolean hasIncompatibleAccountsOrNonAdb =
10178                 hasIncompatibleAccountsOrNonAdbNoLock(caller, userHandle, who);
10179         synchronized (getLockObject()) {
10180             enforceCanSetProfileOwnerLocked(
10181                     caller, who, userHandle, hasIncompatibleAccountsOrNonAdb);
10182             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10183             Preconditions.checkArgument(
10184                     isPackageInstalledForUser(who.getPackageName(), userHandle)
10185                             && admin != null
10186                             && !getUserData(userHandle).mRemovingAdmins.contains(who),
10187                     "Not active admin: " + who);
10188 
10189             final int parentUserId = getProfileParentId(userHandle);
10190             // When trying to set a profile owner on a new user, it may be that this user is
10191             // a profile - but it may not be a managed profile if there's a restriction on the
10192             // parent to add managed profiles (e.g. if the device has a device owner).
10193             if (parentUserId != userHandle && mUserManager.hasUserRestriction(
10194                     UserManager.DISALLOW_ADD_MANAGED_PROFILE,
10195                     UserHandle.of(parentUserId))) {
10196                 Slogf.i(LOG_TAG, "Cannot set profile owner because of restriction.");
10197                 return false;
10198             }
10199 
10200             if (isAdb(caller)) {
10201                 // Log profile owner provisioning was started using adb.
10202                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
10203                 DevicePolicyEventLogger
10204                         .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
10205                         .setAdmin(who)
10206                         .setStrings(LOG_TAG_PROFILE_OWNER)
10207                         .write();
10208             }
10209 
10210             // Shutting down backup manager service permanently.
10211             toggleBackupServiceActive(userHandle, /* makeActive= */ false);
10212 
10213             mOwners.setProfileOwner(who, userHandle);
10214             mOwners.writeProfileOwner(userHandle);
10215             Slogf.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
10216 
10217             mInjector.binderWithCleanCallingIdentity(() -> {
10218                 if (mUserManager.isManagedProfile(userHandle)) {
10219                     maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin);
10220                     ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
10221                             true /* newOwner */);
10222                 }
10223                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
10224                         userHandle);
10225             });
10226             mDeviceAdminServiceController.startServiceForAdmin(
10227                     who.getPackageName(), userHandle, "set-profile-owner");
10228             return true;
10229         }
10230     }
10231 
10232     private void toggleBackupServiceActive(int userId, boolean makeActive) {
10233         long ident = mInjector.binderClearCallingIdentity();
10234         try {
10235             if (mInjector.getIBackupManager() != null) {
10236                 mInjector.getIBackupManager()
10237                         .setBackupServiceActive(userId, makeActive);
10238             }
10239         } catch (RemoteException e) {
10240             throw new IllegalStateException(String.format("Failed %s backup service.",
10241                     makeActive ? "activating" : "deactivating"), e);
10242         } finally {
10243             mInjector.binderRestoreCallingIdentity(ident);
10244         }
10245 
10246     }
10247 
10248     @Override
10249     public void clearProfileOwner(ComponentName who) {
10250         if (!mHasFeature) {
10251             return;
10252         }
10253         Objects.requireNonNull(who, "ComponentName is null");
10254 
10255         final CallerIdentity caller = getCallerIdentity(who);
10256         final int userId = caller.getUserId();
10257         Preconditions.checkCallingUser(!isManagedProfile(userId));
10258         Preconditions.checkCallAuthorization(isProfileOwner(caller));
10259 
10260         enforceUserUnlocked(userId);
10261         synchronized (getLockObject()) {
10262             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
10263 
10264             mInjector.binderWithCleanCallingIdentity(() -> {
10265                 clearProfileOwnerLocked(admin, userId);
10266                 removeActiveAdminLocked(who, userId);
10267                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
10268                         userId);
10269             });
10270             Slogf.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
10271         }
10272     }
10273 
10274     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
10275         String ownersPackage = mOwners.getProfileOwnerPackage(userId);
10276         if (ownersPackage != null) {
10277             mDeviceAdminServiceController.stopServiceForAdmin(
10278                     ownersPackage, userId, "clear-profile-owner");
10279         }
10280 
10281         if (admin != null) {
10282             admin.disableCamera = false;
10283             admin.userRestrictions = null;
10284             admin.defaultEnabledRestrictionsAlreadySet.clear();
10285         }
10286         final DevicePolicyData policyData = getUserData(userId);
10287         policyData.mCurrentInputMethodSet = false;
10288         policyData.mOwnerInstalledCaCerts.clear();
10289         saveSettingsLocked(userId);
10290         clearUserPoliciesLocked(userId);
10291         clearApplicationRestrictions(userId);
10292         mOwners.removeProfileOwner(userId);
10293         mOwners.writeProfileOwner(userId);
10294         deleteTransferOwnershipBundleLocked(userId);
10295         toggleBackupServiceActive(userId, true);
10296         applyProfileRestrictionsIfDeviceOwnerLocked();
10297         setNetworkLoggingActiveInternal(false);
10298 
10299         if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
10300             mDevicePolicyEngine.removePoliciesForAdmin(
10301                     EnforcingAdmin.createEnterpriseEnforcingAdmin(
10302                             admin.info.getComponent(), userId, admin));
10303         }
10304     }
10305 
10306     @Override
10307     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
10308         if (!mHasFeature) {
10309             return;
10310         }
10311         Objects.requireNonNull(who, "ComponentName is null");
10312 
10313         final CallerIdentity caller = getCallerIdentity(who);
10314         Preconditions.checkCallAuthorization(
10315                 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller));
10316 
10317         mInjector.binderWithCleanCallingIdentity(() ->
10318                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null));
10319 
10320         DevicePolicyEventLogger
10321                 .createEvent(DevicePolicyEnums.SET_DEVICE_OWNER_LOCK_SCREEN_INFO)
10322                 .setAdmin(caller.getComponentName())
10323                 .write();
10324     }
10325 
10326     @Override
10327     public CharSequence getDeviceOwnerLockScreenInfo() {
10328         final CallerIdentity caller = getCallerIdentity();
10329         Preconditions.checkCallAuthorization(
10330                 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller));
10331         return mInjector.binderWithCleanCallingIdentity(() ->
10332             mLockPatternUtils.getDeviceOwnerInfo());
10333     }
10334 
10335     private void clearUserPoliciesLocked(int userId) {
10336         // Reset some of the user-specific policies.
10337         final DevicePolicyData policy = getUserData(userId);
10338         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
10339         // Clear delegations.
10340         policy.mDelegationMap.clear();
10341         policy.mStatusBarDisabled = false;
10342         policy.mSecondaryLockscreenEnabled = false;
10343         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
10344         policy.mAffiliationIds.clear();
10345         resetAffiliationCacheLocked();
10346         policy.mLockTaskPackages.clear();
10347         if (!isPolicyEngineForFinanceFlagEnabled()) {
10348             updateLockTaskPackagesLocked(mContext, policy.mLockTaskPackages, userId);
10349         }
10350         policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
10351         saveSettingsLocked(userId);
10352 
10353         try {
10354             mIPermissionManager.updatePermissionFlagsForAllApps(
10355                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
10356                     0  /* flagValues */, userId);
10357             pushUserRestrictions(userId);
10358         } catch (RemoteException re) {
10359             // Shouldn't happen.
10360             Slogf.wtf(LOG_TAG, "Failing in updatePermissionFlagsForAllApps", re);
10361         }
10362     }
10363 
10364     @Override
10365     public boolean hasUserSetupCompleted() {
10366         return hasUserSetupCompleted(mInjector.userHandleGetCallingUserId());
10367     }
10368 
10369     // This checks only if the Setup Wizard has run.  Since Wear devices pair before
10370     // completing Setup Wizard, and pairing involves transferring user data, calling
10371     // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
10372     private boolean hasUserSetupCompleted(int userHandle) {
10373         if (!mHasFeature) {
10374             return true;
10375         }
10376         return mInjector.hasUserSetupCompleted(getUserData(userHandle));
10377     }
10378 
10379     private boolean hasPaired(int userHandle) {
10380         if (!mHasFeature) {
10381             return true;
10382         }
10383         return getUserData(userHandle).mPaired;
10384     }
10385 
10386     @Override
10387     public int getUserProvisioningState(int userHandle) {
10388         if (!mHasFeature) {
10389             return DevicePolicyManager.STATE_USER_UNMANAGED;
10390         }
10391         final CallerIdentity caller = getCallerIdentity();
10392         Preconditions.checkCallAuthorization(canManageUsers(caller)
10393                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10394 
10395         if (userHandle != caller.getUserId()) {
10396             Preconditions.checkCallAuthorization(canManageUsers(caller)
10397                     || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
10398         }
10399 
10400         return getUserData(userHandle).mUserProvisioningState;
10401     }
10402 
10403     @Override
10404     public void setUserProvisioningState(int newState, int userId) {
10405         if (!mHasFeature) {
10406             logMissingFeatureAction("Cannot set provisioning state " + newState + " for user "
10407                     + userId);
10408             return;
10409         }
10410         Preconditions.checkCallAuthorization(
10411                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10412 
10413         final CallerIdentity caller = getCallerIdentity();
10414         final long id = mInjector.binderClearCallingIdentity();
10415         try {
10416             int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
10417             // NOTE: multiple if statements are nested below so it can log more info on error
10418             if (userId != deviceOwnerUserId) {
10419                 boolean hasProfileOwner = mOwners.hasProfileOwner(userId);
10420                 if (!hasProfileOwner) {
10421                     int managedUserId = getManagedUserId(userId);
10422                     if (managedUserId < 0 && newState != STATE_USER_UNMANAGED) {
10423                         // No managed device, user or profile, so setting provisioning state makes
10424                         // no sense.
10425                         String error = "Not allowed to change provisioning state unless a "
10426                                 + "device or profile owner is set.";
10427                         Slogf.w(LOG_TAG, "setUserProvisioningState(newState=%d, userId=%d) failed: "
10428                                 + "deviceOwnerId=%d, hasProfileOwner=%b, managedUserId=%d, err=%s",
10429                                 newState, userId, deviceOwnerUserId, hasProfileOwner,
10430                                 managedUserId, error);
10431                         throw new IllegalStateException(error);
10432                     }
10433                 }
10434             }
10435 
10436             synchronized (getLockObject()) {
10437                 boolean transitionCheckNeeded = true;
10438 
10439                 // Calling identity/permission checks.
10440                 if (isAdb(caller)) {
10441                     // ADB shell can only move directly from un-managed to finalized as part of
10442                     // directly setting profile-owner or device-owner.
10443                     if (getUserProvisioningState(userId)
10444                             != DevicePolicyManager.STATE_USER_UNMANAGED
10445                             || newState != STATE_USER_SETUP_FINALIZED) {
10446                         throw new IllegalStateException("Not allowed to change provisioning state "
10447                                 + "unless current provisioning state is unmanaged, and new state"
10448                                 + "is finalized.");
10449                     }
10450                     transitionCheckNeeded = false;
10451                 }
10452 
10453                 final DevicePolicyData policyData = getUserData(userId);
10454                 if (transitionCheckNeeded) {
10455                     // Optional state transition check for non-ADB case.
10456                     checkUserProvisioningStateTransition(policyData.mUserProvisioningState,
10457                             newState);
10458                 }
10459                 policyData.mUserProvisioningState = newState;
10460                 saveSettingsLocked(userId);
10461             }
10462         } finally {
10463             mInjector.binderRestoreCallingIdentity(id);
10464         }
10465     }
10466 
10467     private void checkUserProvisioningStateTransition(int currentState, int newState) {
10468         // Valid transitions for normal use-cases.
10469         switch (currentState) {
10470             case DevicePolicyManager.STATE_USER_UNMANAGED:
10471                 // Can move to any state from unmanaged (except itself as an edge case)..
10472                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
10473                     return;
10474                 }
10475                 break;
10476             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
10477             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
10478                 // Can only move to finalized from these states.
10479                 if (newState == STATE_USER_SETUP_FINALIZED) {
10480                     return;
10481                 }
10482                 break;
10483             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
10484                 // Current user has a managed-profile, but current user is not managed, so
10485                 // rather than moving to finalized state, go back to unmanaged once
10486                 // profile provisioning is complete.
10487                 if (newState == DevicePolicyManager.STATE_USER_PROFILE_FINALIZED) {
10488                     return;
10489                 }
10490                 break;
10491             case STATE_USER_SETUP_FINALIZED:
10492                 // Cannot transition out of finalized.
10493                 break;
10494             case DevicePolicyManager.STATE_USER_PROFILE_FINALIZED:
10495                 // Should only move to an unmanaged state after removing the work profile.
10496                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
10497                     return;
10498                 }
10499                 break;
10500         }
10501 
10502         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
10503         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
10504                 + "from state [" + currentState + "]");
10505     }
10506 
10507     @Override
10508     public void setProfileEnabled(ComponentName who) {
10509         if (!mHasFeature) {
10510             logMissingFeatureAction("Cannot enable profile for "
10511                     + ComponentName.flattenToShortString(who));
10512             return;
10513         }
10514         Objects.requireNonNull(who, "ComponentName is null");
10515 
10516         final CallerIdentity caller = getCallerIdentity(who);
10517         final int userId = caller.getUserId();
10518         Preconditions.checkCallAuthorization(
10519                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
10520         Preconditions.checkCallingUser(isManagedProfile(userId));
10521 
10522         synchronized (getLockObject()) {
10523             // Check if the profile is already enabled.
10524             UserInfo managedProfile = getUserInfo(userId);
10525             if (managedProfile.isEnabled()) {
10526                 Slogf.e(LOG_TAG,
10527                         "setProfileEnabled is called when the profile is already enabled");
10528                 return;
10529             }
10530             mInjector.binderWithCleanCallingIdentity(() -> {
10531                 mUserManager.setUserEnabled(userId);
10532                 UserInfo parent = mUserManager.getProfileParent(userId);
10533                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
10534                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
10535                 UserHandle parentHandle = new UserHandle(parent.id);
10536                 mLocalService.broadcastIntentToManifestReceivers(intent,
10537                         parentHandle, /* requiresPermission= */ true);
10538                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
10539                         Intent.FLAG_RECEIVER_FOREGROUND);
10540                 mContext.sendBroadcastAsUser(intent, parentHandle);
10541             });
10542         }
10543     }
10544 
10545     @Override
10546     public void setProfileName(ComponentName who, String profileName) {
10547         Objects.requireNonNull(who, "ComponentName is null");
10548 
10549         final CallerIdentity caller = getCallerIdentity(who);
10550         Preconditions.checkCallAuthorization(
10551                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
10552 
10553         final String truncatedProfileName =
10554                 profileName.substring(0, Math.min(profileName.length(), MAX_PROFILE_NAME_LENGTH));
10555         mInjector.binderWithCleanCallingIdentity(() -> {
10556             mUserManager.setUserName(caller.getUserId(), truncatedProfileName);
10557             DevicePolicyEventLogger
10558                     .createEvent(DevicePolicyEnums.SET_PROFILE_NAME)
10559                     .setAdmin(caller.getComponentName())
10560                     .write();
10561         });
10562     }
10563 
10564     @Override
10565     public ComponentName getProfileOwnerAsUser(int userId) {
10566         if (!mHasFeature) {
10567             return null;
10568         }
10569         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
10570 
10571         CallerIdentity caller = getCallerIdentity();
10572         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)
10573                 || hasFullCrossUsersPermission(caller, userId));
10574 
10575         synchronized (getLockObject()) {
10576             return mOwners.getProfileOwnerComponent(userId);
10577         }
10578     }
10579 
10580     // Returns the active profile owner for this user or null if the current user has no
10581     // profile owner.
10582     @VisibleForTesting
10583     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
10584         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
10585         if (profileOwner == null) {
10586             return null;
10587         }
10588         DevicePolicyData policy = getUserData(userHandle);
10589         final int n = policy.mAdminList.size();
10590         for (int i = 0; i < n; i++) {
10591             ActiveAdmin admin = policy.mAdminList.get(i);
10592             if (profileOwner.equals(admin.info.getComponent())) {
10593                 return admin;
10594             }
10595         }
10596         return null;
10597     }
10598 
10599     /**
10600      * Returns the ActiveAdmin associated with the PO or DO on the given user.
10601      */
10602     private @Nullable ActiveAdmin getDeviceOrProfileOwnerAdminLocked(int userHandle) {
10603         ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
10604         if (admin == null && getDeviceOwnerUserIdUncheckedLocked() == userHandle) {
10605             admin = getDeviceOwnerAdminLocked();
10606         }
10607         return admin;
10608     }
10609 
10610     @GuardedBy("getLockObject()")
10611     ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked(int userHandle) {
10612         return mInjector.binderWithCleanCallingIdentity(() -> {
10613             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
10614                 if (userInfo.isManagedProfile()) {
10615                     if (getProfileOwnerAsUser(userInfo.id) != null
10616                             && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
10617                         ComponentName who = getProfileOwnerAsUser(userInfo.id);
10618                         return getActiveAdminUncheckedLocked(who, userInfo.id);
10619                     }
10620                 }
10621             }
10622             return null;
10623         });
10624     }
10625 
10626     @GuardedBy("getLockObject()")
10627     ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked() {
10628         return mInjector.binderWithCleanCallingIdentity(() -> {
10629             for (UserInfo userInfo : mUserManager.getUsers()) {
10630                 if (userInfo.isManagedProfile()) {
10631                     if (getProfileOwnerAsUser(userInfo.id) != null
10632                             && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
10633                         ComponentName who = getProfileOwnerAsUser(userInfo.id);
10634                         return getActiveAdminUncheckedLocked(who, userInfo.id);
10635                     }
10636                 }
10637             }
10638             return null;
10639         });
10640     }
10641 
10642     /**
10643      * This API is cached: invalidate with invalidateBinderCaches().
10644      */
10645     @Override
10646     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
10647             @NonNull UserHandle userHandle) {
10648         if (!mHasFeature) {
10649             return null;
10650         }
10651         synchronized (getLockObject()) {
10652             final ComponentName doComponent = mOwners.getDeviceOwnerComponent();
10653             final ComponentName poComponent =
10654                     mOwners.getProfileOwnerComponent(userHandle.getIdentifier());
10655             // Return test only admin if configured to do so.
10656             // TODO(b/182994391): Replace with more generic solution to override the supervision
10657             // component.
10658             if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) {
10659                 if (isAdminTestOnlyLocked(doComponent, userHandle.getIdentifier())) {
10660                     return doComponent;
10661                 } else if (isAdminTestOnlyLocked(poComponent, userHandle.getIdentifier())) {
10662                     return poComponent;
10663                 }
10664             }
10665 
10666             // Check profile owner first as that is what most likely is set.
10667             if (isSupervisionComponentLocked(poComponent)) {
10668                 return poComponent;
10669             }
10670 
10671             if (isSupervisionComponentLocked(doComponent)) {
10672                 return doComponent;
10673             }
10674 
10675             return null;
10676         }
10677     }
10678 
10679     /**
10680      * Returns if the specified component is the supervision component.
10681      */
10682     @Override
10683     public boolean isSupervisionComponent(@NonNull ComponentName who) {
10684         if (!mHasFeature) {
10685             return false;
10686         }
10687         synchronized (getLockObject()) {
10688             if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) {
10689                 final CallerIdentity caller = getCallerIdentity();
10690                 if (isAdminTestOnlyLocked(who, caller.getUserId())) {
10691                     return true;
10692                 }
10693             }
10694             return isSupervisionComponentLocked(who);
10695         }
10696     }
10697 
10698     private boolean isSupervisionComponentLocked(@Nullable ComponentName who) {
10699         if (who == null) {
10700             return false;
10701         }
10702 
10703         final String configComponent = mContext.getResources().getString(
10704                 com.android.internal.R.string.config_defaultSupervisionProfileOwnerComponent);
10705         if (configComponent != null) {
10706             final ComponentName componentName = ComponentName.unflattenFromString(configComponent);
10707             if (who.equals(componentName)) {
10708                 return true;
10709             }
10710         }
10711 
10712         // Check the system supervision role.
10713         final String configPackage = mContext.getResources().getString(
10714                 com.android.internal.R.string.config_systemSupervision);
10715 
10716         return who.getPackageName().equals(configPackage);
10717     }
10718 
10719     // TODO(b/240562946): Remove api as owner name is not used.
10720     @Override
10721     public String getProfileOwnerName(int userHandle) {
10722         if (!mHasFeature) {
10723             return null;
10724         }
10725         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
10726                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10727         return getProfileOwnerNameUnchecked(userHandle);
10728     }
10729 
10730     private String getProfileOwnerNameUnchecked(int userHandle) {
10731         ComponentName profileOwner = getProfileOwnerAsUser(userHandle);
10732         if (profileOwner == null) {
10733             return null;
10734         }
10735         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
10736     }
10737 
10738     private @UserIdInt int getOrganizationOwnedProfileUserId() {
10739         for (UserInfo ui : mUserManagerInternal.getUserInfos()) {
10740             if (ui.isManagedProfile() && isProfileOwnerOfOrganizationOwnedDevice(ui.id)) {
10741                 return ui.id;
10742             }
10743         }
10744         return UserHandle.USER_NULL;
10745     }
10746 
10747     /**
10748      * This API is cached: invalidate with invalidateBinderCaches().
10749      */
10750     @Override
10751     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
10752         if (!mHasFeature) {
10753             return false;
10754         }
10755         return getOrganizationOwnedProfileUserId() != UserHandle.USER_NULL;
10756     }
10757 
10758     @Override
10759     public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) {
10760         final CallerIdentity caller = getCallerIdentity();
10761         ensureCallerIdentityMatchesIfNotSystem(packageName, pid, uid, caller);
10762 
10763         // Verify that the specified packages matches the provided uid.
10764         if (!doesPackageMatchUid(packageName, uid)) {
10765             return false;
10766         }
10767         // A device or profile owner must also have the READ_PHONE_STATE permission to access device
10768         // identifiers. If the package being checked does not have this permission then deny access.
10769         if (!hasPermission(permission.READ_PHONE_STATE, pid, uid)) {
10770             return false;
10771         }
10772         return hasDeviceIdAccessUnchecked(packageName, uid);
10773     }
10774 
10775     /**
10776      * Check if one the following conditions hold:
10777      * (1) The device has a Device Owner, and one of the following holds:
10778      *   (1.1) The caller is the Device Owner
10779      *   (1.2) The caller is another app in the same user as the device owner, AND
10780      *         The caller is the delegated certificate installer.
10781      *   (1.3) The caller is a Profile Owner and the calling user is affiliated.
10782      * (2) The user has a profile owner, AND:
10783      *   (2.1) The profile owner has been granted access to Device IDs and one of the following
10784      *         holds:
10785      *     (2.1.1) The caller is the profile owner.
10786      *     (2.1.2) The caller is from another app in the same user as the profile owner, AND
10787      *             the caller is the delegated cert installer.
10788      * (3) The caller holds the
10789      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
10790      *
10791      *  For the device owner case, simply check that the caller is the device owner or the
10792      *  delegated certificate installer.
10793      *
10794      *  For the profile owner case, first check that the caller is the profile owner or can
10795      *  manage the DELEGATION_CERT_INSTALL scope.
10796      *  If that check succeeds, ensure the profile owner was granted access to device
10797      *  identifiers. The grant is transitive: The delegated cert installer is implicitly allowed
10798      *  access to device identifiers in this case as part of the delegation.
10799      */
10800     @VisibleForTesting
10801     boolean hasDeviceIdAccessUnchecked(String packageName, int uid) {
10802         final int userId = UserHandle.getUserId(uid);
10803         // TODO(b/280048070): Introduce a permission to handle device ID access
10804         if (isPermissionCheckFlagEnabled()
10805                 && !(isUidProfileOwnerLocked(uid) || isUidDeviceOwnerLocked(uid))) {
10806             return hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES, packageName, userId);
10807         } else {
10808             ComponentName deviceOwner = getDeviceOwnerComponent(true);
10809             if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName)
10810                     || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) {
10811                 return true;
10812             }
10813             ComponentName profileOwner = getProfileOwnerAsUser(userId);
10814             final boolean isCallerProfileOwnerOrDelegate = profileOwner != null
10815                     && (profileOwner.getPackageName().equals(packageName)
10816                     || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL));
10817             if (isCallerProfileOwnerOrDelegate && (isProfileOwnerOfOrganizationOwnedDevice(userId)
10818                     || isUserAffiliatedWithDevice(userId))) {
10819                 return true;
10820             }
10821         }
10822         return false;
10823     }
10824 
10825     private boolean doesPackageMatchUid(String packageName, int uid) {
10826         final int userId = UserHandle.getUserId(uid);
10827         try {
10828             ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(packageName, 0, userId);
10829             // Since this call goes directly to PackageManagerService a NameNotFoundException is not
10830             // thrown but null data can be returned; if the appInfo for the specified package cannot
10831             // be found then return false to prevent crashing the app.
10832             if (appInfo == null) {
10833                 Slogf.w(LOG_TAG, "appInfo could not be found for package %s", packageName);
10834                 return false;
10835             } else if (uid != appInfo.uid) {
10836                 String message = String.format("Package %s (uid=%d) does not match provided uid %d",
10837                         packageName, appInfo.uid, uid);
10838                 Slogf.w(LOG_TAG, message);
10839                 throw new SecurityException(message);
10840             }
10841         } catch (RemoteException e) {
10842             // If an exception is caught obtaining the appInfo just return false to prevent crashing
10843             // apps due to an internal error.
10844             Slogf.e(LOG_TAG, e, "Exception caught obtaining appInfo for package %s", packageName);
10845             return false;
10846         }
10847         return true;
10848     }
10849 
10850     private void ensureCallerIdentityMatchesIfNotSystem(String packageName, int pid, int uid,
10851             CallerIdentity caller) {
10852         // If the caller is not a system app then it should only be able to check its own device
10853         // identifier access.
10854         int callingUid = caller.getUid();
10855         int callingPid = mInjector.binderGetCallingPid();
10856         if (UserHandle.getAppId(callingUid) >= Process.FIRST_APPLICATION_UID
10857                 && (callingUid != uid || callingPid != pid)) {
10858             String message = String.format(
10859                     "Calling uid %d, pid %d cannot check device identifier access for package %s "
10860                             + "(uid=%d, pid=%d)", callingUid, callingPid, packageName, uid, pid);
10861             Slogf.w(LOG_TAG, message);
10862             throw new SecurityException(message);
10863         }
10864     }
10865 
10866     /**
10867      * Canonical name for a given package.
10868      */
10869     private String getApplicationLabel(String packageName, @UserIdInt int userId) {
10870         return mInjector.binderWithCleanCallingIdentity(() -> {
10871             final Context userContext;
10872             try {
10873                 UserHandle userHandle = UserHandle.of(userId);
10874                 userContext = mContext.createPackageContextAsUser(packageName, /* flags= */ 0,
10875                         userHandle);
10876             } catch (PackageManager.NameNotFoundException nnfe) {
10877                 Slogf.w(LOG_TAG, nnfe, "%s is not installed for user %d", packageName, userId);
10878                 return null;
10879             }
10880             ApplicationInfo appInfo = userContext.getApplicationInfo();
10881             CharSequence result = null;
10882             if (appInfo != null) {
10883                 result = appInfo.loadUnsafeLabel(userContext.getPackageManager());
10884             }
10885             return result != null ? result.toString() : null;
10886         });
10887     }
10888 
10889     /**
10890      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
10891      * permission.
10892      * The profile owner can only be set before the user setup phase has completed,
10893      * except for:
10894      * - SYSTEM_UID
10895      * - adb unless hasIncompatibleAccountsOrNonAdb is true.
10896      */
10897     @GuardedBy("getLockObject()")
10898     private void enforceCanSetProfileOwnerLocked(
10899             CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int userId,
10900             boolean hasIncompatibleAccountsOrNonAdb) {
10901         UserInfo info = getUserInfo(userId);
10902         if (info == null) {
10903             // User doesn't exist.
10904             throw new IllegalArgumentException(
10905                     "Attempted to set profile owner for invalid userId: " + userId);
10906         }
10907         if (info.isGuest()) {
10908             throw new IllegalStateException("Cannot set a profile owner on a guest");
10909         }
10910         if (mOwners.hasProfileOwner(userId)) {
10911             StringBuilder errorMessage = new StringBuilder("Trying to set the profile owner");
10912             if (!hasIncompatibleAccountsOrNonAdb) {
10913                 append(errorMessage, owner).append(" on user ").append(userId);
10914             }
10915             errorMessage.append(", but profile owner");
10916             if (!hasIncompatibleAccountsOrNonAdb) {
10917                 appendProfileOwnerLocked(errorMessage, userId);
10918             }
10919 
10920             throw new IllegalStateException(errorMessage.append(" is already set.").toString());
10921         }
10922         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userId) {
10923             StringBuilder errorMessage = new StringBuilder("Trying to set the profile owner");
10924             if (!hasIncompatibleAccountsOrNonAdb) {
10925                 append(errorMessage, owner).append(" on user ").append(userId);
10926             }
10927             errorMessage.append(", but the user already has a device owner");
10928             if (!hasIncompatibleAccountsOrNonAdb) {
10929                 appendDeviceOwnerLocked(errorMessage);
10930             }
10931             throw new IllegalStateException(errorMessage.append('.').toString());
10932         }
10933         if (isAdb(caller)) {
10934             if ((mIsWatch || hasUserSetupCompleted(userId))
10935                     && hasIncompatibleAccountsOrNonAdb) {
10936                 StringBuilder errorMessage = new StringBuilder("Not allowed to set the profile "
10937                         + "owner");
10938                 if (!hasIncompatibleAccountsOrNonAdb) {
10939                     append(errorMessage, owner).append(" on user ").append(userId).append(' ');
10940                 }
10941                 throw new IllegalStateException(errorMessage.append(" because there are already "
10942                         + "some accounts on the profile.").toString());
10943             }
10944             return;
10945         }
10946         Preconditions.checkCallAuthorization(
10947                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10948 
10949         if ((mIsWatch || hasUserSetupCompleted(userId))) {
10950             Preconditions.checkState(isSystemUid(caller),
10951                     "Cannot set the profile owner on a user which is already set-up");
10952 
10953             if (!mIsWatch) {
10954                 if (!isSupervisionComponentLocked(owner)) {
10955                     throw new IllegalStateException("Unable to set non-default profile owner"
10956                             + " post-setup " + owner);
10957                 }
10958             }
10959         }
10960     }
10961 
10962     /**
10963      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
10964      * permission.
10965      */
10966     @GuardedBy("getLockObject()")
10967     private void enforceCanSetDeviceOwnerLocked(
10968             CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int deviceOwnerUserId,
10969             boolean hasIncompatibleAccountsOrNonAdb) {
10970         boolean showComponentOnError = false;
10971         if (!isAdb(caller)) {
10972             Preconditions.checkCallAuthorization(
10973                     hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10974         } else {
10975             showComponentOnError = true;
10976         }
10977 
10978         final int code = checkDeviceOwnerProvisioningPreConditionLocked(owner,
10979                 /* deviceOwnerUserId= */ deviceOwnerUserId, /* callingUserId*/ caller.getUserId(),
10980                 isAdb(caller), hasIncompatibleAccountsOrNonAdb);
10981         if (code != STATUS_OK) {
10982             final String provisioningErrorStringLocked = computeProvisioningErrorStringLocked(code,
10983                     deviceOwnerUserId, owner, showComponentOnError);
10984             if (code == STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED) {
10985                 throw new ServiceSpecificException(code, provisioningErrorStringLocked);
10986             } else {
10987                 throw new IllegalStateException(provisioningErrorStringLocked);
10988             }
10989         }
10990     }
10991 
10992     private String computeProvisioningErrorString(int code, @UserIdInt int userId) {
10993         synchronized (getLockObject()) {
10994             return computeProvisioningErrorStringLocked(code, userId, /* newOwner= */ null,
10995                     /* showComponentOnError= */ false);
10996         }
10997     }
10998 
10999     @GuardedBy("getLockObject()")
11000     private String computeProvisioningErrorStringLocked(int code, @UserIdInt int userId,
11001             @Nullable ComponentName newOwner, boolean showComponentOnError) {
11002         switch (code) {
11003             case STATUS_OK:
11004                 return "OK";
11005             case STATUS_HAS_DEVICE_OWNER: {
11006                 StringBuilder error = new StringBuilder("Trying to set the device owner");
11007                 if (showComponentOnError && newOwner != null) {
11008                     append(error, newOwner);
11009                 }
11010                 error.append(", but device owner");
11011                 if (showComponentOnError) {
11012                     appendDeviceOwnerLocked(error);
11013                 }
11014                 return error.append(" is already set.").toString();
11015             }
11016             case STATUS_USER_HAS_PROFILE_OWNER: {
11017                 StringBuilder error = new StringBuilder("Trying to set the device owner");
11018                 if (showComponentOnError && newOwner != null) {
11019                     append(error, newOwner);
11020                 }
11021                 error.append(", but the user already has a profile owner");
11022                 if (showComponentOnError) {
11023                     appendProfileOwnerLocked(error, userId);
11024                 }
11025                 return error.append(".").toString();
11026             }
11027             case STATUS_USER_NOT_RUNNING:
11028                 return "User " + userId + " not running.";
11029             case STATUS_NOT_SYSTEM_USER:
11030                 return "User " + userId + " is not system user.";
11031             case STATUS_USER_SETUP_COMPLETED:
11032                 return  "Cannot set the device owner if the device is already set-up.";
11033             case STATUS_NONSYSTEM_USER_EXISTS:
11034                 return "Not allowed to set the device owner because there are already several"
11035                         + " users on the device.";
11036             case STATUS_ACCOUNTS_NOT_EMPTY:
11037                 return "Not allowed to set the device owner because there are already some accounts"
11038                         + " on the device.";
11039             case STATUS_HAS_PAIRED:
11040                 return "Not allowed to set the device owner because this device has already "
11041                         + "paired.";
11042             case STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED:
11043                 return "Cannot provision an unsupported DPC into DO on a"
11044                         + " headless device";
11045             default:
11046                 return "Unexpected @ProvisioningPreCondition: " + code;
11047         }
11048     }
11049 
11050     @GuardedBy("getLockObject()")
11051     private void appendDeviceOwnerLocked(StringBuilder string) {
11052         ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
11053         if (deviceOwner == null) {
11054             // Shouldn't happen, but it doesn't hurt to check...
11055             Slogf.wtf(LOG_TAG, "appendDeviceOwnerLocked(): device has no DO set");
11056             return;
11057         }
11058         append(string, deviceOwner);
11059     }
11060 
11061     @GuardedBy("getLockObject()")
11062     private void appendProfileOwnerLocked(StringBuilder string, @UserIdInt int userId) {
11063         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
11064         if (profileOwner == null) {
11065             // Shouldn't happen, but it doesn't hurt to check...
11066             Slogf.wtf(LOG_TAG, "profileOwner(%d): PO not set", userId);
11067             return;
11068         }
11069         append(string, profileOwner);
11070     }
11071 
11072     private static StringBuilder append(StringBuilder string, ComponentName component) {
11073         return string.append(" (").append(component.flattenToShortString()).append(')');
11074     }
11075 
11076     private void enforceUserUnlocked(int userId) {
11077         // Since we're doing this operation on behalf of an app, we only
11078         // want to use the actual "unlocked" state.
11079         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
11080                 "User must be running and unlocked");
11081     }
11082 
11083     private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
11084         if (parent) {
11085             enforceUserUnlocked(getProfileParentId(userId));
11086         } else {
11087             enforceUserUnlocked(userId);
11088         }
11089     }
11090 
11091     private boolean canManageUsers(CallerIdentity caller) {
11092         return hasCallingOrSelfPermission(permission.MANAGE_USERS);
11093     }
11094 
11095     private boolean canQueryAdminPolicy(CallerIdentity caller) {
11096         return hasCallingOrSelfPermission(permission.QUERY_ADMIN_POLICY);
11097     }
11098 
11099     private boolean hasPermission(String permission, int pid, int uid) {
11100         return mContext.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED;
11101     }
11102 
11103     private boolean hasCallingPermission(String permission) {
11104         return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED;
11105     }
11106 
11107     private boolean hasCallingOrSelfPermission(String permission) {
11108         return mContext.checkCallingOrSelfPermission(permission)
11109                 == PackageManager.PERMISSION_GRANTED;
11110     }
11111 
11112     private boolean hasPermissionForPreflight(CallerIdentity caller, String permission) {
11113         final int callingPid = mInjector.binderGetCallingPid();
11114         final String packageName = mContext.getPackageName();
11115 
11116         return PermissionChecker.checkPermissionForPreflight(mContext, permission, callingPid,
11117                 caller.getUid(), packageName) == PermissionChecker.PERMISSION_GRANTED;
11118     }
11119 
11120     private boolean hasFullCrossUsersPermission(CallerIdentity caller, int userHandle) {
11121         return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller)
11122                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL);
11123     }
11124 
11125     private boolean hasCrossUsersPermission(CallerIdentity caller, int userHandle) {
11126         return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller)
11127                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS);
11128     }
11129 
11130     private boolean canDPCManagedUserUseLockTaskLocked(int userId) {
11131         if (isUserAffiliatedWithDeviceLocked(userId)) {
11132             return true;
11133         }
11134 
11135         // Unaffiliated profile owners are not allowed to use lock when there is a device owner.
11136         if (mOwners.hasDeviceOwner()) {
11137             return false;
11138         }
11139 
11140         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
11141         if (profileOwner == null) {
11142             return false;
11143         }
11144         // Managed profiles are not allowed to use lock task
11145         if (isManagedProfile(userId)) {
11146             return false;
11147         }
11148 
11149         return true;
11150     }
11151     private void enforceCanQueryLockTaskLocked(ComponentName who, String callerPackageName) {
11152         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
11153         final int userId = caller.getUserId();
11154 
11155         enforceCanQuery(MANAGE_DEVICE_POLICY_LOCK_TASK, caller.getPackageName(), userId);
11156         if ((isDeviceOwner(caller) || isProfileOwner(caller))
11157                 && !canDPCManagedUserUseLockTaskLocked(userId)) {
11158             throw new SecurityException("User " + userId + " is not allowed to use lock task");
11159         }
11160     }
11161 
11162     private EnforcingAdmin enforceCanCallLockTaskLocked(ComponentName who,
11163             String callerPackageName) {
11164         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
11165         final int userId =  caller.getUserId();
11166 
11167         EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
11168                 who,
11169                 MANAGE_DEVICE_POLICY_LOCK_TASK,
11170                 caller.getPackageName(),
11171                 userId
11172         );
11173         if ((isDeviceOwner(caller) || isProfileOwner(caller))
11174                 && !canDPCManagedUserUseLockTaskLocked(userId)) {
11175             throw new SecurityException("User " + userId + " is not allowed to use lock task");
11176         }
11177         return enforcingAdmin;
11178     }
11179 
11180     private void enforceCanCallLockTaskLocked(CallerIdentity caller) {
11181         Preconditions.checkCallAuthorization(isProfileOwner(caller)
11182                 || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
11183 
11184         final int userId =  caller.getUserId();
11185         if (!canDPCManagedUserUseLockTaskLocked(userId)) {
11186             throw new SecurityException("User " + userId + " is not allowed to use lock task");
11187         }
11188     }
11189 
11190     private boolean isSystemUid(CallerIdentity caller) {
11191         return UserHandle.isSameApp(caller.getUid(), Process.SYSTEM_UID);
11192     }
11193 
11194     private boolean isRootUid(CallerIdentity caller) {
11195         return UserHandle.isSameApp(caller.getUid(), Process.ROOT_UID);
11196     }
11197 
11198     private boolean isShellUid(CallerIdentity caller) {
11199         return UserHandle.isSameApp(caller.getUid(), Process.SHELL_UID);
11200     }
11201 
11202     private boolean isCameraServerUid(CallerIdentity caller) {
11203         return UserHandle.isSameApp(caller.getUid(), Process.CAMERASERVER_UID);
11204     }
11205 
11206     private @UserIdInt int getCurrentForegroundUserId() {
11207         try {
11208             UserInfo currentUser = mInjector.getIActivityManager().getCurrentUser();
11209             if (currentUser == null) {
11210                 // TODO(b/206107460): should not happen on production, but it's happening on unit
11211                 // tests that are not properly setting the expectation (because they don't need it)
11212                 Slogf.wtf(LOG_TAG, "getCurrentForegroundUserId(): mInjector.getIActivityManager()"
11213                         + ".getCurrentUser() returned null, please ignore when running unit tests");
11214                 return ActivityManager.getCurrentUser();
11215             }
11216             return currentUser.id;
11217         } catch (RemoteException e) {
11218             Slogf.wtf(LOG_TAG, "cannot get current user", e);
11219         }
11220         return UserHandle.USER_NULL;
11221     }
11222 
11223     @Override
11224     public List<UserHandle> listForegroundAffiliatedUsers() {
11225         checkIsDeviceOwner(getCallerIdentity());
11226 
11227         return mInjector.binderWithCleanCallingIdentity(() -> {
11228             int userId = getCurrentForegroundUserId();
11229             boolean isAffiliated;
11230             synchronized (getLockObject()) {
11231                 isAffiliated = isUserAffiliatedWithDeviceLocked(userId);
11232             }
11233 
11234             if (!isAffiliated) return Collections.emptyList();
11235 
11236             List<UserHandle> users = new ArrayList<>(1);
11237             users.add(UserHandle.of(userId));
11238 
11239             return users;
11240         });
11241     }
11242 
11243     protected int getProfileParentId(int userHandle) {
11244         return mInjector.binderWithCleanCallingIdentity(() -> {
11245             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
11246             return parentUser != null ? parentUser.id : userHandle;
11247         });
11248     }
11249 
11250     private int getProfileParentUserIfRequested(int userHandle, boolean parent) {
11251         if (parent) {
11252             return getProfileParentId(userHandle);
11253         }
11254 
11255         return userHandle;
11256     }
11257 
11258     private int getCredentialOwner(final int userHandle, final boolean parent) {
11259         return mInjector.binderWithCleanCallingIdentity(() -> {
11260             int effectiveUserHandle = userHandle;
11261             if (parent) {
11262                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
11263                 if (parentProfile != null) {
11264                     effectiveUserHandle = parentProfile.id;
11265                 }
11266             }
11267             return mUserManager.getCredentialOwnerProfile(effectiveUserHandle);
11268         });
11269     }
11270 
11271     private boolean isManagedProfile(int userHandle) {
11272         final UserInfo user = getUserInfo(userHandle);
11273         return user != null && user.isManagedProfile();
11274     }
11275 
11276     private void enableIfNecessary(String packageName, int userId) {
11277         try {
11278             final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
11279                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
11280             if (ai.enabledSetting
11281                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
11282                 mIPackageManager.setApplicationEnabledSetting(packageName,
11283                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
11284                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
11285             }
11286         } catch (RemoteException e) {
11287         }
11288     }
11289 
11290     private void dumpPersonalAppInfoForSystemUserNoLock(IndentingPrintWriter pw) {
11291         wtfIfInLock();
11292         PersonalAppsSuspensionHelper.forUser(mContext, UserHandle.USER_SYSTEM).dump(pw);
11293     }
11294 
11295     private void dumpPerUserPolicyData(IndentingPrintWriter pw) {
11296         int userCount = mUserData.size();
11297         for (int i = 0; i < userCount; i++) {
11298             int userId = mUserData.keyAt(i);
11299             DevicePolicyData policy = getUserData(userId);
11300             policy.dump(pw);
11301             pw.println();
11302         }
11303     }
11304 
11305     @Override
11306     protected void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
11307         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, printWriter)) return;
11308 
11309         try (IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ")) {
11310             pw.println("Current Device Policy Manager state:");
11311             pw.increaseIndent();
11312 
11313             dumpImmutableState(pw);
11314             synchronized (getLockObject()) {
11315                 mOwners.dump(pw);
11316                 pw.println();
11317                 mDeviceAdminServiceController.dump(pw);
11318                 pw.println();
11319                 dumpPerUserPolicyData(pw);
11320                 pw.println();
11321                 mConstants.dump(pw);
11322                 pw.println();
11323                 mStatLogger.dump(pw);
11324                 pw.println();
11325                 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
11326                 pw.println("Logout user: " + getLogoutUserIdUnchecked());
11327                 pw.println();
11328 
11329                 if (mPendingUserCreatedCallbackTokens.isEmpty()) {
11330                     pw.println("no pending user created callback tokens");
11331                 } else {
11332                     int size = mPendingUserCreatedCallbackTokens.size();
11333                     pw.printf("%d pending user created callback token%s\n", size,
11334                             (size == 1 ? "" : "s"));
11335                 }
11336                 pw.println();
11337                 pw.println("Keep profiles running: "
11338                         + getUserData(UserHandle.USER_SYSTEM).mEffectiveKeepProfilesRunning);
11339                 pw.println();
11340 
11341                 mPolicyCache.dump(pw);
11342                 pw.println();
11343                 mStateCache.dump(pw);
11344                 pw.println();
11345             }
11346             dumpPersonalAppInfoForSystemUserNoLock(pw);
11347 
11348             synchronized (mSubscriptionsChangedListenerLock) {
11349                 pw.println("Subscription changed listener : " + mSubscriptionsChangedListener);
11350             }
11351 
11352             pw.println("DPM global setting ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS : "
11353                     + mInjector.settingsGlobalGetString(
11354                     Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS));
11355             mHandler.post(() -> handleDump(pw));
11356             dumpResources(pw);
11357         }
11358     }
11359 
11360     // Dump state that is guarded by the handler
11361     private void handleDump(IndentingPrintWriter pw) {
11362         if (mNetworkLoggingNotificationUserId != UserHandle.USER_NULL) {
11363             pw.println("mNetworkLoggingNotificationUserId:  " + mNetworkLoggingNotificationUserId);
11364         }
11365     }
11366 
11367     private void dumpImmutableState(IndentingPrintWriter pw) {
11368         pw.println("Immutable state:");
11369         pw.increaseIndent();
11370         pw.printf("mHasFeature=%b\n", mHasFeature);
11371         pw.printf("mIsWatch=%b\n", mIsWatch);
11372         pw.printf("mIsAutomotive=%b\n", mIsAutomotive);
11373         pw.printf("mHasTelephonyFeature=%b\n", mHasTelephonyFeature);
11374         pw.printf("mSafetyChecker=%s\n", mSafetyChecker);
11375         pw.decreaseIndent();
11376     }
11377 
11378     private void dumpResources(IndentingPrintWriter pw) {
11379         mOverlayPackagesProvider.dump(pw);
11380         pw.println();
11381 
11382         pw.println("Other overlayable app resources");
11383         pw.increaseIndent();
11384         dumpResources(pw, mContext, "cross_profile_apps", R.array.cross_profile_apps);
11385         dumpResources(pw, mContext, "vendor_cross_profile_apps", R.array.vendor_cross_profile_apps);
11386         dumpResources(pw, mContext, "config_packagesExemptFromSuspension",
11387                 R.array.config_packagesExemptFromSuspension);
11388         dumpResources(pw, mContext, "policy_exempt_apps", R.array.policy_exempt_apps);
11389         dumpResources(pw, mContext, "vendor_policy_exempt_apps", R.array.vendor_policy_exempt_apps);
11390         pw.decreaseIndent();
11391         pw.println();
11392     }
11393 
11394     static void dumpResources(IndentingPrintWriter pw, Context context, String resName, int resId) {
11395         dumpApps(pw, resName, context.getResources().getStringArray(resId));
11396     }
11397 
11398     static void dumpApps(IndentingPrintWriter pw, String name, String[] apps) {
11399         dumpApps(pw, name, Arrays.asList(apps));
11400     }
11401 
11402     static void dumpApps(IndentingPrintWriter pw, String name, List apps) {
11403         if (apps == null || apps.isEmpty()) {
11404             pw.printf("%s: empty\n", name);
11405             return;
11406         }
11407         int size = apps.size();
11408         pw.printf("%s: %d app%s\n", name, size, size == 1 ? "" : "s");
11409         pw.increaseIndent();
11410         for (int i = 0; i < size; i++) {
11411             pw.printf("%d: %s\n", i, apps.get(i));
11412         }
11413         pw.decreaseIndent();
11414     }
11415 
11416     @Override
11417     public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
11418             String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
11419         new DevicePolicyManagerServiceShellCommand(DevicePolicyManagerService.this).exec(
11420                 this, in, out, err, args, callback, resultReceiver);
11421 
11422     }
11423 
11424     private String getEncryptionStatusName(int encryptionStatus) {
11425         switch (encryptionStatus) {
11426             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
11427                 return "per-user";
11428             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
11429                 return "unsupported";
11430             default:
11431                 return "unknown";
11432         }
11433     }
11434 
11435     @Override
11436     public void addPersistentPreferredActivity(ComponentName who, String callerPackageName,
11437             IntentFilter filter, ComponentName activity) {
11438         CallerIdentity caller;
11439         if (isPolicyEngineForFinanceFlagEnabled()) {
11440             caller = getCallerIdentity(who, callerPackageName);
11441         } else {
11442             caller = getCallerIdentity(who);
11443         }
11444 
11445         final int userId = caller.getUserId();
11446         if (isPolicyEngineForFinanceFlagEnabled()) {
11447             EnforcingAdmin enforcingAdmin;
11448             if (who == null) {
11449                 enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
11450                         who,
11451                         MANAGE_DEVICE_POLICY_LOCK_TASK,
11452                         caller.getPackageName(),
11453                         userId);
11454             } else {
11455                 Preconditions.checkCallAuthorization(isProfileOwner(caller)
11456                         || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
11457                 enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
11458             }
11459             if (!isPackageInstalledForUser(activity.getPackageName(), userId)) {
11460                 // Fail early as packageManager doesn't persist the activity if its not installed.
11461                 return;
11462             }
11463             mDevicePolicyEngine.setLocalPolicy(
11464                     PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
11465                     enforcingAdmin,
11466                     new ComponentNamePolicyValue(activity),
11467                     userId);
11468         } else {
11469             Objects.requireNonNull(who, "ComponentName is null");
11470             Preconditions.checkCallAuthorization(isProfileOwner(caller)
11471                     || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
11472             synchronized (getLockObject()) {
11473                 long id = mInjector.binderClearCallingIdentity();
11474                 try {
11475                     mIPackageManager.addPersistentPreferredActivity(filter, activity, userId);
11476                     mIPackageManager.flushPackageRestrictionsAsUser(userId);
11477                 } catch (RemoteException re) {
11478                     // Shouldn't happen
11479                     Slog.wtf(LOG_TAG, "Error adding persistent preferred activity", re);
11480                 } finally {
11481                     mInjector.binderRestoreCallingIdentity(id);
11482                 }
11483             }
11484         }
11485         final String activityPackage =
11486                 (activity != null ? activity.getPackageName() : null);
11487         DevicePolicyEventLogger
11488                 .createEvent(DevicePolicyEnums.ADD_PERSISTENT_PREFERRED_ACTIVITY)
11489                 .setAdmin(caller.getPackageName())
11490                 .setStrings(activityPackage, getIntentFilterActions(filter))
11491                 .write();
11492     }
11493 
11494     @Override
11495     public void clearPackagePersistentPreferredActivities(ComponentName who,
11496             String callerPackageName, String packageName) {
11497         CallerIdentity caller;
11498         if (isPolicyEngineForFinanceFlagEnabled()) {
11499             caller = getCallerIdentity(who, callerPackageName);
11500         } else {
11501             caller = getCallerIdentity(who);
11502         }
11503         final int userId = caller.getUserId();
11504 
11505         if (isPolicyEngineForFinanceFlagEnabled()) {
11506             EnforcingAdmin enforcingAdmin;
11507             if (who == null) {
11508                 enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
11509                         who,
11510                         MANAGE_DEVICE_POLICY_LOCK_TASK,
11511                         caller.getPackageName(),
11512                         userId);
11513             } else {
11514                 Preconditions.checkCallAuthorization(isProfileOwner(caller)
11515                         || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
11516                 enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
11517             }
11518             clearPackagePersistentPreferredActivitiesFromPolicyEngine(
11519                     enforcingAdmin,
11520                     packageName,
11521                     userId);
11522         } else {
11523             Objects.requireNonNull(who, "ComponentName is null");
11524             Preconditions.checkCallAuthorization(isProfileOwner(caller)
11525                     || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
11526             synchronized (getLockObject()) {
11527                 long id = mInjector.binderClearCallingIdentity();
11528                 try {
11529                     mIPackageManager.clearPackagePersistentPreferredActivities(packageName,
11530                             userId);
11531                     mIPackageManager.flushPackageRestrictionsAsUser(userId);
11532                 } catch (RemoteException re) {
11533                     // Shouldn't happen
11534                     Slogf.wtf(
11535                             LOG_TAG, "Error when clearing package persistent preferred activities",
11536                             re);
11537                 } finally {
11538                     mInjector.binderRestoreCallingIdentity(id);
11539                 }
11540             }
11541         }
11542     }
11543 
11544     /**
11545      * Remove all persistent intent handler preferences associated with the given package that were
11546      * set by this admin, note that is doesn't remove preferences set by other admins for the same
11547      * package.
11548      */
11549     private void clearPackagePersistentPreferredActivitiesFromPolicyEngine(
11550             EnforcingAdmin admin, String packageName, int userId) {
11551         Set<PolicyKey> keys = mDevicePolicyEngine.getLocalPolicyKeysSetByAdmin(
11552                 PolicyDefinition.GENERIC_PERSISTENT_PREFERRED_ACTIVITY,
11553                 admin,
11554                 userId);
11555         for (PolicyKey key : keys) {
11556             if (!(key instanceof IntentFilterPolicyKey)) {
11557                 throw new IllegalStateException("PolicyKey for PERSISTENT_PREFERRED_ACTIVITY is not"
11558                         + "of type IntentFilterPolicyKey");
11559             }
11560             IntentFilterPolicyKey parsedKey =
11561                     (IntentFilterPolicyKey) key;
11562             IntentFilter filter = Objects.requireNonNull(parsedKey.getIntentFilter());
11563 
11564             ComponentName preferredActivity = mDevicePolicyEngine.getLocalPolicySetByAdmin(
11565                     PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
11566                     admin,
11567                     userId);
11568             if (preferredActivity != null
11569                     && preferredActivity.getPackageName().equals(packageName)) {
11570                 mDevicePolicyEngine.removeLocalPolicy(
11571                         PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
11572                         admin,
11573                         userId);
11574             }
11575         }
11576     }
11577 
11578     @Override
11579     public void setDefaultSmsApplication(ComponentName admin, String callerPackageName,
11580             String packageName, boolean parent) {
11581         CallerIdentity caller;
11582         if (isPermissionCheckFlagEnabled()) {
11583             caller = getCallerIdentity(admin, callerPackageName);
11584         } else {
11585             caller = getCallerIdentity(admin);
11586         }
11587 
11588         final int userId;
11589 
11590         if (isPermissionCheckFlagEnabled()) {
11591             enforcePermission(
11592                     MANAGE_DEVICE_POLICY_DEFAULT_SMS,
11593                     caller.getPackageName(),
11594                     getAffectedUser(parent));
11595         } else {
11596             Objects.requireNonNull(admin, "ComponentName is null");
11597             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
11598                     || isProfileOwnerOfOrganizationOwnedDevice(caller));
11599         }
11600 
11601         if (!parent && isManagedProfile(caller.getUserId())
11602                 && getManagedSubscriptionsPolicy().getPolicyType()
11603                 != ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
11604             throw new IllegalStateException(
11605                     "Default sms application can only be set on the profile, when "
11606                             + "ManagedSubscriptions policy is set");
11607         }
11608 
11609         if (parent) {
11610             userId = getProfileParentId(mInjector.userHandleGetCallingUserId());
11611             mInjector.binderWithCleanCallingIdentity(() -> enforcePackageIsSystemPackage(
11612                     packageName, userId));
11613         } else {
11614             userId = mInjector.userHandleGetCallingUserId();
11615         }
11616 
11617         mInjector.binderWithCleanCallingIdentity(() ->
11618                 SmsApplication.setDefaultApplicationAsUser(packageName, mContext, userId));
11619 
11620         synchronized (getLockObject()) {
11621             final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
11622                     getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
11623 
11624             if (isManagedProfile(userId)) {
11625                 mInjector.binderWithCleanCallingIdentity(
11626                         () -> updateDialerAndSmsManagedShortcutsOverrideCache());
11627             }
11628 
11629             if (!Objects.equals(activeAdmin.mSmsPackage, packageName)) {
11630                 activeAdmin.mSmsPackage = packageName;
11631                 saveSettingsLocked(caller.getUserId());
11632             }
11633         }
11634     }
11635 
11636     @Override
11637     public void setDefaultDialerApplication(String packageName) {
11638         if (!mHasFeature || !mHasTelephonyFeature) {
11639             return;
11640         }
11641 
11642         final CallerIdentity caller = getCallerIdentity();
11643         final int callerUserId = caller.getUserId();
11644         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
11645                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
11646         mInjector.binderWithCleanCallingIdentity(() -> {
11647             CompletableFuture<Void> future = new CompletableFuture<>();
11648             Consumer<Boolean> callback = successful -> {
11649                 if (successful) {
11650                     future.complete(null);
11651                 } else {
11652                     future.completeExceptionally(new IllegalArgumentException(
11653                             packageName +  " cannot be set as the dialer"));
11654                 }
11655             };
11656             mRoleManager.addRoleHolderAsUser(
11657                     RoleManager.ROLE_DIALER, packageName, 0, UserHandle.of(callerUserId),
11658                     AsyncTask.THREAD_POOL_EXECUTOR, callback);
11659             try {
11660                 future.get(20, TimeUnit.SECONDS);
11661             } catch (TimeoutException e) {
11662                 throw new IllegalArgumentException("Timeout when setting the app as the dialer", e);
11663             } catch (ExecutionException e) {
11664                 Throwable cause = e.getCause();
11665                 if (cause instanceof IllegalArgumentException) {
11666                     throw (IllegalArgumentException) cause;
11667                 } else {
11668                     throw new IllegalStateException(cause);
11669                 }
11670             }
11671         });
11672         // Only save the package when the setting the role succeeded without exception.
11673         synchronized (getLockObject()) {
11674             if (isManagedProfile(callerUserId)) {
11675                 mInjector.binderWithCleanCallingIdentity(
11676                         () -> updateDialerAndSmsManagedShortcutsOverrideCache());
11677             }
11678 
11679             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(callerUserId);
11680             if (!Objects.equals(admin.mDialerPackage, packageName)) {
11681                 admin.mDialerPackage = packageName;
11682                 saveSettingsLocked(callerUserId);
11683             }
11684         }
11685     }
11686 
11687     @Override
11688     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
11689             String packageName) {
11690         try {
11691             setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
11692         } catch (IllegalArgumentException e) {
11693             return false;
11694         }
11695         return true;
11696     }
11697 
11698     @Override
11699     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
11700         final List<String> delegatePackages = getDelegatePackages(admin,
11701                 DELEGATION_APP_RESTRICTIONS);
11702         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
11703     }
11704 
11705     @Override
11706     public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
11707         return isCallerDelegate(callerPackage, getCallerIdentity().getUid(),
11708                 DELEGATION_APP_RESTRICTIONS);
11709     }
11710 
11711     @Override
11712     public void setApplicationRestrictions(ComponentName who, String callerPackage,
11713             String packageName, Bundle restrictions) {
11714         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11715         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_RESTRICTIONS);
11716 
11717         if (isUnicornFlagEnabled()) {
11718             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
11719                     who,
11720                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
11721                     caller.getPackageName(),
11722                     caller.getUserId()
11723             );
11724             // This check is eventually made in UMS, checking here to fail early.
11725             String validationResult =
11726                     FrameworkParsingPackageUtils.validateName(packageName, false, false);
11727             if (validationResult != null) {
11728                 throw new IllegalArgumentException("Invalid package name: " + validationResult);
11729             }
11730 
11731             if (restrictions == null || restrictions.isEmpty()) {
11732                 mDevicePolicyEngine.removeLocalPolicy(
11733                         PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
11734                         enforcingAdmin,
11735                         caller.getUserId());
11736             } else {
11737                 mDevicePolicyEngine.setLocalPolicy(
11738                         PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
11739                         enforcingAdmin,
11740                         new BundlePolicyValue(restrictions),
11741                         caller.getUserId());
11742             }
11743             setBackwardsCompatibleAppRestrictions(
11744                     caller, packageName, restrictions, caller.getUserHandle());
11745         } else {
11746             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11747                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
11748                     || (caller.hasPackage() && isCallerDelegate(caller,
11749                     DELEGATION_APP_RESTRICTIONS)));
11750             mInjector.binderWithCleanCallingIdentity(() -> {
11751                 mUserManager.setApplicationRestrictions(packageName, restrictions,
11752                         caller.getUserHandle());
11753             });
11754         }
11755 
11756         DevicePolicyEventLogger
11757                 .createEvent(DevicePolicyEnums.SET_APPLICATION_RESTRICTIONS)
11758                 .setAdmin(caller.getPackageName())
11759                 .setBoolean(/* isDelegate */ isCallerDelegate(caller))
11760                 .setStrings(packageName)
11761                 .write();
11762     }
11763 
11764     /**
11765      * Set app restrictions in user manager for DPC callers only to keep backwards compatibility
11766      * for the old getApplicationRestrictions API.
11767      */
11768     private void setBackwardsCompatibleAppRestrictions(
11769             CallerIdentity caller, String packageName, Bundle restrictions, UserHandle userHandle) {
11770         if ((caller.hasAdminComponent() && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
11771                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS))) {
11772             Bundle restrictionsToApply = restrictions == null || restrictions.isEmpty()
11773                     ? getAppRestrictionsSetByAnyAdmin(packageName, userHandle)
11774                     : restrictions;
11775             mInjector.binderWithCleanCallingIdentity(() -> {
11776                 mUserManager.setApplicationRestrictions(packageName, restrictionsToApply,
11777                         userHandle);
11778             });
11779         } else {
11780             // Notify package of changes via an intent - only sent to explicitly registered
11781             // receivers. Sending here because For DPCs, this is being sent in UMS.
11782             final Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
11783             changeIntent.setPackage(packageName);
11784             changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11785             mContext.sendBroadcastAsUser(changeIntent, userHandle);
11786         }
11787     }
11788 
11789     private Bundle getAppRestrictionsSetByAnyAdmin(String packageName, UserHandle userHandle) {
11790         LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
11791                 mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
11792                         PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
11793                         userHandle.getIdentifier());
11794         return policies.isEmpty()
11795                 ? null : policies.entrySet().stream().findAny().get().getValue().getValue();
11796     }
11797 
11798     private int getUidForPackage(String packageName, int userId) {
11799         return mInjector.binderWithCleanCallingIdentity(() -> {
11800             try {
11801                 return mContext.getPackageManager().getApplicationInfoAsUser(
11802                         packageName, /* flags= */ 0, userId).uid;
11803             } catch (NameNotFoundException exception) {
11804                 return -1;
11805             }
11806         });
11807     }
11808 
11809     @Override
11810     public void setTrustAgentConfiguration(
11811             ComponentName admin, String callerPackageName, ComponentName agent,
11812             PersistableBundle args, boolean parent) {
11813         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
11814             return;
11815         }
11816 
11817         if (!isPermissionCheckFlagEnabled()) {
11818             Objects.requireNonNull(admin, "admin is null");
11819         }
11820 
11821         Objects.requireNonNull(agent, "agent is null");
11822 
11823         enforceMaxPackageNameLength(agent.getPackageName());
11824         final String agentAsString = agent.flattenToString();
11825         enforceMaxStringLength(agentAsString, "agent name");
11826         if (args != null) {
11827             enforceMaxStringLength(args, "args");
11828         }
11829 
11830         int userHandle = mInjector.userHandleGetCallingUserId();
11831         synchronized (getLockObject()) {
11832             ActiveAdmin ap;
11833             if (isPermissionCheckFlagEnabled()) {
11834                 CallerIdentity caller = getCallerIdentity(admin, callerPackageName);
11835                 int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
11836                 ap = enforcePermissionAndGetEnforcingAdmin(
11837                         admin,
11838                         /*permission=*/MANAGE_DEVICE_POLICY_KEYGUARD,
11839                         /*adminPolicy=*/DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES,
11840                         caller.getPackageName(), affectedUserId).getActiveAdmin();
11841             } else {
11842                 ap = getActiveAdminForCallerLocked(admin,
11843                         DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
11844             }
11845             checkCanExecuteOrThrowUnsafe(
11846                     DevicePolicyManager.OPERATION_SET_TRUST_AGENT_CONFIGURATION);
11847 
11848             ap.trustAgentInfos.put(agentAsString, new TrustAgentInfo(args));
11849             saveSettingsLocked(userHandle);
11850         }
11851     }
11852 
11853     @Override
11854     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
11855             ComponentName agent, int userHandle, boolean parent) {
11856         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
11857             return null;
11858         }
11859         Objects.requireNonNull(agent, "agent null");
11860         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
11861 
11862         final CallerIdentity caller = getCallerIdentity(admin);
11863         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
11864 
11865         synchronized (getLockObject()) {
11866             final String componentName = agent.flattenToString();
11867             if (admin != null) {
11868                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
11869                 if (ap == null) return null;
11870                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
11871                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
11872                 List<PersistableBundle> result = new ArrayList<>();
11873                 result.add(trustAgentInfo.options);
11874                 return result;
11875             }
11876 
11877             // Return strictest policy for this user and profiles that are visible from this user.
11878             List<PersistableBundle> result = null;
11879             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
11880             // of the options. If any admin doesn't have options, discard options for the rest
11881             // and return null.
11882             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
11883                     getProfileParentUserIfRequested(userHandle, parent));
11884             boolean allAdminsHaveOptions = true;
11885             final int N = admins.size();
11886             for (int i = 0; i < N; i++) {
11887                 final ActiveAdmin active = admins.get(i);
11888 
11889                 final boolean disablesTrust = (active.disabledKeyguardFeatures
11890                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
11891                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
11892                 if (info != null && info.options != null && !info.options.isEmpty()) {
11893                     if (disablesTrust) {
11894                         if (result == null) {
11895                             result = new ArrayList<>();
11896                         }
11897                         result.add(info.options);
11898                     } else {
11899                         Slogf.w(LOG_TAG, "Ignoring admin %s because it has trust options but "
11900                                 + "doesn't declare KEYGUARD_DISABLE_TRUST_AGENTS", active.info);
11901                     }
11902                 } else if (disablesTrust) {
11903                     allAdminsHaveOptions = false;
11904                     break;
11905                 }
11906             }
11907             return allAdminsHaveOptions ? result : null;
11908         }
11909     }
11910 
11911     @Override
11912     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
11913         Objects.requireNonNull(who, "ComponentName is null");
11914         final CallerIdentity caller = getCallerIdentity(who);
11915         Preconditions.checkCallAuthorization(
11916                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
11917         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_RESTRICTIONS_PROVIDER);
11918 
11919         synchronized (getLockObject()) {
11920             int userHandle = caller.getUserId();
11921             DevicePolicyData userData = getUserData(userHandle);
11922             userData.mRestrictionsProvider = permissionProvider;
11923             saveSettingsLocked(userHandle);
11924         }
11925     }
11926 
11927     @Override
11928     public ComponentName getRestrictionsProvider(int userHandle) {
11929         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
11930                 String.format(NOT_SYSTEM_CALLER_MSG, "query the permission provider"));
11931         synchronized (getLockObject()) {
11932             DevicePolicyData userData = getUserData(userHandle);
11933             return userData != null ? userData.mRestrictionsProvider : null;
11934         }
11935     }
11936 
11937     @Override
11938     public void addCrossProfileIntentFilter(ComponentName who, String callerPackageName,
11939             IntentFilter filter, int flags) {
11940         CallerIdentity caller;
11941         if (isPermissionCheckFlagEnabled()) {
11942             caller = getCallerIdentity(who, callerPackageName);
11943         } else {
11944             caller = getCallerIdentity(who);
11945         }
11946         int callingUserId = caller.getUserId();
11947 
11948         if (isPermissionCheckFlagEnabled()) {
11949             enforcePermission(
11950                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
11951                     caller.getPackageName(),
11952                     callingUserId);
11953         } else {
11954             Objects.requireNonNull(who, "ComponentName is null");
11955             Preconditions.checkCallAuthorization(
11956                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
11957         }
11958         synchronized (getLockObject()) {
11959             long id = mInjector.binderClearCallingIdentity();
11960             try {
11961                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
11962                 if (parent == null) {
11963                     Slogf.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
11964                             + "parent");
11965                     return;
11966                 }
11967                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
11968                     mIPackageManager.addCrossProfileIntentFilter(
11969                             filter, who.getPackageName(), callingUserId, parent.id, 0);
11970                 }
11971                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
11972                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
11973                             parent.id, callingUserId, 0);
11974                 }
11975             } catch (RemoteException re) {
11976                 // Shouldn't happen
11977                 Slogf.wtf(LOG_TAG, "Error adding cross profile intent filter", re);
11978             } finally {
11979                 mInjector.binderRestoreCallingIdentity(id);
11980             }
11981         }
11982         DevicePolicyEventLogger
11983                 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_INTENT_FILTER)
11984                 .setAdmin(caller.getPackageName())
11985                 .setStrings(getIntentFilterActions(filter))
11986                 .setInt(flags)
11987                 .write();
11988     }
11989 
11990     private static String[] getIntentFilterActions(IntentFilter filter) {
11991         if (filter == null) {
11992             return null;
11993         }
11994         final int actionsCount = filter.countActions();
11995         final String[] actions = new String[actionsCount];
11996         for (int i = 0; i < actionsCount; i++) {
11997             actions[i] = filter.getAction(i);
11998         }
11999         return actions;
12000     }
12001 
12002     @Override
12003     public void clearCrossProfileIntentFilters(ComponentName who, String callerPackageName) {
12004         CallerIdentity caller;
12005         if (isPermissionCheckFlagEnabled()) {
12006             caller = getCallerIdentity(who, callerPackageName);
12007         } else {
12008             caller = getCallerIdentity(who);
12009         }
12010         int callingUserId = caller.getUserId();
12011 
12012         if (isPermissionCheckFlagEnabled()) {
12013             enforcePermission(
12014                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
12015                     caller.getPackageName(),
12016                     callingUserId);
12017         } else {
12018             Objects.requireNonNull(who, "ComponentName is null");
12019             Preconditions.checkCallAuthorization(
12020                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
12021         }
12022 
12023         synchronized (getLockObject()) {
12024             long id = mInjector.binderClearCallingIdentity();
12025             try {
12026                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
12027                 if (parent == null) {
12028                     Slogf.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
12029                             + "parent");
12030                     return;
12031                 }
12032                 // Removing those that go from the managed profile to the parent.
12033                 mIPackageManager.clearCrossProfileIntentFilters(
12034                         callingUserId, who.getPackageName());
12035                 // And those that go from the parent to the managed profile.
12036                 // If we want to support multiple managed profiles, we will have to only remove
12037                 // those that have callingUserId as their target.
12038                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
12039             } catch (RemoteException re) {
12040                 // Shouldn't happen
12041                 Slogf.wtf(LOG_TAG, "Error clearing cross profile intent filters", re);
12042             } finally {
12043                 mInjector.binderRestoreCallingIdentity(id);
12044             }
12045         }
12046     }
12047 
12048     /**
12049      * @return true if all packages in enabledPackages are either in the list
12050      * permittedList or are a system app.
12051      */
12052     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
12053             List<String> permittedList, int userIdToCheck) {
12054         long id = mInjector.binderClearCallingIdentity();
12055         try {
12056             // If we have an enabled packages list for a managed profile the packages
12057             // we should check are installed for the parent user.
12058             UserInfo user = getUserInfo(userIdToCheck);
12059             if (user.isManagedProfile()) {
12060                 userIdToCheck = user.profileGroupId;
12061             }
12062 
12063             for (String enabledPackage : enabledPackages) {
12064                 boolean systemService = false;
12065                 try {
12066                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
12067                             enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
12068                             userIdToCheck);
12069 
12070                     if (applicationInfo == null) {
12071                         return false;
12072                     }
12073 
12074                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12075                 } catch (RemoteException e) {
12076                     Slogf.i(LOG_TAG, "Can't talk to package managed", e);
12077                 }
12078                 if (!systemService && !permittedList.contains(enabledPackage)) {
12079                     return false;
12080                 }
12081             }
12082         } finally {
12083             mInjector.binderRestoreCallingIdentity(id);
12084         }
12085         return true;
12086     }
12087 
12088     /**
12089      * Invoke a method in AccessibilityManager ensuring the client is removed.
12090      */
12091     private <T> T withAccessibilityManager(
12092             int userId, Function<AccessibilityManager, T> function) {
12093         // Not using AccessibilityManager.getInstance because that guesses
12094         // at the user you require based on callingUid and caches for a given
12095         // process.
12096         final IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
12097         final IAccessibilityManager service = iBinder == null
12098                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
12099         final AccessibilityManager am = new AccessibilityManager(mContext, service, userId);
12100         try {
12101             return function.apply(am);
12102         } finally {
12103             am.removeClient();
12104         }
12105     }
12106 
12107     @Override
12108     public boolean setPermittedAccessibilityServices(ComponentName who, List<String> packageList) {
12109         if (!mHasFeature) {
12110             return false;
12111         }
12112         Objects.requireNonNull(who, "ComponentName is null");
12113         final CallerIdentity caller = getCallerIdentity(who);
12114         Preconditions.checkCallAuthorization(
12115                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
12116 
12117         if (packageList != null) {
12118             for (String pkg : packageList) {
12119                 enforceMaxPackageNameLength(pkg);
12120             }
12121 
12122             int userId = caller.getUserId();
12123             final List<AccessibilityServiceInfo> enabledServices;
12124             long id = mInjector.binderClearCallingIdentity();
12125             try {
12126                 UserInfo user = getUserInfo(userId);
12127                 if (user.isManagedProfile()) {
12128                     userId = user.profileGroupId;
12129                 }
12130                 enabledServices = withAccessibilityManager(userId,
12131                         am -> am.getEnabledAccessibilityServiceList(FEEDBACK_ALL_MASK));
12132             } finally {
12133                 mInjector.binderRestoreCallingIdentity(id);
12134             }
12135 
12136             if (enabledServices != null) {
12137                 List<String> enabledPackages = new ArrayList<>();
12138                 for (AccessibilityServiceInfo service : enabledServices) {
12139                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
12140                 }
12141                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
12142                         userId)) {
12143                     Slogf.e(LOG_TAG, "Cannot set permitted accessibility services, "
12144                             + "because it contains already enabled accesibility services.");
12145                     return false;
12146                 }
12147             }
12148         }
12149 
12150         synchronized (getLockObject()) {
12151             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
12152             admin.permittedAccessiblityServices = packageList;
12153             saveSettingsLocked(UserHandle.getCallingUserId());
12154         }
12155         final String[] packageArray =
12156                 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null;
12157         DevicePolicyEventLogger
12158                 .createEvent(DevicePolicyEnums.SET_PERMITTED_ACCESSIBILITY_SERVICES)
12159                 .setAdmin(who)
12160                 .setStrings(packageArray)
12161                 .write();
12162         return true;
12163     }
12164 
12165     @Override
12166     public List<String> getPermittedAccessibilityServices(ComponentName who) {
12167         if (!mHasFeature) {
12168             return null;
12169         }
12170         Objects.requireNonNull(who, "ComponentName is null");
12171         final CallerIdentity caller = getCallerIdentity(who);
12172         Preconditions.checkCallAuthorization(
12173                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
12174 
12175         synchronized (getLockObject()) {
12176             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
12177             return admin.permittedAccessiblityServices;
12178         }
12179     }
12180 
12181     @Override
12182     public List<String> getPermittedAccessibilityServicesForUser(int userId) {
12183         if (!mHasFeature) {
12184             return null;
12185         }
12186         final CallerIdentity caller = getCallerIdentity();
12187         Preconditions.checkCallAuthorization(canManageUsers(caller) || canQueryAdminPolicy(caller));
12188 
12189         List<String> result = null;
12190 
12191         synchronized (getLockObject()) {
12192             // If we have multiple profiles we return the intersection of the
12193             // permitted lists. This can happen in cases where we have a device
12194             // and profile owner.
12195             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
12196             for (int profileId : profileIds) {
12197                 // Just loop though all admins, only device or profiles
12198                 // owners can have permitted lists set.
12199                 DevicePolicyData policy = getUserDataUnchecked(profileId);
12200                 final int N = policy.mAdminList.size();
12201                 for (int j = 0; j < N; j++) {
12202                     ActiveAdmin admin = policy.mAdminList.get(j);
12203                     List<String> fromAdmin = admin.permittedAccessiblityServices;
12204                     if (fromAdmin != null) {
12205                         if (result == null) {
12206                             result = new ArrayList<>(fromAdmin);
12207                         } else {
12208                             result.retainAll(fromAdmin);
12209                         }
12210                     }
12211                 }
12212             }
12213         }
12214 
12215         // If we have a permitted list add all system accessibility services.
12216         if (result != null) {
12217             long id = mInjector.binderClearCallingIdentity();
12218             try {
12219                 UserInfo user = getUserInfo(userId);
12220                 if (user.isManagedProfile()) {
12221                     userId = user.profileGroupId;
12222                 }
12223                 // Move AccessibilityManager out of {@link getLockObject} to prevent potential
12224                 // deadlock.
12225                 final List<AccessibilityServiceInfo> installedServices =
12226                         withAccessibilityManager(userId,
12227                                 AccessibilityManager::getInstalledAccessibilityServiceList);
12228 
12229                 if (installedServices != null) {
12230                     for (AccessibilityServiceInfo service : installedServices) {
12231                         ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
12232                         ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
12233                         if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12234                             result.add(serviceInfo.packageName);
12235                         }
12236                     }
12237                 }
12238             } finally {
12239                 mInjector.binderRestoreCallingIdentity(id);
12240             }
12241         }
12242 
12243         return result;
12244     }
12245 
12246     @Override
12247     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
12248             int userHandle) {
12249         if (!mHasFeature) {
12250             return true;
12251         }
12252         Objects.requireNonNull(who, "ComponentName is null");
12253         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
12254         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
12255                 String.format(NOT_SYSTEM_CALLER_MSG,
12256                         "query if an accessibility service is disabled by admin"));
12257 
12258         synchronized (getLockObject()) {
12259             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
12260             if (admin == null) {
12261                 return false;
12262             }
12263             if (admin.permittedAccessiblityServices == null) {
12264                 return true;
12265             }
12266             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
12267                     admin.permittedAccessiblityServices, userHandle);
12268         }
12269     }
12270 
12271     @Override
12272     public boolean setPermittedInputMethods(ComponentName who, String callerPackageName,
12273             List<String> packageList, boolean calledOnParentInstance) {
12274         if (!mHasFeature) {
12275             return false;
12276         }
12277 
12278         CallerIdentity caller;
12279         if (isPolicyEngineForFinanceFlagEnabled()) {
12280             caller = getCallerIdentity(who, callerPackageName);
12281         } else {
12282             caller = getCallerIdentity(who);
12283             Objects.requireNonNull(who, "ComponentName is null");
12284         }
12285 
12286         int userId = getProfileParentUserIfRequested(
12287                 caller.getUserId(), calledOnParentInstance);
12288         if (calledOnParentInstance) {
12289             if (!isPolicyEngineForFinanceFlagEnabled()) {
12290                 Preconditions.checkCallAuthorization(
12291                         isProfileOwnerOfOrganizationOwnedDevice(caller));
12292             }
12293             Preconditions.checkArgument(packageList == null || packageList.isEmpty(),
12294                     "Permitted input methods must allow all input methods or only "
12295                             + "system input methods when called on the parent instance of an "
12296                             + "organization-owned device");
12297         } else if (!isPolicyEngineForFinanceFlagEnabled()) {
12298             Preconditions.checkCallAuthorization(
12299                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
12300         }
12301 
12302         if (packageList != null) {
12303             for (String pkg : packageList) {
12304                 enforceMaxPackageNameLength(pkg);
12305             }
12306 
12307             List<InputMethodInfo> enabledImes = mInjector.binderWithCleanCallingIdentity(() ->
12308                     InputMethodManagerInternal.get().getEnabledInputMethodListAsUser(userId));
12309             if (enabledImes != null) {
12310                 List<String> enabledPackages = new ArrayList<String>();
12311                 for (InputMethodInfo ime : enabledImes) {
12312                     enabledPackages.add(ime.getPackageName());
12313                 }
12314                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
12315                         userId)) {
12316                     Slogf.e(LOG_TAG, "Cannot set permitted input methods, because the list of "
12317                             + "permitted input methods excludes an already-enabled input method.");
12318                     return false;
12319                 }
12320             }
12321         }
12322 
12323         synchronized (getLockObject()) {
12324             if (isPolicyEngineForFinanceFlagEnabled()) {
12325                 EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
12326                         who, MANAGE_DEVICE_POLICY_INPUT_METHODS,
12327                         caller.getPackageName(), userId);
12328                 if (packageList == null) {
12329                     mDevicePolicyEngine.removeLocalPolicy(
12330                             PolicyDefinition.PERMITTED_INPUT_METHODS,
12331                             admin,
12332                             userId);
12333                 } else {
12334                     mDevicePolicyEngine.setLocalPolicy(
12335                             PolicyDefinition.PERMITTED_INPUT_METHODS,
12336                             admin,
12337                             new StringSetPolicyValue(new HashSet<>(packageList)),
12338                             userId);
12339                 }
12340             } else {
12341                 ActiveAdmin admin = getParentOfAdminIfRequired(
12342                         getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()),
12343                         calledOnParentInstance);
12344                 admin.permittedInputMethods = packageList;
12345                 saveSettingsLocked(caller.getUserId());
12346             }
12347         }
12348 
12349         DevicePolicyEventLogger
12350                 .createEvent(DevicePolicyEnums.SET_PERMITTED_INPUT_METHODS)
12351                 .setAdmin(caller.getPackageName())
12352                 .setStrings(getStringArrayForLogging(packageList, calledOnParentInstance))
12353                 .write();
12354         return true;
12355     }
12356 
12357     private String[] getStringArrayForLogging(List list, boolean calledOnParentInstance) {
12358         List<String> stringList = new ArrayList<String>();
12359         stringList.add(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT);
12360         if (list == null) {
12361             stringList.add(NULL_STRING_ARRAY);
12362         } else {
12363             stringList.addAll((List<String>) list);
12364         }
12365         return stringList.toArray(new String[0]);
12366     }
12367 
12368     @Override
12369     public List<String> getPermittedInputMethods(ComponentName who, String callerPackageName,
12370             boolean calledOnParentInstance) {
12371         if (!mHasFeature) {
12372             return null;
12373         }
12374 
12375         CallerIdentity caller;
12376         if (isPolicyEngineForFinanceFlagEnabled()) {
12377             caller = getCallerIdentity(who, callerPackageName);
12378         } else {
12379             caller = getCallerIdentity(who);
12380             Objects.requireNonNull(who, "ComponentName is null");
12381         }
12382 
12383         if (!isPolicyEngineForFinanceFlagEnabled()) {
12384             if (calledOnParentInstance) {
12385                 Preconditions.checkCallAuthorization(
12386                         isProfileOwnerOfOrganizationOwnedDevice(caller));
12387             } else {
12388                 Preconditions.checkCallAuthorization(
12389                         isDefaultDeviceOwner(caller) || isProfileOwner(caller));
12390             }
12391         }
12392 
12393         synchronized (getLockObject()) {
12394             if (isPolicyEngineForFinanceFlagEnabled()) {
12395                 int affectedUser = calledOnParentInstance ? getProfileParentId(
12396                         caller.getUserId()) : caller.getUserId();
12397                 Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
12398                         PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
12399                 return policy == null ? null : new ArrayList<>(policy);
12400             } else {
12401                 ActiveAdmin admin = getParentOfAdminIfRequired(
12402                         getProfileOwnerOrDeviceOwnerLocked(
12403                                 caller.getUserId()), calledOnParentInstance);
12404                 return admin.permittedInputMethods;
12405             }
12406         }
12407     }
12408 
12409     @Override
12410     public @Nullable List<String> getPermittedInputMethodsAsUser(@UserIdInt int userId) {
12411         final CallerIdentity caller = getCallerIdentity();
12412         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
12413         Preconditions.checkCallAuthorization(canManageUsers(caller) || canQueryAdminPolicy(caller));
12414         final long callingIdentity = Binder.clearCallingIdentity();
12415         try {
12416             return getPermittedInputMethodsUnchecked(userId);
12417         } finally {
12418             Binder.restoreCallingIdentity(callingIdentity);
12419         }
12420     }
12421 
12422     private @Nullable List<String> getPermittedInputMethodsUnchecked(@UserIdInt int userId) {
12423         List<String> result = null;
12424         if (isPolicyEngineForFinanceFlagEnabled()) {
12425             Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
12426                     PolicyDefinition.PERMITTED_INPUT_METHODS, userId);
12427             result = policy == null ? null : new ArrayList<>(policy);
12428         } else {
12429             synchronized (getLockObject()) {
12430                 // Only device or profile owners can have permitted lists set.
12431                 List<ActiveAdmin> admins =
12432                         getActiveAdminsForAffectedUserInclPermissionBasedAdminLocked(
12433                                 userId);
12434                 for (ActiveAdmin admin : admins) {
12435                     List<String> fromAdmin = admin.permittedInputMethods;
12436                     if (fromAdmin != null) {
12437                         if (result == null) {
12438                             result = new ArrayList<String>(fromAdmin);
12439                         } else {
12440                             result.retainAll(fromAdmin);
12441                         }
12442                     }
12443                 }
12444             }
12445         }
12446 
12447         // If we have a permitted list add all system input methods.
12448         if (result != null) {
12449             List<InputMethodInfo> imes = InputMethodManagerInternal
12450                     .get().getInputMethodListAsUser(userId);
12451             if (imes != null) {
12452                 for (InputMethodInfo ime : imes) {
12453                     ServiceInfo serviceInfo = ime.getServiceInfo();
12454                     ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
12455                     if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12456                         result.add(serviceInfo.packageName);
12457                     }
12458                 }
12459             }
12460         }
12461         return result;
12462     }
12463 
12464     @Override
12465     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
12466             int userHandle, boolean calledOnParentInstance) {
12467         if (!mHasFeature) {
12468             return true;
12469         }
12470         Objects.requireNonNull(who, "ComponentName is null");
12471         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
12472         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
12473                 String.format(NOT_SYSTEM_CALLER_MSG,
12474                         "query if an input method is disabled by admin"));
12475 
12476         if (isPolicyEngineForFinanceFlagEnabled()) {
12477             int affectedUser = calledOnParentInstance ? getProfileParentId(userHandle) : userHandle;
12478             Map<EnforcingAdmin, PolicyValue<Set<String>>> policies =
12479                     mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
12480                             PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
12481             EnforcingAdmin admin = null;
12482             for (EnforcingAdmin a : policies.keySet()) {
12483                 if (a.getPackageName().equals(who.getPackageName())) {
12484                     if (policies.get(a).getValue() == null) {
12485                         return true;
12486                     } else {
12487                         return checkPackagesInPermittedListOrSystem(
12488                                 Collections.singletonList(packageName),
12489                                 new ArrayList<>(policies.get(a).getValue()), affectedUser);
12490                     }
12491                 }
12492             }
12493             // Admin didn't set a policy
12494             return false;
12495         } else {
12496             synchronized (getLockObject()) {
12497                 ActiveAdmin admin = getParentOfAdminIfRequired(
12498                         getActiveAdminUncheckedLocked(who, userHandle), calledOnParentInstance);
12499                 if (admin == null) {
12500                     return false;
12501                 }
12502                 if (admin.permittedInputMethods == null) {
12503                     return true;
12504                 }
12505                 return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
12506                         admin.permittedInputMethods, userHandle);
12507             }
12508         }
12509     }
12510 
12511     @Override
12512     public boolean setPermittedCrossProfileNotificationListeners(
12513             ComponentName who, List<String> packageList) {
12514         if (!mHasFeature) {
12515             return false;
12516         }
12517         Objects.requireNonNull(who, "ComponentName is null");
12518         final CallerIdentity caller = getCallerIdentity(who);
12519 
12520         if (!isManagedProfile(caller.getUserId())) {
12521             return false;
12522         }
12523         Preconditions.checkCallAuthorization(isProfileOwner(caller));
12524         synchronized (getLockObject()) {
12525             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
12526             admin.permittedNotificationListeners = packageList;
12527             saveSettingsLocked(caller.getUserId());
12528         }
12529         return true;
12530     }
12531 
12532     @Override
12533     public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
12534         if (!mHasFeature) {
12535             return null;
12536         }
12537         Objects.requireNonNull(who, "ComponentName is null");
12538         final CallerIdentity caller = getCallerIdentity(who);
12539         Preconditions.checkCallAuthorization(
12540                 isDeviceOwner(caller) || isProfileOwner(caller));
12541 
12542         synchronized (getLockObject()) {
12543             // API contract is to return null if there are no permitted cross-profile notification
12544             // listeners, including in Device Owner mode.
12545             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
12546             return admin.permittedNotificationListeners;
12547         }
12548     }
12549 
12550     @Override
12551     public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
12552         if (!mHasFeature) {
12553             return true;
12554         }
12555 
12556         Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
12557         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
12558                 String.format(NOT_SYSTEM_CALLER_MSG,
12559                         "query if a notification listener service is permitted"));
12560 
12561         synchronized (getLockObject()) {
12562             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
12563             if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
12564                 return true;
12565             }
12566             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
12567                     profileOwner.permittedNotificationListeners, userId);
12568 
12569         }
12570     }
12571 
12572     private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
12573         DevicePolicyData policyData = getUserData(userHandle);
12574         if (policyData.mAdminBroadcastPending) {
12575             // Send the initialization data to profile owner and delete the data
12576             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
12577             boolean clearInitBundle = true;
12578             if (admin != null) {
12579                 PersistableBundle initBundle = policyData.mInitBundle;
12580                 clearInitBundle = sendAdminCommandLocked(admin,
12581                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
12582                         initBundle == null ? null : new Bundle(initBundle),
12583                         /* result= */ null ,
12584                         /* inForeground= */ true);
12585             }
12586             if (clearInitBundle) {
12587                 // If there's no admin or we've successfully called the admin, clear the init bundle
12588                 // otherwise, keep it around
12589                 policyData.mInitBundle = null;
12590                 policyData.mAdminBroadcastPending = false;
12591                 saveSettingsLocked(userHandle);
12592             }
12593         }
12594     }
12595 
12596     @Override
12597     public UserHandle createAndManageUser(ComponentName admin, String name,
12598             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
12599         Objects.requireNonNull(admin, "admin is null");
12600         Objects.requireNonNull(profileOwner, "profileOwner is null");
12601         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
12602             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
12603                     + admin + " are not in the same package");
12604         }
12605         final CallerIdentity caller = getCallerIdentity(admin);
12606         // Only allow the system user to use this method
12607         Preconditions.checkCallAuthorization(caller.getUserHandle().isSystem(),
12608                 "createAndManageUser was called from non-system user");
12609         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12610         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CREATE_AND_MANAGE_USER);
12611 
12612         final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
12613         final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
12614                 && UserManager.isDeviceInDemoMode(mContext);
12615         final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
12616         final int targetSdkVersion;
12617 
12618         // Create user.
12619         UserHandle user = null;
12620         synchronized (getLockObject()) {
12621             final long id = mInjector.binderClearCallingIdentity();
12622             try {
12623                 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion(
12624                         caller.getUid());
12625 
12626                 // Return detail error code for checks inside
12627                 // UserManagerService.createUserInternalUnchecked.
12628                 DeviceStorageMonitorInternal deviceStorageMonitorInternal =
12629                         LocalServices.getService(DeviceStorageMonitorInternal.class);
12630                 if (deviceStorageMonitorInternal.isMemoryLow()) {
12631                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
12632                         throw new ServiceSpecificException(
12633                                 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage");
12634                     } else {
12635                         return null;
12636                     }
12637                 }
12638 
12639                 String userType = demo ? UserManager.USER_TYPE_FULL_DEMO
12640                         : UserManager.USER_TYPE_FULL_SECONDARY;
12641                 int userInfoFlags = ephemeral ? UserInfo.FLAG_EPHEMERAL : 0;
12642 
12643                 if (!mUserManager.canAddMoreUsers(userType)) {
12644                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
12645                         throw new ServiceSpecificException(
12646                                 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached");
12647                     } else {
12648                         return null;
12649                     }
12650                 }
12651 
12652                 String[] disallowedPackages = null;
12653                 if (!leaveAllSystemAppsEnabled) {
12654                     disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
12655                             UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
12656                             new String[0]);
12657                 }
12658 
12659                 Object token = new Object();
12660                 Slogf.d(LOG_TAG, "Adding new pending token: " + token);
12661                 mPendingUserCreatedCallbackTokens.add(token);
12662                 try {
12663                     UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
12664                             userType, userInfoFlags, disallowedPackages, token);
12665                     if (userInfo != null) {
12666                         user = userInfo.getUserHandle();
12667                     }
12668                 } catch (UserManager.CheckedUserOperationException e) {
12669                     Slogf.e(LOG_TAG, "Couldn't createUserEvenWhenDisallowed", e);
12670                 }
12671             } finally {
12672                 mInjector.binderRestoreCallingIdentity(id);
12673             }
12674         } // synchronized
12675 
12676         if (user == null) {
12677             if (targetSdkVersion >= Build.VERSION_CODES.P) {
12678                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
12679                         "failed to create user");
12680             } else {
12681                 return null;
12682             }
12683         }
12684 
12685         final int userHandle = user.getIdentifier();
12686         final long id = mInjector.binderClearCallingIdentity();
12687         try {
12688             maybeInstallDevicePolicyManagementRoleHolderInUser(userHandle);
12689 
12690             manageUserUnchecked(admin, profileOwner, userHandle, adminExtras,
12691                     /* showDisclaimer= */ true);
12692 
12693             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
12694                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
12695                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
12696             }
12697 
12698             sendProvisioningCompletedBroadcast(
12699                     userHandle, ACTION_PROVISION_MANAGED_USER, leaveAllSystemAppsEnabled);
12700 
12701             return user;
12702         } catch (Throwable re) {
12703             mUserManager.removeUser(userHandle);
12704             if (targetSdkVersion >= Build.VERSION_CODES.P) {
12705                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
12706                         re.getMessage());
12707             } else {
12708                 return null;
12709             }
12710         } finally {
12711             mInjector.binderRestoreCallingIdentity(id);
12712         }
12713     }
12714 
12715     private void sendProvisioningCompletedBroadcast(
12716             int user, String action, boolean leaveAllSystemAppsEnabled) {
12717         final Intent intent = new Intent(DevicePolicyManager.ACTION_PROVISIONING_COMPLETED)
12718                 .putExtra(Intent.EXTRA_USER_HANDLE, user)
12719                 .putExtra(Intent.EXTRA_USER, UserHandle.of(user))
12720                 .putExtra(
12721                         DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
12722                         leaveAllSystemAppsEnabled)
12723                 .putExtra(DevicePolicyManager.EXTRA_PROVISIONING_ACTION,
12724                         action)
12725                 .setPackage(getManagedProvisioningPackage(mContext))
12726                 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12727         mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
12728     }
12729 
12730     private void manageUserUnchecked(ComponentName admin, ComponentName profileOwner,
12731             @UserIdInt int userId, @Nullable PersistableBundle adminExtras,
12732             boolean showDisclaimer) {
12733         synchronized (getLockObject()) {
12734             if (VERBOSE_LOG) {
12735                 Slogf.v(LOG_TAG, "manageUserUnchecked(): admin=" + admin + ", po=" + profileOwner
12736                         + ", userId=" + userId + ", hasAdminExtras=" + (adminExtras != null)
12737                         + ", showDisclaimer=" + showDisclaimer);
12738             }
12739         }
12740         final String adminPkg = admin.getPackageName();
12741         mInjector.binderWithCleanCallingIdentity(() -> {
12742             try {
12743                 // Install the profile owner if not present.
12744                 if (!mIPackageManager.isPackageAvailable(adminPkg, userId)) {
12745                     mIPackageManager.installExistingPackageAsUser(adminPkg, userId,
12746                             PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
12747                             PackageManager.INSTALL_REASON_POLICY,
12748                             /* allowlistedRestrictedPermissions= */ null);
12749                 }
12750             } catch (RemoteException e) {
12751                 // Does not happen, same process
12752                 Slogf.wtf(LOG_TAG, e, "Failed to install admin package %s for user %d",
12753                         adminPkg, userId);
12754             }
12755         });
12756 
12757         // Set admin.
12758         setActiveAdmin(profileOwner, /* refreshing= */ true, userId);
12759         setProfileOwner(profileOwner, userId);
12760 
12761         synchronized (getLockObject()) {
12762             DevicePolicyData policyData = getUserData(userId);
12763             policyData.mInitBundle = adminExtras;
12764             policyData.mAdminBroadcastPending = true;
12765             policyData.mNewUserDisclaimer = showDisclaimer
12766                     ? DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED
12767                     : DevicePolicyData.NEW_USER_DISCLAIMER_NOT_NEEDED;
12768             saveSettingsLocked(userId);
12769 
12770         }
12771     }
12772 
12773     private void handleNewUserCreated(UserInfo user, @Nullable Object token) {
12774         if (VERBOSE_LOG) {
12775             Slogf.v(LOG_TAG, "handleNewUserCreated(): user=" + user.toFullString()
12776                     + ", token=" + token);
12777         }
12778 
12779         final int userId = user.id;
12780 
12781         if (isPolicyEngineForFinanceFlagEnabled() || isPermissionCheckFlagEnabled()) {
12782             mDevicePolicyEngine.handleUserCreated(user);
12783         }
12784 
12785         if (token != null) {
12786             synchronized (getLockObject()) {
12787                 if (mPendingUserCreatedCallbackTokens.contains(token)) {
12788                     // Ignore because it was triggered by createAndManageUser()
12789                     Slogf.d(LOG_TAG, "handleNewUserCreated(): ignoring for user " + userId
12790                             + " due to token " + token);
12791                     mPendingUserCreatedCallbackTokens.remove(token);
12792                     return;
12793                 }
12794             }
12795         }
12796 
12797         if (!mOwners.hasDeviceOwner() || !user.isFull() || user.isManagedProfile()
12798                 || user.isGuest()) {
12799             return;
12800         }
12801 
12802         if (mInjector.userManagerIsHeadlessSystemUserMode()) {
12803             ComponentName admin = mOwners.getDeviceOwnerComponent();
12804             Slogf.i(LOG_TAG, "Automatically setting profile owner (" + admin + ") on new user "
12805                     + userId);
12806             manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin,
12807                     /* managedUser= */ userId, /* adminExtras= */ null, /* showDisclaimer= */ true);
12808         } else {
12809             Slogf.i(LOG_TAG, "User %d added on DO mode; setting ShowNewUserDisclaimer", userId);
12810             setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED);
12811         }
12812     }
12813 
12814     @Override
12815     public void acknowledgeNewUserDisclaimer(@UserIdInt int userId) {
12816         CallerIdentity callerIdentity = getCallerIdentity();
12817         Preconditions.checkCallAuthorization(canManageUsers(callerIdentity)
12818                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
12819 
12820         setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_ACKNOWLEDGED);
12821     }
12822 
12823     private void setShowNewUserDisclaimer(@UserIdInt int userId, String value) {
12824         Slogf.i(LOG_TAG, "Setting new user disclaimer for user " + userId + " as " + value);
12825         synchronized (getLockObject()) {
12826             DevicePolicyData policyData = getUserData(userId);
12827             policyData.mNewUserDisclaimer = value;
12828             saveSettingsLocked(userId);
12829         }
12830     }
12831 
12832     private void showNewUserDisclaimerIfNecessary(@UserIdInt int userId) {
12833         boolean mustShow;
12834         synchronized (getLockObject()) {
12835             DevicePolicyData policyData = getUserData(userId);
12836             if (VERBOSE_LOG) {
12837                 Slogf.v(LOG_TAG, "showNewUserDisclaimerIfNecessary(" + userId + "): "
12838                         + policyData.mNewUserDisclaimer + ")");
12839             }
12840             mustShow = DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED
12841                     .equals(policyData.mNewUserDisclaimer);
12842         }
12843         if (!mustShow) return;
12844 
12845         Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_NEW_USER_DISCLAIMER);
12846 
12847         // TODO(b/172691310): add CTS tests to make sure disclaimer is shown
12848         Slogf.i(LOG_TAG, "Dispatching ACTION_SHOW_NEW_USER_DISCLAIMER intent");
12849         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
12850     }
12851 
12852     @Override
12853     public boolean isNewUserDisclaimerAcknowledged(@UserIdInt int userId) {
12854         CallerIdentity callerIdentity = getCallerIdentity();
12855         Preconditions.checkCallAuthorization(canManageUsers(callerIdentity)
12856                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
12857         synchronized (getLockObject()) {
12858             DevicePolicyData policyData = getUserData(userId);
12859             return policyData.isNewUserDisclaimerAcknowledged();
12860         }
12861     }
12862 
12863     @Override
12864     public boolean removeUser(ComponentName who, UserHandle userHandle) {
12865         Objects.requireNonNull(who, "ComponentName is null");
12866         Objects.requireNonNull(userHandle, "UserHandle is null");
12867         final CallerIdentity caller = getCallerIdentity(who);
12868         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12869         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_USER);
12870 
12871         return mInjector.binderWithCleanCallingIdentity(() -> {
12872             String restriction = isManagedProfile(userHandle.getIdentifier())
12873                     ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
12874                     : UserManager.DISALLOW_REMOVE_USER;
12875             if (isAdminAffectedByRestriction(who, restriction, caller.getUserId())) {
12876                 Slogf.w(LOG_TAG, "The device owner cannot remove a user because %s is enabled, and "
12877                         + "was not set by the device owner", restriction);
12878                 return false;
12879             }
12880             return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
12881         });
12882     }
12883 
12884     private boolean isAdminAffectedByRestriction(
12885             @Nullable ComponentName admin, String userRestriction, int userId) {
12886         switch (mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
12887             case UserManager.RESTRICTION_NOT_SET:
12888                 return false;
12889             case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
12890             case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
12891                 return !(isDeviceOwner(admin, userId) || isProfileOwner(admin, userId));
12892             default:
12893                 return true;
12894         }
12895     }
12896 
12897     @Override
12898     public boolean switchUser(ComponentName who, UserHandle userHandle) {
12899         Objects.requireNonNull(who, "ComponentName is null");
12900         final CallerIdentity caller = getCallerIdentity(who);
12901         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12902         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SWITCH_USER);
12903 
12904         boolean switched = false;
12905         // Save previous logout user id in case of failure
12906         int logoutUserId = getLogoutUserIdUnchecked();
12907         synchronized (getLockObject()) {
12908             long id = mInjector.binderClearCallingIdentity();
12909             try {
12910                 int userId = UserHandle.USER_SYSTEM;
12911                 if (userHandle != null) {
12912                     userId = userHandle.getIdentifier();
12913                 }
12914                 Slogf.i(LOG_TAG, "Switching to user %d (logout user is %d)", userId, logoutUserId);
12915                 setLogoutUserIdLocked(UserHandle.USER_CURRENT);
12916                 switched = mInjector.getIActivityManager().switchUser(userId);
12917                 if (!switched) {
12918                     Slogf.w(LOG_TAG, "Failed to switch to user %d", userId);
12919                 } else {
12920                     Slogf.d(LOG_TAG, "Switched");
12921                 }
12922                 return switched;
12923             } catch (RemoteException e) {
12924                 Slogf.e(LOG_TAG, "Couldn't switch user", e);
12925                 return false;
12926             } finally {
12927                 mInjector.binderRestoreCallingIdentity(id);
12928                 if (!switched) {
12929                     setLogoutUserIdLocked(logoutUserId);
12930                 }
12931             }
12932         }
12933     }
12934 
12935     @Override
12936     public int getLogoutUserId() {
12937         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
12938                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
12939 
12940         return getLogoutUserIdUnchecked();
12941     }
12942 
12943     private @UserIdInt int getLogoutUserIdUnchecked() {
12944         synchronized (getLockObject()) {
12945             return mLogoutUserId;
12946         }
12947     }
12948 
12949     private void clearLogoutUser() {
12950         synchronized (getLockObject()) {
12951             setLogoutUserIdLocked(UserHandle.USER_NULL);
12952         }
12953     }
12954 
12955     @GuardedBy("getLockObject()")
12956     private void setLogoutUserIdLocked(@UserIdInt int userId) {
12957         if (userId == UserHandle.USER_CURRENT) {
12958             userId = getCurrentForegroundUserId();
12959         }
12960 
12961         Slogf.d(LOG_TAG, "setLogoutUserId(): %d -> %d", mLogoutUserId, userId);
12962         mLogoutUserId = userId;
12963     }
12964 
12965     @Override
12966     public int startUserInBackground(ComponentName who, UserHandle userHandle) {
12967         Objects.requireNonNull(who, "ComponentName is null");
12968         Objects.requireNonNull(userHandle, "UserHandle is null");
12969         final CallerIdentity caller = getCallerIdentity(who);
12970         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12971         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_START_USER_IN_BACKGROUND);
12972 
12973         final int userId = userHandle.getIdentifier();
12974         if (isManagedProfile(userId)) {
12975             Slogf.w(LOG_TAG, "Managed profile cannot be started in background");
12976             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
12977         }
12978 
12979         final long id = mInjector.binderClearCallingIdentity();
12980         try {
12981             if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) {
12982                 Slogf.w(LOG_TAG, "Cannot start user %d, too many users in background", userId);
12983                 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS;
12984             }
12985 
12986             Slogf.i(LOG_TAG, "Starting user %d in background", userId);
12987             if (mInjector.getIActivityManager().startUserInBackground(userId)) {
12988                 return UserManager.USER_OPERATION_SUCCESS;
12989             } else {
12990                 Slogf.w(LOG_TAG, "failed to start user %d in background", userId);
12991                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
12992             }
12993         } catch (RemoteException e) {
12994             // Same process, should not happen.
12995             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
12996         } finally {
12997             mInjector.binderRestoreCallingIdentity(id);
12998         }
12999     }
13000 
13001     @Override
13002     public int stopUser(ComponentName who, UserHandle userHandle) {
13003         Objects.requireNonNull(who, "ComponentName is null");
13004         Objects.requireNonNull(userHandle, "UserHandle is null");
13005         final CallerIdentity caller = getCallerIdentity(who);
13006         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
13007         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_STOP_USER);
13008 
13009         final int userId = userHandle.getIdentifier();
13010         if (isManagedProfile(userId)) {
13011             Slogf.w(LOG_TAG, "Managed profile cannot be stopped");
13012             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
13013         }
13014 
13015         return stopUserUnchecked(userId);
13016     }
13017 
13018     @Override
13019     public int logoutUser(ComponentName who) {
13020         Objects.requireNonNull(who, "ComponentName is null");
13021         final CallerIdentity caller = getCallerIdentity(who);
13022         Preconditions.checkCallAuthorization(
13023                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
13024         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOGOUT_USER);
13025 
13026         final int callingUserId = caller.getUserId();
13027         synchronized (getLockObject()) {
13028             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
13029                 throw new SecurityException("Admin " + who +
13030                         " is neither the device owner or affiliated user's profile owner.");
13031             }
13032         }
13033 
13034         if (isManagedProfile(callingUserId)) {
13035             Slogf.w(LOG_TAG, "Managed profile cannot be logout");
13036             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
13037         }
13038 
13039         if (callingUserId != mInjector
13040                 .binderWithCleanCallingIdentity(() -> getCurrentForegroundUserId())) {
13041             Slogf.d(LOG_TAG, "logoutUser(): user %d is in background, just stopping, not switching",
13042                     callingUserId);
13043             return stopUserUnchecked(callingUserId);
13044         }
13045 
13046         return logoutUserUnchecked(/* userIdToStop= */ callingUserId);
13047     }
13048 
13049     @Override
13050     public int logoutUserInternal() {
13051         CallerIdentity caller = getCallerIdentity();
13052         Preconditions.checkCallAuthorization(canManageUsers(caller)
13053                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
13054 
13055         int currentUserId = getCurrentForegroundUserId();
13056         if (VERBOSE_LOG) {
13057             Slogf.v(LOG_TAG, "logout() called by uid %d; current user is %d", caller.getUid(),
13058                     currentUserId);
13059         }
13060         int result = logoutUserUnchecked(currentUserId);
13061         if (VERBOSE_LOG) {
13062             Slogf.v(LOG_TAG, "Result of logout(): %d", result);
13063         }
13064         return result;
13065     }
13066 
13067     private int logoutUserUnchecked(@UserIdInt int userIdToStop) {
13068         int logoutUserId = getLogoutUserIdUnchecked();
13069         if (logoutUserId == UserHandle.USER_NULL) {
13070             // Could happen on devices using headless system user mode when called before calling
13071             // switchUser() or startUserInBackground() first
13072             Slogf.w(LOG_TAG, "logoutUser(): could not determine which user to switch to");
13073             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13074         }
13075         final long id = mInjector.binderClearCallingIdentity();
13076         try {
13077             Slogf.i(LOG_TAG, "logoutUser(): switching to user %d", logoutUserId);
13078             if (!mInjector.getIActivityManager().switchUser(logoutUserId)) {
13079                 Slogf.w(LOG_TAG, "Failed to switch to user %d", logoutUserId);
13080                 // This should never happen as target user is determined by getPreviousUserId()
13081                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13082             }
13083             clearLogoutUser();
13084         } catch (RemoteException e) {
13085             // Same process, should not happen.
13086             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13087         } finally {
13088             mInjector.binderRestoreCallingIdentity(id);
13089         }
13090 
13091         return stopUserUnchecked(userIdToStop);
13092     }
13093 
13094     private int stopUserUnchecked(@UserIdInt int userId) {
13095         Slogf.i(LOG_TAG, "Stopping user %d", userId);
13096         final long id = mInjector.binderClearCallingIdentity();
13097         try {
13098             switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) {
13099                 case ActivityManager.USER_OP_SUCCESS:
13100                     return UserManager.USER_OPERATION_SUCCESS;
13101                 case ActivityManager.USER_OP_IS_CURRENT:
13102                     return UserManager.USER_OPERATION_ERROR_CURRENT_USER;
13103                 default:
13104                     return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13105             }
13106         } catch (RemoteException e) {
13107             // Same process, should not happen.
13108             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13109         } finally {
13110             mInjector.binderRestoreCallingIdentity(id);
13111         }
13112     }
13113 
13114     @Override
13115     public List<UserHandle> getSecondaryUsers(ComponentName who) {
13116         Objects.requireNonNull(who, "ComponentName is null");
13117         final CallerIdentity caller = getCallerIdentity(who);
13118         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
13119 
13120         return mInjector.binderWithCleanCallingIdentity(() -> {
13121             final List<UserInfo> userInfos = mInjector.getUserManager().getAliveUsers();
13122             final List<UserHandle> userHandles = new ArrayList<>();
13123             for (UserInfo userInfo : userInfos) {
13124                 UserHandle userHandle = userInfo.getUserHandle();
13125                 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
13126                     userHandles.add(userInfo.getUserHandle());
13127                 }
13128             }
13129             return userHandles;
13130         });
13131     }
13132 
13133     @Override
13134     public boolean isEphemeralUser(ComponentName who) {
13135         Objects.requireNonNull(who, "ComponentName is null");
13136 
13137         final CallerIdentity caller = getCallerIdentity(who);
13138         Preconditions.checkCallAuthorization(
13139                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
13140 
13141         return mInjector.binderWithCleanCallingIdentity(
13142                 () -> mInjector.getUserManager().isUserEphemeral(caller.getUserId()));
13143     }
13144 
13145     @Override
13146     public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
13147             String packageName) {
13148         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
13149 
13150         if (isUnicornFlagEnabled()) {
13151             EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
13152                     who,
13153                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
13154                     caller.getPackageName(),
13155                     caller.getUserId()
13156             );
13157 
13158             LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
13159                     mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
13160                             PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
13161                             caller.getUserId());
13162             if (policies.isEmpty() || !policies.containsKey(enforcingAdmin)) {
13163                 return Bundle.EMPTY;
13164             }
13165             return policies.get(enforcingAdmin).getValue();
13166         } else {
13167             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13168                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
13169                     || (caller.hasPackage() && isCallerDelegate(caller,
13170                     DELEGATION_APP_RESTRICTIONS)));
13171             return mInjector.binderWithCleanCallingIdentity(() -> {
13172                 Bundle bundle = mUserManager.getApplicationRestrictions(packageName,
13173                         caller.getUserHandle());
13174                 // if no restrictions were saved, mUserManager.getApplicationRestrictions
13175                 // returns null, but DPM method should return an empty Bundle as per JavaDoc
13176                 return bundle != null ? bundle : Bundle.EMPTY;
13177             });
13178         }
13179     }
13180 
13181     /**
13182      * Returns the apps that are non-exempt from some policies (such as suspension), and populates
13183      * the given set with the apps that are exempt.
13184      *
13185      * @param packageNames apps to check
13186      * @param outputExemptApps will be populate with subset of {@code packageNames} that is exempt
13187      * from some policy restrictions
13188      *
13189      * @return subset of {@code packageNames} that is affected by some policy restrictions.
13190      */
13191     private String[] populateNonExemptAndExemptFromPolicyApps(String[] packageNames,
13192             Set<String> outputExemptApps) {
13193         Preconditions.checkArgument(outputExemptApps.isEmpty(), "outputExemptApps is not empty");
13194         List<String> exemptAppsList = listPolicyExemptAppsUnchecked(mContext);
13195         if (exemptAppsList.isEmpty()) {
13196             return packageNames;
13197         }
13198         // Using a set so contains() is O(1)
13199         Set<String> exemptApps = new HashSet<>(exemptAppsList);
13200         List<String> nonExemptApps = new ArrayList<>(packageNames.length);
13201         for (int i = 0; i < packageNames.length; i++) {
13202             String app = packageNames[i];
13203             if (exemptApps.contains(app)) {
13204                 outputExemptApps.add(app);
13205             } else {
13206                 nonExemptApps.add(app);
13207             }
13208         }
13209         String[] result = new String[nonExemptApps.size()];
13210         nonExemptApps.toArray(result);
13211         return result;
13212     }
13213 
13214     @Override
13215     public String[] setPackagesSuspended(ComponentName who, String callerPackage,
13216             String[] packageNames, boolean suspended) {
13217         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
13218         ActiveAdmin admin;
13219 
13220         if (isUnicornFlagEnabled()) {
13221             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
13222                     who,
13223                     MANAGE_DEVICE_POLICY_PACKAGE_STATE,
13224                     caller.getPackageName(),
13225                     caller.getUserId());
13226             admin = enforcingAdmin.getActiveAdmin();
13227         } else {
13228             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13229                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
13230                     || (caller.hasPackage() && isCallerDelegate(caller,
13231                     DELEGATION_PACKAGE_ACCESS)));
13232             synchronized (getLockObject()) {
13233                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
13234             }
13235         }
13236         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PACKAGES_SUSPENDED);
13237 
13238         // Must remove the exempt apps from the input before calling PM, then add them back to
13239         // the array returned to the caller
13240         Set<String> exemptApps = new HashSet<>();
13241         packageNames = populateNonExemptAndExemptFromPolicyApps(packageNames, exemptApps);
13242 
13243         String[] nonSuspendedPackages = null;
13244         synchronized (getLockObject()) {
13245             long id = mInjector.binderClearCallingIdentity();
13246             try {
13247                 nonSuspendedPackages = mInjector.getPackageManagerInternal()
13248                         .setPackagesSuspendedByAdmin(caller.getUserId(), packageNames, suspended);
13249             } finally {
13250                 mInjector.binderRestoreCallingIdentity(id);
13251             }
13252         }
13253         DevicePolicyEventLogger
13254                 .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED)
13255                 .setAdmin(caller.getPackageName())
13256                 .setBoolean(/* isDelegate */ who == null)
13257                 .setStrings(packageNames)
13258                 .write();
13259 
13260         if (nonSuspendedPackages == null) {
13261             Slogf.w(LOG_TAG, "PM failed to suspend packages (%s)", Arrays.toString(packageNames));
13262             return packageNames;
13263         }
13264 
13265         ArraySet<String> changed = new ArraySet<>(packageNames);
13266         if (suspended) {
13267             // Only save those packages that are actually suspended. If a package is exempt or is
13268             // unsuspendable, it is skipped.
13269             changed.removeAll(List.of(nonSuspendedPackages));
13270         } else {
13271             // If an admin tries to unsuspend a package that is either exempt or is not
13272             // suspendable, drop it from the stored list assuming it must be already unsuspended.
13273             changed.addAll(exemptApps);
13274         }
13275 
13276         synchronized (getLockObject()) {
13277             ArraySet<String> current = new ArraySet<>(admin.suspendedPackages);
13278             if (suspended) {
13279                 current.addAll(changed);
13280             } else {
13281                 current.removeAll(changed);
13282             }
13283             admin.suspendedPackages = current.isEmpty() ? null : new ArrayList<>(current);
13284             saveSettingsLocked(caller.getUserId());
13285         }
13286 
13287         if (exemptApps.isEmpty()) {
13288             return nonSuspendedPackages;
13289         }
13290 
13291         String[] result = buildNonSuspendedPackagesUnionArray(nonSuspendedPackages, exemptApps);
13292         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Returning %s", Arrays.toString(result));
13293         return result;
13294     }
13295 
13296     /**
13297      * Returns an array containing the union of the given non-suspended packages and
13298      * exempt apps. Assumes both parameters are non-null and non-empty.
13299      */
13300     private String[] buildNonSuspendedPackagesUnionArray(String[] nonSuspendedPackages,
13301             Set<String> exemptApps) {
13302         String[] result = new String[nonSuspendedPackages.length + exemptApps.size()];
13303         int index = 0;
13304         for (String app : nonSuspendedPackages) {
13305             result[index++] = app;
13306         }
13307         for (String app : exemptApps) {
13308             result[index++] = app;
13309         }
13310         return result;
13311     }
13312 
13313     @Override
13314     public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
13315         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
13316 
13317         if (isUnicornFlagEnabled()) {
13318             enforcePermission(
13319                     MANAGE_DEVICE_POLICY_PACKAGE_STATE,
13320                     caller.getPackageName(),
13321                     caller.getUserId());
13322         } else {
13323             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13324                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
13325                     || (caller.hasPackage() && isCallerDelegate(caller,
13326                     DELEGATION_PACKAGE_ACCESS)));
13327         }
13328 
13329         synchronized (getLockObject()) {
13330             long id = mInjector.binderClearCallingIdentity();
13331             try {
13332                 return mIPackageManager.isPackageSuspendedForUser(packageName, caller.getUserId());
13333             } catch (RemoteException re) {
13334                 // Shouldn't happen.
13335                 Slogf.e(LOG_TAG, "Failed talking to the package manager", re);
13336             } finally {
13337                 mInjector.binderRestoreCallingIdentity(id);
13338             }
13339             return false;
13340         }
13341     }
13342 
13343     @Override
13344     public List<String> listPolicyExemptApps() {
13345         CallerIdentity caller = getCallerIdentity();
13346         Preconditions.checkCallAuthorization(
13347                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)
13348                         || isDefaultDeviceOwner(caller) || isProfileOwner(caller));
13349 
13350         return listPolicyExemptAppsUnchecked(mContext);
13351     }
13352 
13353     private static List<String> listPolicyExemptAppsUnchecked(Context context) {
13354         // TODO(b/181238156): decide whether it should only list the apps set by the resources,
13355         // or also the "critical" apps defined by PersonalAppsSuspensionHelper (like SMS app).
13356         // If it's the latter, refactor PersonalAppsSuspensionHelper so it (or a superclass) takes
13357         // the resources on constructor.
13358         String[] core = context.getResources().getStringArray(R.array.policy_exempt_apps);
13359         String[] vendor = context.getResources().getStringArray(R.array.vendor_policy_exempt_apps);
13360 
13361         int size = core.length + vendor.length;
13362         Set<String> apps = new ArraySet<>(size);
13363         for (String app : core) {
13364             apps.add(app);
13365         }
13366         for (String app : vendor) {
13367             apps.add(app);
13368         }
13369 
13370         return new ArrayList<>(apps);
13371     }
13372 
13373     @Override
13374     public void setUserRestriction(
13375             ComponentName who, String callerPackage, String key, boolean enabledFromThisOwner,
13376             boolean parent) {
13377 
13378         CallerIdentity caller;
13379         if (isPolicyEngineForFinanceFlagEnabled()) {
13380             caller = getCallerIdentity(who, callerPackage);
13381         } else {
13382             caller = getCallerIdentity(who);
13383         }
13384         int userId = caller.getUserId();
13385         int affectedUserId = parent ? getProfileParentId(userId) : userId;
13386 
13387         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
13388 
13389         if (isPolicyEngineForFinanceFlagEnabled()) {
13390             if (!isDeviceOwner(caller) && !isProfileOwner(caller)) {
13391                 EnforcingAdmin admin = enforcePermissionForUserRestriction(
13392                         who,
13393                         key,
13394                         caller.getPackageName(),
13395                         affectedUserId);
13396                 if (!mInjector.isChangeEnabled(ENABLE_COEXISTENCE_CHANGE, callerPackage, userId)) {
13397                     throw new IllegalStateException("Calling package is not targeting Android U.");
13398                 }
13399                 if (!UserRestrictionsUtils.isValidRestriction(key)) {
13400                     throw new IllegalArgumentException("Invalid restriction key: " + key);
13401                 }
13402                 PolicyDefinition<Boolean> policyDefinition =
13403                         PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
13404                 if (enabledFromThisOwner) {
13405                     setLocalUserRestrictionInternal(
13406                             admin, key, /* enabled= */ true, affectedUserId);
13407                 } else {
13408                     // Remove any local and global policy that was set by the admin
13409                     if (!policyDefinition.isLocalOnlyPolicy()) {
13410                         setGlobalUserRestrictionInternal(admin, key, /* enabled= */ false);
13411                     }
13412                     if (!policyDefinition.isGlobalOnlyPolicy()) {
13413                         setLocalUserRestrictionInternal(admin, key, /* enabled= */ false,
13414                                 userId);
13415 
13416                         int parentUserId = getProfileParentId(userId);
13417                         if (parentUserId != userId) {
13418                             setLocalUserRestrictionInternal(
13419                                     admin, key, /* enabled= */ false, parentUserId);
13420                         }
13421                     }
13422                 }
13423             } else {
13424                 if (!UserRestrictionsUtils.isValidRestriction(key)) {
13425                     return;
13426                 }
13427                 Objects.requireNonNull(who, "ComponentName is null");
13428                 EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
13429                 checkAdminCanSetRestriction(caller, parent, key);
13430                 setBackwardCompatibleUserRestriction(
13431                         caller, admin, key, enabledFromThisOwner, parent);
13432             }
13433         } else {
13434             if (!UserRestrictionsUtils.isValidRestriction(key)) {
13435                 return;
13436             }
13437             Objects.requireNonNull(who, "ComponentName is null");
13438             checkAdminCanSetRestriction(caller, parent, key);
13439             synchronized (getLockObject()) {
13440                 final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
13441                         getProfileOwnerOrDeviceOwnerLocked(userId), parent);
13442                 // Save the restriction to ActiveAdmin.
13443                 final Bundle restrictions = activeAdmin.ensureUserRestrictions();
13444                 if (enabledFromThisOwner) {
13445                     restrictions.putBoolean(key, true);
13446                 } else {
13447                     restrictions.remove(key);
13448                 }
13449                 saveUserRestrictionsLocked(userId);
13450             }
13451         }
13452         logUserRestrictionCall(key, enabledFromThisOwner, parent, caller);
13453     }
13454 
13455     private void checkAdminCanSetRestriction(CallerIdentity caller, boolean parent, String key) {
13456         if (parent) {
13457             Preconditions.checkCallAuthorization(
13458                     isProfileOwnerOfOrganizationOwnedDevice(caller));
13459         } else {
13460             Preconditions.checkCallAuthorization(
13461                     isDeviceOwner(caller) || isProfileOwner(caller));
13462         }
13463         synchronized (getLockObject()) {
13464             if (isDefaultDeviceOwner(caller)) {
13465                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
13466                     throw new SecurityException("Device owner cannot set user restriction "
13467                             + key);
13468                 }
13469                 Preconditions.checkArgument(!parent,
13470                         "Cannot use the parent instance in Device Owner mode");
13471             } else if (isFinancedDeviceOwner(caller)) {
13472                 if (!UserRestrictionsUtils.canFinancedDeviceOwnerChange(key)) {
13473                     throw new SecurityException("Cannot set user restriction " + key
13474                             + " when managing a financed device");
13475                 }
13476                 Preconditions.checkArgument(!parent,
13477                         "Cannot use the parent instance in Financed Device Owner"
13478                                 + " mode");
13479             } else {
13480                 boolean profileOwnerCanChangeOnItself = !parent
13481                         && UserRestrictionsUtils.canProfileOwnerChange(
13482                         key, caller.getUserId() == getMainUserId());
13483                 boolean orgOwnedProfileOwnerCanChangeGlobally = parent
13484                         && isProfileOwnerOfOrganizationOwnedDevice(caller)
13485                         && UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(
13486                         key);
13487 
13488                 if (!profileOwnerCanChangeOnItself && !orgOwnedProfileOwnerCanChangeGlobally) {
13489                     throw new SecurityException("Profile owner cannot set user restriction "
13490                             + key);
13491                 }
13492             }
13493         }
13494     }
13495     private void setBackwardCompatibleUserRestriction(
13496             CallerIdentity caller, EnforcingAdmin admin, String key, boolean enabled,
13497             boolean parent) {
13498         synchronized (getLockObject()) {
13499             if (isDeviceOwner(caller)) {
13500                 if (UserRestrictionsUtils.isGlobal(OWNER_TYPE_DEVICE_OWNER, key)) {
13501                     setGlobalUserRestrictionInternal(admin, key, enabled);
13502                 } else {
13503                     setLocalUserRestrictionInternal(admin, key, enabled, caller.getUserId());
13504                 }
13505             } else if (isProfileOwner(caller)) {
13506                 if (UserRestrictionsUtils.isGlobal(OWNER_TYPE_PROFILE_OWNER, key)
13507                         || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)
13508                         && UserRestrictionsUtils.isGlobal(
13509                                 OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE, key))) {
13510                     setGlobalUserRestrictionInternal(admin, key, enabled);
13511                 } else {
13512                     int affectedUserId = parent
13513                             ? getProfileParentId(caller.getUserId()) : caller.getUserId();
13514                     setLocalUserRestrictionInternal(admin, key, enabled, affectedUserId);
13515                 }
13516             } else {
13517                 throw new IllegalStateException("Non-DO/Non-PO cannot set restriction " + key
13518                         + " while targetSdkVersion is less than UPSIDE_DOWN_CAKE");
13519             }
13520         }
13521     }
13522 
13523     @Override
13524     public void setUserRestrictionGlobally(String callerPackage, String key) {
13525         final CallerIdentity caller = getCallerIdentity(callerPackage);
13526 
13527         EnforcingAdmin admin = enforcePermissionForUserRestriction(
13528                 /* who= */ null,
13529                 key,
13530                 caller.getPackageName(),
13531                 UserHandle.USER_ALL
13532         );
13533 
13534         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
13535 
13536         if (!isPolicyEngineForFinanceFlagEnabled()) {
13537             throw new IllegalStateException("Feature flag is not enabled.");
13538         }
13539         if (isDeviceOwner(caller) || isProfileOwner(caller)) {
13540             throw new SecurityException("Admins are not allowed to call this API.");
13541         }
13542         if (!mInjector.isChangeEnabled(
13543                 ENABLE_COEXISTENCE_CHANGE, callerPackage, caller.getUserId())) {
13544             throw new IllegalStateException("Calling package is not targeting Android U.");
13545         }
13546         if (!UserRestrictionsUtils.isValidRestriction(key)) {
13547             throw new IllegalArgumentException("Invalid restriction key: " + key);
13548         }
13549 
13550         setGlobalUserRestrictionInternal(admin, key, /* enabled= */ true);
13551 
13552         logUserRestrictionCall(key, /* enabled= */ true, /* parent= */ false, caller);
13553     }
13554     private void setLocalUserRestrictionInternal(
13555             EnforcingAdmin admin, String key, boolean enabled, int userId) {
13556         PolicyDefinition<Boolean> policyDefinition =
13557                 PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
13558         if (enabled) {
13559             mDevicePolicyEngine.setLocalPolicy(
13560                     policyDefinition,
13561                     admin,
13562                     new BooleanPolicyValue(true),
13563                     userId);
13564         } else {
13565             mDevicePolicyEngine.removeLocalPolicy(
13566                     policyDefinition,
13567                     admin,
13568                     userId);
13569         }
13570     }
13571     private void setGlobalUserRestrictionInternal(
13572             EnforcingAdmin admin, String key, boolean enabled) {
13573         PolicyDefinition<Boolean> policyDefinition =
13574                 PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
13575         if (enabled) {
13576             mDevicePolicyEngine.setGlobalPolicy(
13577                     PolicyDefinition.getPolicyDefinitionForUserRestriction(key),
13578                     admin,
13579                     new BooleanPolicyValue(true));
13580         } else {
13581             mDevicePolicyEngine.removeGlobalPolicy(
13582                     policyDefinition,
13583                     admin);
13584         }
13585     }
13586 
13587     private void logUserRestrictionCall(
13588             String key, boolean enabled, boolean parent, CallerIdentity caller) {
13589         final int eventId = enabled
13590                 ? DevicePolicyEnums.ADD_USER_RESTRICTION
13591                 : DevicePolicyEnums.REMOVE_USER_RESTRICTION;
13592         DevicePolicyEventLogger
13593                 .createEvent(eventId)
13594                 .setAdmin(caller.getComponentName())
13595                 .setStrings(key, parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
13596                 .write();
13597         if (SecurityLog.isLoggingEnabled()) {
13598             final int eventTag = enabled
13599                     ? SecurityLog.TAG_USER_RESTRICTION_ADDED
13600                     : SecurityLog.TAG_USER_RESTRICTION_REMOVED;
13601             SecurityLog.writeEvent(eventTag, caller.getPackageName(), caller.getUserId(), key);
13602         }
13603 
13604         Slogf.i(LOG_TAG, "Changing user restriction %s to: %b caller: %s",
13605                 key, enabled, caller.toString());
13606     }
13607 
13608     private void saveUserRestrictionsLocked(int userId) {
13609         if (isPolicyEngineForFinanceFlagEnabled()) {
13610             // User restrictions are handled in the policy engine
13611             return;
13612         }
13613         saveSettingsLocked(userId);
13614         pushUserRestrictions(userId);
13615         sendChangedNotification(userId);
13616     }
13617 
13618     /**
13619      * Pushes the user restrictions originating from a specific user.
13620      *
13621      * If called by the profile owner of an organization-owned device, the global and local
13622      * user restrictions will be an accumulation of the global user restrictions from the profile
13623      * owner active admin and its parent active admin. The key of the local user restrictions set
13624      * will be the target user id.
13625      */
13626     private void pushUserRestrictions(int originatingUserId) {
13627         if (isPolicyEngineForFinanceFlagEnabled()) {
13628             // User restrictions are handled in the policy engine
13629             return;
13630         }
13631         final Bundle global;
13632         final RestrictionsSet local = new RestrictionsSet();
13633         final boolean isDeviceOwner;
13634         synchronized (getLockObject()) {
13635             isDeviceOwner = mOwners.isDeviceOwnerUserId(originatingUserId);
13636             if (isDeviceOwner) {
13637                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
13638                 if (deviceOwner == null) {
13639                     return; // Shouldn't happen.
13640                 }
13641                 global = deviceOwner.getGlobalUserRestrictions(OWNER_TYPE_DEVICE_OWNER);
13642                 local.updateRestrictions(originatingUserId, deviceOwner.getLocalUserRestrictions(
13643                         OWNER_TYPE_DEVICE_OWNER));
13644             } else {
13645                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(originatingUserId);
13646                 if (profileOwner == null) {
13647                     return;
13648                 }
13649                 global = profileOwner.getGlobalUserRestrictions(OWNER_TYPE_PROFILE_OWNER);
13650                 local.updateRestrictions(originatingUserId, profileOwner.getLocalUserRestrictions(
13651                         OWNER_TYPE_PROFILE_OWNER));
13652                 // Global (device-wide) and local user restrictions set by the profile owner of an
13653                 // organization-owned device are stored in the parent ActiveAdmin instance.
13654                 if (isProfileOwnerOfOrganizationOwnedDevice(
13655                         profileOwner.getUserHandle().getIdentifier())) {
13656                     // The global restrictions set on the parent ActiveAdmin instance need to be
13657                     // merged with the global restrictions set on the profile owner ActiveAdmin
13658                     // instance, since both are to be applied device-wide.
13659                     UserRestrictionsUtils.merge(global,
13660                             profileOwner.getParentActiveAdmin().getGlobalUserRestrictions(
13661                                     OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
13662                     // The local restrictions set on the parent ActiveAdmin instance are only to be
13663                     // applied to the primary user. They therefore need to be added the local
13664                     // restriction set with the primary user id as the key, in this case the
13665                     // primary user id is the target user.
13666                     local.updateRestrictions(
13667                             getProfileParentId(profileOwner.getUserHandle().getIdentifier()),
13668                             profileOwner.getParentActiveAdmin().getLocalUserRestrictions(
13669                                     OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
13670                 }
13671             }
13672         }
13673         mUserManagerInternal.setDevicePolicyUserRestrictions(originatingUserId, global, local,
13674                 isDeviceOwner);
13675     }
13676 
13677     @Override
13678     public Bundle getUserRestrictions(ComponentName who, String callerPackage, boolean parent) {
13679         if (!mHasFeature) {
13680             return null;
13681         }
13682         CallerIdentity caller;
13683         if (isPolicyEngineForFinanceFlagEnabled()) {
13684             caller = getCallerIdentity(who, callerPackage);
13685         } else {
13686             caller = getCallerIdentity(who);
13687         }
13688 
13689         if (isPolicyEngineForFinanceFlagEnabled()) {
13690             int targetUserId = parent
13691                     ? getProfileParentId(caller.getUserId()) : caller.getUserId();
13692             EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
13693             if (isDeviceOwner(caller) || isProfileOwner(caller)) {
13694                 Objects.requireNonNull(who, "ComponentName is null");
13695                 Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
13696                         || isFinancedDeviceOwner(caller)
13697                         || isProfileOwner(caller)
13698                         || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)));
13699 
13700                 Bundle restrictions = getUserRestrictionsFromPolicyEngine(admin, targetUserId);
13701                 // Add global restrictions set by the admin as well.
13702                 restrictions.putAll(
13703                         getUserRestrictionsFromPolicyEngine(admin, UserHandle.USER_ALL));
13704                 return restrictions;
13705             } else {
13706                 if (!mInjector.isChangeEnabled(
13707                         ENABLE_COEXISTENCE_CHANGE, callerPackage, caller.getUserId())) {
13708                     throw new IllegalStateException("Calling package is not targeting Android U.");
13709                 }
13710                 return getUserRestrictionsFromPolicyEngine(admin, targetUserId);
13711             }
13712         } else {
13713             Objects.requireNonNull(who, "ComponentName is null");
13714             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
13715                     || isFinancedDeviceOwner(caller)
13716                     || isProfileOwner(caller)
13717                     || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)));
13718             synchronized (getLockObject()) {
13719                 final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
13720                         getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
13721                 return activeAdmin.userRestrictions;
13722             }
13723         }
13724     }
13725 
13726     // Map of user restriction to permission.
13727     private static final HashMap<String, String[]> USER_RESTRICTION_PERMISSIONS = new HashMap<>();
13728     {
13729         USER_RESTRICTION_PERMISSIONS.put(
13730                 UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, new String[]{MANAGE_DEVICE_POLICY_PROFILES});
13731         USER_RESTRICTION_PERMISSIONS.put(
13732                 UserManager.DISALLOW_ADD_CLONE_PROFILE, new String[]{MANAGE_DEVICE_POLICY_PROFILES});
13733         USER_RESTRICTION_PERMISSIONS.put(
13734                 UserManager.DISALLOW_ADD_USER, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
13735         USER_RESTRICTION_PERMISSIONS.put(
13736                 UserManager.DISALLOW_ADD_WIFI_CONFIG, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13737         USER_RESTRICTION_PERMISSIONS.put(
13738                 UserManager.DISALLOW_ADJUST_VOLUME, new String[]{MANAGE_DEVICE_POLICY_AUDIO_OUTPUT});
13739         USER_RESTRICTION_PERMISSIONS.put(
13740                 UserManager.DISALLOW_AIRPLANE_MODE, new String[]{MANAGE_DEVICE_POLICY_AIRPLANE_MODE});
13741         USER_RESTRICTION_PERMISSIONS.put(
13742                 UserManager.DISALLOW_AMBIENT_DISPLAY, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
13743         USER_RESTRICTION_PERMISSIONS.put(
13744                 UserManager.DISALLOW_APPS_CONTROL, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
13745         USER_RESTRICTION_PERMISSIONS.put(
13746                 UserManager.DISALLOW_AUTOFILL, new String[]{MANAGE_DEVICE_POLICY_AUTOFILL});
13747         USER_RESTRICTION_PERMISSIONS.put(
13748                 UserManager.DISALLOW_BLUETOOTH, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
13749         USER_RESTRICTION_PERMISSIONS.put(
13750                 UserManager.DISALLOW_BLUETOOTH_SHARING, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
13751         USER_RESTRICTION_PERMISSIONS.put(
13752                 UserManager.DISALLOW_CAMERA, new String[]{MANAGE_DEVICE_POLICY_CAMERA});
13753         USER_RESTRICTION_PERMISSIONS.put(
13754                 UserManager.DISALLOW_CAMERA_TOGGLE, new String[]{MANAGE_DEVICE_POLICY_CAMERA_TOGGLE});
13755         USER_RESTRICTION_PERMISSIONS.put(
13756                 UserManager.DISALLOW_CELLULAR_2G, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13757         USER_RESTRICTION_PERMISSIONS.put(
13758                 UserManager.DISALLOW_CHANGE_WIFI_STATE, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13759         USER_RESTRICTION_PERMISSIONS.put(
13760                 UserManager.DISALLOW_CONFIG_BLUETOOTH, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
13761         USER_RESTRICTION_PERMISSIONS.put(
13762                 UserManager.DISALLOW_CONFIG_BRIGHTNESS, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
13763         USER_RESTRICTION_PERMISSIONS.put(
13764                 UserManager.DISALLOW_CONFIG_CELL_BROADCASTS, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13765         USER_RESTRICTION_PERMISSIONS.put(
13766                 UserManager.DISALLOW_CONFIG_CREDENTIALS, new String[]{MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS});
13767         USER_RESTRICTION_PERMISSIONS.put(
13768                 UserManager.DISALLOW_CONFIG_DATE_TIME, new String[]{MANAGE_DEVICE_POLICY_TIME});
13769         USER_RESTRICTION_PERMISSIONS.put(
13770                 UserManager.DISALLOW_CONFIG_DEFAULT_APPS, new String[]{MANAGE_DEFAULT_APPLICATIONS});
13771         USER_RESTRICTION_PERMISSIONS.put(
13772                 UserManager.DISALLOW_CONFIG_LOCALE, new String[]{MANAGE_DEVICE_POLICY_LOCALE});
13773         USER_RESTRICTION_PERMISSIONS.put(
13774                 UserManager.DISALLOW_CONFIG_LOCATION, new String[]{MANAGE_DEVICE_POLICY_LOCATION});
13775         USER_RESTRICTION_PERMISSIONS.put(
13776                 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13777         USER_RESTRICTION_PERMISSIONS.put(
13778                 UserManager.DISALLOW_CONFIG_PRIVATE_DNS, new String[]{MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS});
13779         USER_RESTRICTION_PERMISSIONS.put(
13780                 UserManager.DISALLOW_CONFIG_SCREEN_TIMEOUT, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
13781         USER_RESTRICTION_PERMISSIONS.put(
13782                 UserManager.DISALLOW_CONFIG_TETHERING, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13783         USER_RESTRICTION_PERMISSIONS.put(
13784                 UserManager.DISALLOW_CONFIG_VPN, new String[]{MANAGE_DEVICE_POLICY_VPN});
13785         USER_RESTRICTION_PERMISSIONS.put(
13786                 UserManager.DISALLOW_CONFIG_WIFI, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13787         USER_RESTRICTION_PERMISSIONS.put(
13788                 UserManager.DISALLOW_CONTENT_CAPTURE, new String[]{MANAGE_DEVICE_POLICY_SCREEN_CONTENT});
13789         USER_RESTRICTION_PERMISSIONS.put(
13790                 UserManager.DISALLOW_CONTENT_SUGGESTIONS, new String[]{MANAGE_DEVICE_POLICY_SCREEN_CONTENT});
13791         USER_RESTRICTION_PERMISSIONS.put(
13792                 UserManager.DISALLOW_CREATE_WINDOWS, new String[]{MANAGE_DEVICE_POLICY_WINDOWS});
13793         USER_RESTRICTION_PERMISSIONS.put(
13794                 UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE, new String[]{MANAGE_DEVICE_POLICY_PROFILE_INTERACTION});
13795         USER_RESTRICTION_PERMISSIONS.put(
13796                 UserManager.DISALLOW_DATA_ROAMING, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13797         USER_RESTRICTION_PERMISSIONS.put(
13798                 UserManager.DISALLOW_DEBUGGING_FEATURES, new String[]{MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES});
13799         USER_RESTRICTION_PERMISSIONS.put(
13800                 UserManager.DISALLOW_FACTORY_RESET, new String[]{MANAGE_DEVICE_POLICY_FACTORY_RESET});
13801         USER_RESTRICTION_PERMISSIONS.put(
13802                 UserManager.DISALLOW_FUN, new String[]{MANAGE_DEVICE_POLICY_FUN});
13803         USER_RESTRICTION_PERMISSIONS.put(
13804                 UserManager.DISALLOW_INSTALL_APPS, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
13805         USER_RESTRICTION_PERMISSIONS.put(
13806                 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});
13807         USER_RESTRICTION_PERMISSIONS.put(
13808                 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});
13809         USER_RESTRICTION_PERMISSIONS.put(
13810                 UserManager.DISALLOW_MICROPHONE_TOGGLE, new String[]{MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE});
13811         USER_RESTRICTION_PERMISSIONS.put(
13812                 UserManager.DISALLOW_MODIFY_ACCOUNTS, new String[]{MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT});
13813         USER_RESTRICTION_PERMISSIONS.put(
13814                 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, new String[]{MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA});
13815         USER_RESTRICTION_PERMISSIONS.put(
13816                 UserManager.DISALLOW_NETWORK_RESET, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13817         USER_RESTRICTION_PERMISSIONS.put(
13818                 UserManager.DISALLOW_OUTGOING_BEAM, new String[]{MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION});
13819         USER_RESTRICTION_PERMISSIONS.put(
13820                 UserManager.DISALLOW_OUTGOING_CALLS, new String[]{MANAGE_DEVICE_POLICY_CALLS});
13821         USER_RESTRICTION_PERMISSIONS.put(
13822                 UserManager.DISALLOW_PRINTING, new String[]{MANAGE_DEVICE_POLICY_PRINTING});
13823         USER_RESTRICTION_PERMISSIONS.put(
13824                 UserManager.DISALLOW_REMOVE_USER, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
13825         USER_RESTRICTION_PERMISSIONS.put(
13826                 UserManager.DISALLOW_RUN_IN_BACKGROUND, new String[]{MANAGE_DEVICE_POLICY_RUN_IN_BACKGROUND});
13827         USER_RESTRICTION_PERMISSIONS.put(
13828                 UserManager.DISALLOW_SAFE_BOOT, new String[]{MANAGE_DEVICE_POLICY_SAFE_BOOT});
13829         USER_RESTRICTION_PERMISSIONS.put(
13830                 UserManager.DISALLOW_SET_USER_ICON, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
13831         USER_RESTRICTION_PERMISSIONS.put(
13832                 UserManager.DISALLOW_SET_WALLPAPER, new String[]{MANAGE_DEVICE_POLICY_WALLPAPER});
13833         USER_RESTRICTION_PERMISSIONS.put(
13834                 UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, new String[]{MANAGE_DEVICE_POLICY_PROFILE_INTERACTION});
13835         USER_RESTRICTION_PERMISSIONS.put(
13836                 UserManager.DISALLOW_SHARE_LOCATION, new String[]{MANAGE_DEVICE_POLICY_LOCATION});
13837         USER_RESTRICTION_PERMISSIONS.put(
13838                 UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13839         USER_RESTRICTION_PERMISSIONS.put(
13840                 UserManager.DISALLOW_SMS, new String[]{MANAGE_DEVICE_POLICY_SMS});
13841         USER_RESTRICTION_PERMISSIONS.put(
13842                 UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS, new String[]{MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS});
13843         USER_RESTRICTION_PERMISSIONS.put(
13844                 UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO, new String[]{MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION});
13845         USER_RESTRICTION_PERMISSIONS.put(
13846                 UserManager.DISALLOW_UNIFIED_PASSWORD, new String[]{MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS});
13847         USER_RESTRICTION_PERMISSIONS.put(
13848                 UserManager.DISALLOW_UNINSTALL_APPS, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
13849         USER_RESTRICTION_PERMISSIONS.put(
13850                 UserManager.DISALLOW_UNMUTE_DEVICE, new String[]{MANAGE_DEVICE_POLICY_AUDIO_OUTPUT});
13851         USER_RESTRICTION_PERMISSIONS.put(
13852                 UserManager.DISALLOW_UNMUTE_MICROPHONE, new String[]{MANAGE_DEVICE_POLICY_MICROPHONE});
13853         USER_RESTRICTION_PERMISSIONS.put(
13854                 UserManager.DISALLOW_USB_FILE_TRANSFER, new String[]{MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER});
13855         USER_RESTRICTION_PERMISSIONS.put(
13856                 UserManager.DISALLOW_USER_SWITCH, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
13857         USER_RESTRICTION_PERMISSIONS.put(
13858                 UserManager.DISALLOW_WIFI_DIRECT, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13859         USER_RESTRICTION_PERMISSIONS.put(
13860                 UserManager.DISALLOW_WIFI_TETHERING, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13861         USER_RESTRICTION_PERMISSIONS.put(
13862                 UserManager.ENSURE_VERIFY_APPS, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});
13863 
13864         // Restrictions not allowed to be set by admins.
13865         USER_RESTRICTION_PERMISSIONS.put(
13866                 UserManager.DISALLOW_RECORD_AUDIO, null);
13867         USER_RESTRICTION_PERMISSIONS.put(
13868                 UserManager.DISALLOW_WALLPAPER, null);
13869     }
13870 
enforcePermissionForUserRestriction(ComponentName who, String userRestriction, String callerPackageName, int userId)13871     private EnforcingAdmin enforcePermissionForUserRestriction(ComponentName who,
13872             String userRestriction, String callerPackageName, int userId) {
13873         String[] permissions = USER_RESTRICTION_PERMISSIONS.get(userRestriction);
13874         if (permissions.length > 0) {
13875             try {
13876                 return enforcePermissionsAndGetEnforcingAdmin(who, permissions, callerPackageName,
13877                         userId);
13878             } catch (SecurityException e) {
13879                 throw new SecurityException("Caller does not hold the required permission for this "
13880                         + "user restriction: " + userRestriction + ".\n" + e.getMessage());
13881             }
13882          }
13883         throw new SecurityException("Admins are not permitted to set User Restriction: "
13884                 + userRestriction);
13885     }
13886 
13887     @Override
getUserRestrictionsGlobally(String callerPackage)13888     public Bundle getUserRestrictionsGlobally(String callerPackage) {
13889         if (!mHasFeature) {
13890             return null;
13891         }
13892         final CallerIdentity caller = getCallerIdentity(callerPackage);
13893         if (!isPolicyEngineForFinanceFlagEnabled()) {
13894             throw new IllegalStateException("Feature flag is not enabled.");
13895         }
13896 
13897         EnforcingAdmin admin = getEnforcingAdminForCaller(/*who=*/ null, caller.getPackageName());
13898 
13899         return getUserRestrictionsFromPolicyEngine(admin,
13900                 UserHandle.USER_ALL);
13901     }
13902 
13903     /**
13904      * Returns user restrictions set by the given admin for the provided {@code userId}.
13905      *
13906      * <p>Pass in {@link UserHandle#USER_ALL} for {@code userId} to get global restrictions set by
13907      * the admin
13908      */
getUserRestrictionsFromPolicyEngine(EnforcingAdmin admin, int userId)13909     private Bundle getUserRestrictionsFromPolicyEngine(EnforcingAdmin admin, int userId) {
13910         Set<UserRestrictionPolicyKey> restrictionKeys =
13911                 mDevicePolicyEngine.getUserRestrictionPolicyKeysForAdmin(
13912                         admin,
13913                         userId);
13914         Bundle restrictions = new Bundle();
13915         for (UserRestrictionPolicyKey key : restrictionKeys) {
13916             restrictions.putBoolean(key.getRestriction(), true);
13917         }
13918         return restrictions;
13919     }
13920 
13921     @Override
setApplicationHidden(ComponentName who, String callerPackage, String packageName, boolean hidden, boolean parent)13922     public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
13923             boolean hidden, boolean parent) {
13924         CallerIdentity caller = getCallerIdentity(who, callerPackage);
13925         final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
13926         if (isPolicyEngineForFinanceFlagEnabled()) {
13927             enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
13928         } else {
13929             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13930                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
13931                     || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS)));
13932         }
13933 
13934         List<String> exemptApps = listPolicyExemptAppsUnchecked(mContext);
13935         if (exemptApps.contains(packageName)) {
13936             Slogf.d(LOG_TAG, "setApplicationHidden(): ignoring %s as it's on policy-exempt list",
13937                     packageName);
13938             return false;
13939         }
13940 
13941         boolean result;
13942         synchronized (getLockObject()) {
13943             if (parent) {
13944                 if (!isPolicyEngineForFinanceFlagEnabled()) {
13945                     Preconditions.checkCallAuthorization(
13946                             isProfileOwnerOfOrganizationOwnedDevice(
13947                                     caller.getUserId()) && isManagedProfile(caller.getUserId()));
13948                 }
13949                 // Ensure the package provided is a system package, this is to ensure that this
13950                 // API cannot be used to leak if certain non-system package exists in the person
13951                 // profile.
13952                 mInjector.binderWithCleanCallingIdentity(() ->
13953                         enforcePackageIsSystemPackage(packageName, userId));
13954             }
13955             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_HIDDEN);
13956 
13957             if (VERBOSE_LOG) {
13958                 Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)",
13959                         packageName, hidden, userId);
13960             }
13961             if (isPolicyEngineForFinanceFlagEnabled()) {
13962                 EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
13963                 mDevicePolicyEngine.setLocalPolicy(
13964                         PolicyDefinition.APPLICATION_HIDDEN(packageName),
13965                         admin,
13966                         new BooleanPolicyValue(hidden),
13967                         userId);
13968                 result = mInjector.binderWithCleanCallingIdentity(() -> {
13969                     try {
13970                         // This is a best effort to continue returning the same value that was
13971                         // returned before the policy engine migration.
13972                         return mInjector.getIPackageManager().getPackageInfo(
13973                                 packageName, MATCH_UNINSTALLED_PACKAGES, userId) != null
13974                                 && (mIPackageManager.getApplicationHiddenSettingAsUser(
13975                                         packageName, userId) == hidden);
13976                     } catch (RemoteException e) {
13977                         return false;
13978                     }
13979                 });
13980             } else {
13981                 result = mInjector.binderWithCleanCallingIdentity(() -> mIPackageManager
13982                         .setApplicationHiddenSettingAsUser(packageName, hidden, userId));
13983             }
13984         }
13985         DevicePolicyEventLogger
13986                 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN)
13987                 .setAdmin(caller.getPackageName())
13988                 .setBoolean(/* isDelegate */ isCallerDelegate(caller))
13989                 .setStrings(packageName, hidden ? "hidden" : "not_hidden",
13990                         parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
13991                 .write();
13992         return result;
13993     }
13994 
13995     @Override
isApplicationHidden(ComponentName who, String callerPackage, String packageName, boolean parent)13996     public boolean isApplicationHidden(ComponentName who, String callerPackage,
13997             String packageName, boolean parent) {
13998         CallerIdentity caller = getCallerIdentity(who, callerPackage);
13999         int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
14000         if (isPolicyEngineForFinanceFlagEnabled()) {
14001             // TODO: Also support DELEGATION_PACKAGE_ACCESS
14002             enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
14003         } else {
14004             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
14005                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
14006                     || (caller.hasPackage() && isCallerDelegate(
14007                             caller, DELEGATION_PACKAGE_ACCESS)));
14008         }
14009 
14010         synchronized (getLockObject()) {
14011             if (parent) {
14012                 if (!isPolicyEngineForFinanceFlagEnabled()) {
14013                     Preconditions.checkCallAuthorization(
14014                             isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId())
14015                                     && isManagedProfile(caller.getUserId()));
14016                 }
14017                 // Ensure the package provided is a system package.
14018                 mInjector.binderWithCleanCallingIdentity(() ->
14019                         enforcePackageIsSystemPackage(packageName, userId));
14020             }
14021 
14022             return mInjector.binderWithCleanCallingIdentity(
14023                     () -> mIPackageManager.getApplicationHiddenSettingAsUser(packageName, userId));
14024         }
14025     }
14026 
enforcePackageIsSystemPackage(String packageName, int userId)14027     private void enforcePackageIsSystemPackage(String packageName, int userId)
14028             throws RemoteException {
14029         boolean isSystem;
14030         try {
14031             isSystem = isSystemApp(mIPackageManager, packageName, userId);
14032         } catch (IllegalArgumentException e) {
14033             isSystem = false;
14034         }
14035         if (!isSystem) {
14036             throw new IllegalArgumentException("The provided package is not a system package");
14037         }
14038     }
14039 
14040     @Override
enableSystemApp(ComponentName who, String callerPackage, String packageName)14041     public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
14042         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
14043         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
14044                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
14045                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP)));
14046 
14047         final boolean isDemo = isCurrentUserDemo();
14048         int userId = caller.getUserId();
14049         long id = mInjector.binderClearCallingIdentity();
14050         try {
14051             if (VERBOSE_LOG) {
14052                 Slogf.v(LOG_TAG, "installing " + packageName + " for " + userId);
14053             }
14054 
14055             Preconditions.checkArgument(isDemo || isSystemApp(mIPackageManager, packageName,
14056                     getProfileParentId(userId)), "Only system apps can be enabled this way");
14057 
14058             // Install the app.
14059             mIPackageManager.installExistingPackageAsUser(packageName, userId,
14060                     PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
14061                     PackageManager.INSTALL_REASON_POLICY, null);
14062             if (isDemo) {
14063                 // Ensure the app is also ENABLED for demo users.
14064                 mIPackageManager.setApplicationEnabledSetting(packageName,
14065                         PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
14066                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
14067             }
14068         } catch (RemoteException re) {
14069             // shouldn't happen
14070             Slogf.wtf(LOG_TAG, "Failed to install " + packageName, re);
14071         } finally {
14072             mInjector.binderRestoreCallingIdentity(id);
14073         }
14074         DevicePolicyEventLogger
14075                 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP)
14076                 .setAdmin(caller.getPackageName())
14077                 .setBoolean(/* isDelegate */ who == null)
14078                 .setStrings(packageName)
14079                 .write();
14080     }
14081 
14082     @Override
enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent)14083     public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
14084         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
14085         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
14086                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
14087                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP)));
14088 
14089         int numberOfAppsInstalled = 0;
14090         long id = mInjector.binderClearCallingIdentity();
14091         try {
14092             final int parentUserId = getProfileParentId(caller.getUserId());
14093             List<ResolveInfo> activitiesToEnable = mIPackageManager
14094                     .queryIntentActivities(intent,
14095                             intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14096                             PackageManager.MATCH_DIRECT_BOOT_AWARE
14097                                     | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
14098                             parentUserId)
14099                     .getList();
14100 
14101             if (VERBOSE_LOG) {
14102                 Slogf.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
14103             }
14104             if (activitiesToEnable != null) {
14105                 for (ResolveInfo info : activitiesToEnable) {
14106                     if (info.activityInfo != null) {
14107                         String packageName = info.activityInfo.packageName;
14108                         if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
14109                             numberOfAppsInstalled++;
14110                             mIPackageManager.installExistingPackageAsUser(packageName,
14111                                     caller.getUserId(),
14112                                     PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
14113                                     PackageManager.INSTALL_REASON_POLICY, null);
14114                         } else {
14115                             Slogf.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
14116                                     + " system app");
14117                         }
14118                     }
14119                 }
14120             }
14121         } catch (RemoteException e) {
14122             // shouldn't happen
14123             Slogf.wtf(LOG_TAG, "Failed to resolve intent for: " + intent, e);
14124             return 0;
14125         } finally {
14126             mInjector.binderRestoreCallingIdentity(id);
14127         }
14128         DevicePolicyEventLogger
14129                 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP_WITH_INTENT)
14130                 .setAdmin(caller.getPackageName())
14131                 .setBoolean(/* isDelegate */ who == null)
14132                 .setStrings(intent.getAction())
14133                 .write();
14134         return numberOfAppsInstalled;
14135     }
14136 
isSystemApp(IPackageManager pm, String packageName, int userId)14137     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
14138             throws RemoteException {
14139         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
14140                 userId);
14141         if (appInfo == null) {
14142             throw new IllegalArgumentException("The application " + packageName +
14143                     " is not present on this device");
14144         }
14145         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14146     }
14147 
14148     @Override
installExistingPackage(ComponentName who, String callerPackage, String packageName)14149     public boolean installExistingPackage(ComponentName who, String callerPackage,
14150             String packageName) {
14151         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
14152         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
14153                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
14154                 || (caller.hasPackage()
14155                 && isCallerDelegate(caller, DELEGATION_INSTALL_EXISTING_PACKAGE)));
14156 
14157         boolean result;
14158         synchronized (getLockObject()) {
14159             Preconditions.checkCallAuthorization(
14160                     isUserAffiliatedWithDeviceLocked(caller.getUserId()),
14161                             "Admin %s is neither the device owner or "
14162                                     + "affiliated user's profile owner.", who);
14163             final long id = mInjector.binderClearCallingIdentity();
14164             try {
14165                 if (VERBOSE_LOG) {
14166                     Slogf.v(LOG_TAG, "installing " + packageName + " for " + caller.getUserId());
14167                 }
14168 
14169                 // Install the package.
14170                 result = mIPackageManager.installExistingPackageAsUser(packageName,
14171                         caller.getUserId(),
14172                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
14173                         PackageManager.INSTALL_REASON_POLICY, null)
14174                         == PackageManager.INSTALL_SUCCEEDED;
14175             } catch (RemoteException re) {
14176                 // shouldn't happen
14177                 Slogf.wtf(LOG_TAG, "Error installing package", re);
14178                 return false;
14179             } finally {
14180                 mInjector.binderRestoreCallingIdentity(id);
14181             }
14182         }
14183         if (result) {
14184             DevicePolicyEventLogger
14185                     .createEvent(DevicePolicyEnums.INSTALL_EXISTING_PACKAGE)
14186                     .setAdmin(caller.getPackageName())
14187                     .setBoolean(/* isDelegate */ who == null)
14188                     .setStrings(packageName)
14189                     .write();
14190         }
14191         return result;
14192     }
14193 
14194     @Override
setAccountManagementDisabled(ComponentName who, String callerPackageName, String accountType, boolean disabled, boolean parent)14195     public void setAccountManagementDisabled(ComponentName who, String callerPackageName,
14196             String accountType, boolean disabled, boolean parent) {
14197         if (!mHasFeature) {
14198             return;
14199         }
14200 
14201         enforceMaxStringLength(accountType, "account type");
14202 
14203         CallerIdentity caller;
14204         if (isPolicyEngineForFinanceFlagEnabled()) {
14205             caller = getCallerIdentity(who, callerPackageName);
14206         } else {
14207             caller = getCallerIdentity(who);
14208         }
14209         synchronized (getLockObject()) {
14210             if (isPolicyEngineForFinanceFlagEnabled()) {
14211                 int affectedUser = getAffectedUser(parent);
14212                 EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
14213                         who,
14214                         MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
14215                         caller.getPackageName(),
14216                         affectedUser
14217                 );
14218                 if (disabled) {
14219                     mDevicePolicyEngine.setLocalPolicy(
14220                             PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
14221                             enforcingAdmin,
14222                             new BooleanPolicyValue(disabled),
14223                             affectedUser);
14224                 } else {
14225                     mDevicePolicyEngine.removeLocalPolicy(
14226                             PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
14227                             enforcingAdmin,
14228                             affectedUser);
14229                 }
14230             } else {
14231                 final ActiveAdmin ap;
14232                 Objects.requireNonNull(who, "ComponentName is null");
14233                 /*
14234                  * When called on the parent DPM instance (parent == true), affects active admin
14235                  * selection in two ways:
14236                  * * The ActiveAdmin must be of an org-owned profile owner.
14237                  * * The parent ActiveAdmin instance should be used for managing the restriction.
14238                  */
14239                 if (parent) {
14240                     ap = getParentOfAdminIfRequired(getOrganizationOwnedProfileOwnerLocked(caller),
14241                             parent);
14242                 } else {
14243                     Preconditions.checkCallAuthorization(
14244                             isDefaultDeviceOwner(caller) || isProfileOwner(caller));
14245                     ap = getParentOfAdminIfRequired(
14246                             getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
14247                 }
14248                 if (disabled) {
14249                     ap.accountTypesWithManagementDisabled.add(accountType);
14250                 } else {
14251                     ap.accountTypesWithManagementDisabled.remove(accountType);
14252                 }
14253                 saveSettingsLocked(UserHandle.getCallingUserId());
14254             }
14255         }
14256     }
14257 
14258     @Override
getAccountTypesWithManagementDisabled(String callerPackageName)14259     public String[] getAccountTypesWithManagementDisabled(String callerPackageName) {
14260         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId(),
14261                 callerPackageName, false);
14262     }
14263 
14264     @Override
getAccountTypesWithManagementDisabledAsUser(int userId, String callerPackageName, boolean parent)14265     public String[] getAccountTypesWithManagementDisabledAsUser(int userId,
14266             String callerPackageName, boolean parent) {
14267         if (!mHasFeature) {
14268             return null;
14269         }
14270         CallerIdentity caller;
14271         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14272         final ArraySet<String> resultSet = new ArraySet<>();
14273         if (isPolicyEngineForFinanceFlagEnabled()) {
14274             int affectedUser = parent ? getProfileParentId(userId) : userId;
14275             caller = getCallerIdentity(callerPackageName);
14276             if (!hasPermission(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
14277                     callerPackageName, affectedUser)
14278                     && !hasFullCrossUsersPermission(caller, userId)) {
14279                 throw new SecurityException("Caller does not have permission to call this on user: "
14280                         + affectedUser);
14281             }
14282             Set<PolicyKey> keys = mDevicePolicyEngine.getLocalPolicyKeysSetByAllAdmins(
14283                     PolicyDefinition.GENERIC_ACCOUNT_MANAGEMENT_DISABLED,
14284                     affectedUser);
14285 
14286             for (PolicyKey key : keys) {
14287                 if (!(key instanceof AccountTypePolicyKey)) {
14288                     throw new IllegalStateException("PolicyKey for "
14289                             + "MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT is not of type "
14290                             + "AccountTypePolicyKey");
14291                 }
14292                 AccountTypePolicyKey parsedKey =
14293                         (AccountTypePolicyKey) key;
14294                 String accountType = Objects.requireNonNull(parsedKey.getAccountType());
14295 
14296                 Boolean disabled = mDevicePolicyEngine.getResolvedPolicy(
14297                         PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
14298                         affectedUser);
14299                 if (disabled != null && disabled) {
14300                     resultSet.add(accountType);
14301                 }
14302             }
14303         } else {
14304             caller = getCallerIdentity();
14305             Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
14306 
14307             synchronized (getLockObject()) {
14308                 if (!parent) {
14309                     final DevicePolicyData policy = getUserData(userId);
14310                     for (ActiveAdmin admin : policy.mAdminList) {
14311                         resultSet.addAll(admin.accountTypesWithManagementDisabled);
14312                     }
14313                 }
14314 
14315                 // Check if there's a profile owner of an org-owned device and the method is called
14316                 // for the parent user of this profile owner.
14317                 final ActiveAdmin orgOwnedAdmin =
14318                         getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
14319                 final boolean shouldGetParentAccounts = orgOwnedAdmin != null && (parent
14320                         || UserHandle.getUserId(orgOwnedAdmin.getUid()) != userId);
14321                 if (shouldGetParentAccounts) {
14322                     resultSet.addAll(
14323                             orgOwnedAdmin.getParentActiveAdmin()
14324                                     .accountTypesWithManagementDisabled);
14325                 }
14326             }
14327         }
14328         return resultSet.toArray(new String[resultSet.size()]);
14329     }
14330 
14331     @Override
setUninstallBlocked(ComponentName who, String callerPackage, String packageName, boolean uninstallBlocked)14332     public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
14333             boolean uninstallBlocked) {
14334         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
14335 
14336         if (isPolicyEngineForFinanceFlagEnabled()) {
14337             EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
14338                     who,
14339                     new String[]{
14340                             MANAGE_DEVICE_POLICY_APPS_CONTROL,
14341                             MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL
14342                     },
14343                     caller.getPackageName(),
14344                     caller.getUserId());
14345             mDevicePolicyEngine.setLocalPolicy(
14346                     PolicyDefinition.PACKAGE_UNINSTALL_BLOCKED(packageName),
14347                     enforcingAdmin,
14348                     new BooleanPolicyValue(uninstallBlocked),
14349                     caller.getUserId());
14350         } else {
14351             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
14352                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)
14353                     || isFinancedDeviceOwner(caller)))
14354                     || (caller.hasPackage()
14355                     && isCallerDelegate(caller, DELEGATION_BLOCK_UNINSTALL)));
14356             final int userId = caller.getUserId();
14357             synchronized (getLockObject()) {
14358                 long id = mInjector.binderClearCallingIdentity();
14359                 try {
14360                     mIPackageManager.setBlockUninstallForUser(
14361                             packageName, uninstallBlocked, userId);
14362                 } catch (RemoteException re) {
14363                     // Shouldn't happen.
14364                     Slogf.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
14365                 } finally {
14366                     mInjector.binderRestoreCallingIdentity(id);
14367                 }
14368             }
14369             if (uninstallBlocked) {
14370                 final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
14371                 pmi.removeNonSystemPackageSuspensions(packageName, userId);
14372                 pmi.removeDistractingPackageRestrictions(packageName, userId);
14373                 pmi.flushPackageRestrictions(userId);
14374             }
14375         }
14376 
14377         DevicePolicyEventLogger
14378                 .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED)
14379                 .setAdmin(caller.getPackageName())
14380                 .setBoolean(/* isDelegate */ isCallerDelegate(caller))
14381                 .setStrings(packageName)
14382                 .write();
14383     }
14384 
setUninstallBlockedUnchecked( String packageName, boolean uninstallBlocked, int userId)14385     static void setUninstallBlockedUnchecked(
14386             String packageName, boolean uninstallBlocked, int userId) {
14387         Binder.withCleanCallingIdentity(() -> {
14388             try {
14389                 AppGlobals.getPackageManager().setBlockUninstallForUser(
14390                         packageName, uninstallBlocked, userId);
14391             } catch (RemoteException re) {
14392                 // Shouldn't happen.
14393                 Slogf.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
14394             }
14395         });
14396         if (uninstallBlocked) {
14397             final PackageManagerInternal pmi = LocalServices.getService(
14398                     PackageManagerInternal.class);
14399             pmi.removeNonSystemPackageSuspensions(packageName, userId);
14400             pmi.removeDistractingPackageRestrictions(packageName, userId);
14401             pmi.flushPackageRestrictions(userId);
14402         }
14403     }
14404 
14405     @Override
isUninstallBlocked(String packageName)14406     public boolean isUninstallBlocked(String packageName) {
14407         // This function should return true if and only if the package is blocked by
14408         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
14409         // when the package is a system app, or when it is an active device admin.
14410         final int userId = UserHandle.getCallingUserId();
14411 
14412         synchronized (getLockObject()) {
14413             try {
14414                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
14415             } catch (RemoteException re) {
14416                 // Shouldn't happen.
14417                 Slogf.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
14418             }
14419         }
14420         return false;
14421     }
14422 
14423     @Override
setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled)14424     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
14425         if (!mHasFeature) {
14426             return;
14427         }
14428         Objects.requireNonNull(who, "ComponentName is null");
14429         final CallerIdentity caller = getCallerIdentity(who);
14430         Preconditions.checkCallAuthorization(isProfileOwner(caller));
14431 
14432         synchronized (getLockObject()) {
14433             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14434             if (disabled) {
14435                 admin.mManagedProfileCallerIdAccess =
14436                         new PackagePolicy(PackagePolicy.PACKAGE_POLICY_ALLOWLIST);
14437             } else {
14438                 admin.mManagedProfileCallerIdAccess =
14439                         new PackagePolicy(PackagePolicy.PACKAGE_POLICY_BLOCKLIST);
14440             }
14441             saveSettingsLocked(caller.getUserId());
14442         }
14443         DevicePolicyEventLogger
14444                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALLER_ID_DISABLED)
14445                 .setAdmin(who)
14446                 .setBoolean(disabled)
14447                 .write();
14448     }
14449 
14450     @Override
getCrossProfileCallerIdDisabled(ComponentName who)14451     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
14452         if (!mHasFeature) {
14453             return false;
14454         }
14455         Objects.requireNonNull(who, "ComponentName is null");
14456         final CallerIdentity caller = getCallerIdentity(who);
14457         Preconditions.checkCallAuthorization(isProfileOwner(caller));
14458 
14459         synchronized (getLockObject()) {
14460             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14461             if (admin == null) {
14462                 return false;
14463             }
14464 
14465             if (admin.mManagedProfileCallerIdAccess == null) {
14466                 return admin.disableCallerId;
14467             }
14468 
14469             if (admin.mManagedProfileCallerIdAccess.getPolicyType()
14470                     == PackagePolicy.PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM) {
14471                 Slogf.w(LOG_TAG, "Denying callerId due to PACKAGE_POLICY_SYSTEM policyType");
14472             }
14473 
14474             return admin.mManagedProfileCallerIdAccess.getPolicyType()
14475                     != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
14476         }
14477     }
14478 
14479     @Override
getCrossProfileCallerIdDisabledForUser(int userId)14480     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
14481         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14482 
14483         final CallerIdentity caller = getCallerIdentity();
14484         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14485 
14486         synchronized (getLockObject()) {
14487             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14488             if (admin == null) {
14489                 return false;
14490             }
14491 
14492             if (admin.mManagedProfileCallerIdAccess == null) {
14493                 return admin.disableCallerId;
14494             }
14495 
14496             return admin.mManagedProfileCallerIdAccess.getPolicyType()
14497                     == PackagePolicy.PACKAGE_POLICY_ALLOWLIST;
14498         }
14499     }
14500 
14501     @Override
setManagedProfileCallerIdAccessPolicy(PackagePolicy policy)14502     public void setManagedProfileCallerIdAccessPolicy(PackagePolicy policy) {
14503         if (!mHasFeature) {
14504             return;
14505         }
14506         final CallerIdentity caller = getCallerIdentity();
14507         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14508                 && isManagedProfile(caller.getUserId())));
14509         synchronized (getLockObject()) {
14510             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14511             admin.disableCallerId = false;
14512             admin.mManagedProfileCallerIdAccess = policy;
14513             saveSettingsLocked(caller.getUserId());
14514         }
14515     }
14516 
14517     @Override
getManagedProfileCallerIdAccessPolicy()14518     public PackagePolicy getManagedProfileCallerIdAccessPolicy() {
14519         if (!mHasFeature) {
14520             return null;
14521         }
14522         final CallerIdentity caller = getCallerIdentity();
14523         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14524                 && isManagedProfile(caller.getUserId())));
14525         synchronized (getLockObject()) {
14526             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14527             return (admin != null) ? admin.mManagedProfileCallerIdAccess : null;
14528         }
14529     }
14530 
14531     @Override
hasManagedProfileCallerIdAccess(int userId, String packageName)14532     public boolean hasManagedProfileCallerIdAccess(int userId, String packageName) {
14533         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14534 
14535         final CallerIdentity caller = getCallerIdentity();
14536         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14537 
14538         synchronized (getLockObject()) {
14539             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14540             if (admin != null) {
14541                 if (admin.mManagedProfileCallerIdAccess == null) {
14542                     return !admin.disableCallerId;
14543                 }
14544                 return admin.mManagedProfileCallerIdAccess.isPackageAllowed(packageName,
14545                         mContactSystemRoleHolders);
14546             }
14547         }
14548         return true;
14549     }
14550 
14551     @Override
setManagedProfileContactsAccessPolicy(PackagePolicy policy)14552     public void setManagedProfileContactsAccessPolicy(PackagePolicy policy) {
14553         if (!mHasFeature) {
14554             return;
14555         }
14556         final CallerIdentity caller = getCallerIdentity();
14557         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14558                 && isManagedProfile(caller.getUserId())));
14559 
14560         synchronized (getLockObject()) {
14561             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14562             admin.disableContactsSearch = false;
14563             admin.mManagedProfileContactsAccess = policy;
14564             saveSettingsLocked(caller.getUserId());
14565         }
14566     }
14567 
14568     @Override
getManagedProfileContactsAccessPolicy()14569     public PackagePolicy getManagedProfileContactsAccessPolicy() {
14570         if (!mHasFeature) {
14571             return null;
14572         }
14573 
14574         final CallerIdentity caller = getCallerIdentity();
14575         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14576                 && isManagedProfile(caller.getUserId())));
14577 
14578         synchronized (getLockObject()) {
14579             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14580             return (admin != null) ? admin.mManagedProfileContactsAccess : null;
14581         }
14582     }
14583 
14584     @Override
hasManagedProfileContactsAccess(int userId, String packageName)14585     public boolean hasManagedProfileContactsAccess(int userId, String packageName) {
14586         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14587 
14588         final CallerIdentity caller = getCallerIdentity();
14589         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14590 
14591         synchronized (getLockObject()) {
14592             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14593             if (admin != null) {
14594                 if (admin.mManagedProfileContactsAccess == null) {
14595                     return !admin.disableContactsSearch;
14596                 }
14597 
14598                 return admin.mManagedProfileContactsAccess.isPackageAllowed(packageName,
14599                         mContactSystemRoleHolders);
14600             }
14601         }
14602         return true;
14603     }
14604 
14605     @Override
setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled)14606     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
14607         if (!mHasFeature) {
14608             return;
14609         }
14610         Objects.requireNonNull(who, "ComponentName is null");
14611         final CallerIdentity caller = getCallerIdentity(who);
14612         Preconditions.checkCallAuthorization(isProfileOwner(caller));
14613 
14614         synchronized (getLockObject()) {
14615             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14616             if (disabled) {
14617                 admin.mManagedProfileContactsAccess =
14618                         new PackagePolicy(PackagePolicy.PACKAGE_POLICY_ALLOWLIST);
14619             } else {
14620                 admin.mManagedProfileContactsAccess =
14621                         new PackagePolicy(PackagePolicy.PACKAGE_POLICY_BLOCKLIST);
14622             }
14623             saveSettingsLocked(caller.getUserId());
14624         }
14625         DevicePolicyEventLogger
14626                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED)
14627                 .setAdmin(who)
14628                 .setBoolean(disabled)
14629                 .write();
14630     }
14631 
14632     @Override
getCrossProfileContactsSearchDisabled(ComponentName who)14633     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
14634         if (!mHasFeature) {
14635             return false;
14636         }
14637         Objects.requireNonNull(who, "ComponentName is null");
14638         final CallerIdentity caller = getCallerIdentity(who);
14639         Preconditions.checkCallAuthorization(isProfileOwner(caller));
14640 
14641         synchronized (getLockObject()) {
14642             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14643             if (admin == null) {
14644                 return false;
14645             }
14646             if (admin.mManagedProfileContactsAccess == null) {
14647                 return admin.disableContactsSearch;
14648             }
14649             return admin.mManagedProfileContactsAccess.getPolicyType()
14650                     != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
14651         }
14652     }
14653 
14654     @Override
getCrossProfileContactsSearchDisabledForUser(int userId)14655     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
14656         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14657 
14658         final CallerIdentity caller = getCallerIdentity();
14659         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14660 
14661         synchronized (getLockObject()) {
14662             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14663             if (admin == null) {
14664                 return false;
14665             }
14666 
14667             if (admin.mManagedProfileContactsAccess == null) {
14668                 return admin.disableContactsSearch;
14669             }
14670             if (admin.mManagedProfileContactsAccess.getPolicyType()
14671                     == PackagePolicy.PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM) {
14672                 Slogf.w(LOG_TAG, "Denying contacts due to PACKAGE_POLICY_SYSTEM policyType");
14673             }
14674             return admin.mManagedProfileContactsAccess.getPolicyType()
14675                     != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
14676         }
14677     }
14678 
14679     @Override
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent)14680     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
14681             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
14682         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
14683                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
14684         final int callingUserId = UserHandle.getCallingUserId();
14685 
14686         mInjector.binderWithCleanCallingIdentity(() -> {
14687             synchronized (getLockObject()) {
14688                 final int managedUserId = getManagedUserId(callingUserId);
14689                 if (managedUserId < 0) {
14690                     return;
14691                 }
14692                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
14693                     if (VERBOSE_LOG) {
14694                         Slogf.v(LOG_TAG, "Cross-profile contacts access disabled for user %d",
14695                                 managedUserId);
14696                     }
14697                     return;
14698                 }
14699                 ContactsInternal.startQuickContactWithErrorToastForUser(
14700                         mContext, intent, new UserHandle(managedUserId));
14701             }
14702         });
14703     }
14704 
14705     /**
14706      * @return true if cross-profile QuickContact is disabled
14707      */
isCrossProfileQuickContactDisabled(@serIdInt int userId)14708     private boolean isCrossProfileQuickContactDisabled(@UserIdInt int userId) {
14709         return getCrossProfileCallerIdDisabledForUser(userId)
14710                 && getCrossProfileContactsSearchDisabledForUser(userId);
14711     }
14712 
14713     /**
14714      * @return the user ID of the managed user that is linked to the current user, if any.
14715      * Otherwise UserHandle.USER_NULL (-10000).
14716      */
getManagedUserId(@serIdInt int callingUserId)14717     public int getManagedUserId(@UserIdInt int callingUserId) {
14718         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "getManagedUserId: callingUserId=%d", callingUserId);
14719 
14720         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
14721             if (ui.id == callingUserId || !ui.isManagedProfile()) {
14722                 continue; // Caller user self, or not a managed profile.  Skip.
14723             }
14724             if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Managed user=%d", ui.id);
14725             return ui.id;
14726         }
14727         if (VERBOSE_LOG)  Slogf.v(LOG_TAG, "Managed user not found.");
14728         return UserHandle.USER_NULL;
14729     }
14730 
14731     /**
14732      * Returns the userId of the managed profile on the device.
14733      * If none exists, return {@link UserHandle#USER_NULL}.
14734      *
14735      * We assume there is only one managed profile across all users
14736      * on the device, which is true for now (HSUM or not) but could
14737      * change in future.
14738      */
getManagedUserId()14739     private @UserIdInt int getManagedUserId() {
14740         // On HSUM, there is only one main user and only the main user
14741         // can have a managed profile (for now). On non-HSUM, only user 0
14742         // can host the managed profile and user 0 is the main user.
14743         // So in both cases, we could just get the main user and
14744         // search for the profile user under it.
14745         UserHandle mainUser = mUserManager.getMainUser();
14746         if (mainUser == null) return UserHandle.USER_NULL;
14747         return getManagedUserId(mainUser.getIdentifier());
14748     }
14749 
14750     @Override
setBluetoothContactSharingDisabled(ComponentName who, boolean disabled)14751     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
14752         if (!mHasFeature) {
14753             return;
14754         }
14755         Objects.requireNonNull(who, "ComponentName is null");
14756 
14757         final CallerIdentity caller = getCallerIdentity(who);
14758         Preconditions.checkCallAuthorization(
14759                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
14760 
14761         synchronized (getLockObject()) {
14762             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
14763             if (admin.disableBluetoothContactSharing != disabled) {
14764                 admin.disableBluetoothContactSharing = disabled;
14765                 saveSettingsLocked(caller.getUserId());
14766             }
14767         }
14768         DevicePolicyEventLogger
14769                 .createEvent(DevicePolicyEnums.SET_BLUETOOTH_CONTACT_SHARING_DISABLED)
14770                 .setAdmin(who)
14771                 .setBoolean(disabled)
14772                 .write();
14773     }
14774 
14775     @Override
getBluetoothContactSharingDisabled(ComponentName who)14776     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
14777         if (!mHasFeature) {
14778             return false;
14779         }
14780         Objects.requireNonNull(who, "ComponentName is null");
14781 
14782         final CallerIdentity caller = getCallerIdentity(who);
14783         Preconditions.checkCallAuthorization(
14784                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
14785 
14786         synchronized (getLockObject()) {
14787             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
14788             return admin.disableBluetoothContactSharing;
14789         }
14790     }
14791 
14792     @Override
getBluetoothContactSharingDisabledForUser(int userId)14793     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
14794         // TODO: Should there be a check to make sure this relationship is
14795         // within a profile group?
14796         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
14797         synchronized (getLockObject()) {
14798             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14799             return (admin != null) ? admin.disableBluetoothContactSharing : false;
14800         }
14801     }
14802 
14803     @Override
setSecondaryLockscreenEnabled(ComponentName who, boolean enabled)14804     public void setSecondaryLockscreenEnabled(ComponentName who, boolean enabled) {
14805         Objects.requireNonNull(who, "ComponentName is null");
14806 
14807         // Check can set secondary lockscreen enabled
14808         final CallerIdentity caller = getCallerIdentity(who);
14809         Preconditions.checkCallAuthorization(
14810                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
14811         Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
14812                 "User %d is not allowed to call setSecondaryLockscreenEnabled",
14813                         caller.getUserId());
14814 
14815         synchronized (getLockObject()) {
14816             // Allow testOnly admins to bypass supervision config requirement.
14817             Preconditions.checkCallAuthorization(isAdminTestOnlyLocked(who, caller.getUserId())
14818                     || isSupervisionComponentLocked(caller.getComponentName()), "Admin %s is not "
14819                     + "the default supervision component", caller.getComponentName());
14820             DevicePolicyData policy = getUserData(caller.getUserId());
14821             policy.mSecondaryLockscreenEnabled = enabled;
14822             saveSettingsLocked(caller.getUserId());
14823         }
14824     }
14825 
14826     @Override
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)14827     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
14828         synchronized (getLockObject()) {
14829             return getUserData(userHandle.getIdentifier()).mSecondaryLockscreenEnabled;
14830         }
14831     }
14832 
isManagedProfileOwner(CallerIdentity caller)14833     private boolean isManagedProfileOwner(CallerIdentity caller) {
14834         return isProfileOwner(caller) && isManagedProfile(caller.getUserId());
14835     }
14836 
14837     @Override
setPreferentialNetworkServiceConfigs( List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs)14838     public void setPreferentialNetworkServiceConfigs(
14839             List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
14840         if (!mHasFeature) {
14841             return;
14842         }
14843         final CallerIdentity caller = getCallerIdentity();
14844         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14845                         && isManagedProfile(caller.getUserId()))
14846                         || isDefaultDeviceOwner(caller),
14847                 "Caller is not managed profile owner or device owner;"
14848                         + " only managed profile owner or device owner may control the preferential"
14849                         + " network service");
14850 
14851         try {
14852             updateNetworkPreferenceForUser(caller.getUserId(), preferentialNetworkServiceConfigs);
14853             synchronized (getLockObject()) {
14854                 final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
14855                         caller.getUserId());
14856                 if (!requiredAdmin.mPreferentialNetworkServiceConfigs.equals(
14857                         preferentialNetworkServiceConfigs)) {
14858                     requiredAdmin.mPreferentialNetworkServiceConfigs =
14859                             new ArrayList<>(preferentialNetworkServiceConfigs);
14860                     saveSettingsLocked(caller.getUserId());
14861                 }
14862             }
14863         } catch (Exception e) {
14864             Slogf.e(LOG_TAG, "Failed to set preferential network service configs");
14865             throw e;
14866         }
14867         DevicePolicyEventLogger
14868                 .createEvent(DevicePolicyEnums.SET_PREFERENTIAL_NETWORK_SERVICE_ENABLED)
14869                 .setBoolean(preferentialNetworkServiceConfigs
14870                         .stream().anyMatch(c -> c.isEnabled()))
14871                 .write();
14872     }
14873 
14874     @Override
getPreferentialNetworkServiceConfigs()14875     public List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() {
14876         if (!mHasFeature) {
14877             return List.of(PreferentialNetworkServiceConfig.DEFAULT);
14878         }
14879 
14880         final CallerIdentity caller = getCallerIdentity();
14881         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14882                         && isManagedProfile(caller.getUserId()))
14883                         || isDefaultDeviceOwner(caller),
14884                 "Caller is not managed profile owner or device owner;"
14885                         + " only managed profile owner or device owner may retrieve the "
14886                         + "preferential network service configurations");
14887         synchronized (getLockObject()) {
14888             final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
14889                     caller.getUserId());
14890             return requiredAdmin.mPreferentialNetworkServiceConfigs;
14891         }
14892     }
14893 
14894     @Override
setLockTaskPackages(ComponentName who, String callerPackageName, String[] packages)14895     public void setLockTaskPackages(ComponentName who, String callerPackageName, String[] packages)
14896             throws SecurityException {
14897         Objects.requireNonNull(packages, "packages is null");
14898         for (String pkg : packages) {
14899             enforceMaxPackageNameLength(pkg);
14900         }
14901 
14902         CallerIdentity caller;
14903         if (isPolicyEngineForFinanceFlagEnabled()) {
14904             caller = getCallerIdentity(who, callerPackageName);
14905         } else {
14906             caller = getCallerIdentity(who);
14907         }
14908         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_PACKAGES);
14909 
14910         if (isPolicyEngineForFinanceFlagEnabled()) {
14911             EnforcingAdmin enforcingAdmin;
14912             synchronized (getLockObject()) {
14913                 enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
14914             }
14915             LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
14916                     PolicyDefinition.LOCK_TASK,
14917                     enforcingAdmin,
14918                     caller.getUserId());
14919             LockTaskPolicy policy;
14920             if (currentPolicy == null) {
14921                 policy = new LockTaskPolicy(Set.of(packages));
14922             } else {
14923                 policy = new LockTaskPolicy(currentPolicy);
14924                 policy.setPackages(Set.of(packages));
14925             }
14926             if (policy.getPackages().isEmpty()) {
14927                 mDevicePolicyEngine.removeLocalPolicy(
14928                         PolicyDefinition.LOCK_TASK,
14929                         enforcingAdmin,
14930                         caller.getUserId());
14931             } else {
14932                 mDevicePolicyEngine.setLocalPolicy(
14933                         PolicyDefinition.LOCK_TASK,
14934                         enforcingAdmin,
14935                         policy,
14936                         caller.getUserId());
14937             }
14938         } else {
14939             Objects.requireNonNull(who, "ComponentName is null");
14940             synchronized (getLockObject()) {
14941                 enforceCanCallLockTaskLocked(caller);
14942                 final int userHandle = caller.getUserId();
14943                 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
14944             }
14945         }
14946     }
14947 
setLockTaskPackagesLocked(int userHandle, List<String> packages)14948     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
14949         DevicePolicyData policy = getUserData(userHandle);
14950         policy.mLockTaskPackages = packages;
14951 
14952         // Store the settings persistently.
14953         saveSettingsLocked(userHandle);
14954         updateLockTaskPackagesLocked(mContext, packages, userHandle);
14955     }
14956 
14957     @Override
getLockTaskPackages(ComponentName who, String callerPackageName)14958     public String[] getLockTaskPackages(ComponentName who, String callerPackageName) {
14959         CallerIdentity caller;
14960         if (isPolicyEngineForFinanceFlagEnabled()) {
14961             caller = getCallerIdentity(who, callerPackageName);
14962         } else {
14963             caller = getCallerIdentity(who);
14964         }
14965         final int userHandle = caller.getUserId();
14966 
14967         if (isPolicyEngineForFinanceFlagEnabled()) {
14968             synchronized (getLockObject()) {
14969                 enforceCanQueryLockTaskLocked(who, caller.getPackageName());
14970             }
14971             LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
14972                     PolicyDefinition.LOCK_TASK, userHandle);
14973             if (policy == null) {
14974                 return new String[0];
14975             } else {
14976                 return policy.getPackages().toArray(new String[policy.getPackages().size()]);
14977             }
14978         } else {
14979             Objects.requireNonNull(who, "ComponentName is null");
14980             synchronized (getLockObject()) {
14981                 enforceCanCallLockTaskLocked(caller);
14982                 final List<String> packages = getUserData(userHandle).mLockTaskPackages;
14983                 return packages.toArray(new String[packages.size()]);
14984             }
14985         }
14986     }
14987 
14988     @Override
isLockTaskPermitted(String pkg)14989     public boolean isLockTaskPermitted(String pkg) {
14990         // Check policy-exempt apps first, as it doesn't require the lock
14991         if (listPolicyExemptAppsUnchecked(mContext).contains(pkg)) {
14992             if (VERBOSE_LOG) {
14993                 Slogf.v(LOG_TAG, "isLockTaskPermitted(%s): returning true for policy-exempt app",
14994                             pkg);
14995             }
14996             return true;
14997         }
14998 
14999         final int userId = mInjector.userHandleGetCallingUserId();
15000         if (isPolicyEngineForFinanceFlagEnabled()) {
15001             LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
15002                     PolicyDefinition.LOCK_TASK, userId);
15003             if (policy == null) {
15004                 return false;
15005             }
15006             return policy.getPackages().contains(pkg);
15007         } else {
15008             synchronized (getLockObject()) {
15009                 return getUserData(userId).mLockTaskPackages.contains(pkg);
15010             }
15011         }
15012     }
15013 
15014     @Override
setLockTaskFeatures(ComponentName who, String callerPackageName, int flags)15015     public void setLockTaskFeatures(ComponentName who, String callerPackageName, int flags) {
15016         // Throw if Overview is used without Home.
15017         boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0;
15018         boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0;
15019         Preconditions.checkArgument(hasHome || !hasOverview,
15020                 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME");
15021         boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0;
15022         Preconditions.checkArgument(hasHome || !hasNotification,
15023             "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");
15024 
15025         CallerIdentity caller;
15026         if (isPolicyEngineForFinanceFlagEnabled()) {
15027             caller = getCallerIdentity(who, callerPackageName);
15028         } else {
15029             caller = getCallerIdentity(who);
15030         }
15031         final int userHandle = caller.getUserId();
15032         synchronized (getLockObject()) {
15033             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_FEATURES);
15034         }
15035 
15036         if (isPolicyEngineForFinanceFlagEnabled()) {
15037             EnforcingAdmin enforcingAdmin;
15038             synchronized (getLockObject()) {
15039                 enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
15040                 enforceCanSetLockTaskFeaturesOnFinancedDevice(caller, flags);
15041             }
15042             LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
15043                     PolicyDefinition.LOCK_TASK,
15044                     enforcingAdmin,
15045                     caller.getUserId());
15046             LockTaskPolicy policy;
15047             if (currentPolicy == null) {
15048                 policy = new LockTaskPolicy(flags);
15049             } else {
15050                 policy = new LockTaskPolicy(currentPolicy);
15051                 policy.setFlags(flags);
15052             }
15053             if (policy.getPackages().isEmpty()
15054                     && policy.getFlags() == DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
15055                 mDevicePolicyEngine.removeLocalPolicy(
15056                         PolicyDefinition.LOCK_TASK,
15057                         enforcingAdmin,
15058                         caller.getUserId());
15059             } else {
15060                 mDevicePolicyEngine.setLocalPolicy(
15061                         PolicyDefinition.LOCK_TASK,
15062                         enforcingAdmin,
15063                         policy,
15064                         caller.getUserId());
15065             }
15066         } else {
15067             Objects.requireNonNull(who, "ComponentName is null");
15068             synchronized (getLockObject()) {
15069                 enforceCanCallLockTaskLocked(caller);
15070                 enforceCanSetLockTaskFeaturesOnFinancedDevice(caller, flags);
15071                 setLockTaskFeaturesLocked(userHandle, flags);
15072             }
15073         }
15074     }
15075 
setLockTaskFeaturesLocked(int userHandle, int flags)15076     private void setLockTaskFeaturesLocked(int userHandle, int flags) {
15077         DevicePolicyData policy = getUserData(userHandle);
15078         policy.mLockTaskFeatures = flags;
15079         saveSettingsLocked(userHandle);
15080         updateLockTaskFeaturesLocked(flags, userHandle);
15081     }
15082 
15083     @Override
getLockTaskFeatures(ComponentName who, String callerPackageName)15084     public int getLockTaskFeatures(ComponentName who, String callerPackageName) {
15085         CallerIdentity caller;
15086         if (isPolicyEngineForFinanceFlagEnabled()) {
15087             caller = getCallerIdentity(who, callerPackageName);
15088         } else {
15089             caller = getCallerIdentity(who);
15090         }
15091         final int userHandle = caller.getUserId();
15092 
15093         if (isPolicyEngineForFinanceFlagEnabled()) {
15094             synchronized (getLockObject()) {
15095                 enforceCanQueryLockTaskLocked(who, caller.getPackageName());
15096             }
15097             LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
15098                     PolicyDefinition.LOCK_TASK, userHandle);
15099             if (policy == null) {
15100                 // We default on the power button menu, in order to be consistent with pre-P
15101                 // behaviour.
15102                 return DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
15103             }
15104             return policy.getFlags();
15105         } else {
15106             Objects.requireNonNull(who, "ComponentName is null");
15107             synchronized (getLockObject()) {
15108                 enforceCanCallLockTaskLocked(caller);
15109                 return getUserData(userHandle).mLockTaskFeatures;
15110             }
15111         }
15112     }
15113 
maybeClearLockTaskPolicyLocked()15114     private void maybeClearLockTaskPolicyLocked() {
15115         mInjector.binderWithCleanCallingIdentity(() -> {
15116             final List<UserInfo> userInfos = mUserManager.getAliveUsers();
15117             for (int i = userInfos.size() - 1; i >= 0; i--) {
15118                 int userId = userInfos.get(i).id;
15119                 if (canDPCManagedUserUseLockTaskLocked(userId)) {
15120                     continue;
15121                 }
15122 
15123                 if (isPolicyEngineForFinanceFlagEnabled()) {
15124                     Map<EnforcingAdmin, PolicyValue<LockTaskPolicy>> policies =
15125                             mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
15126                                     PolicyDefinition.LOCK_TASK, userId);
15127                     Set<EnforcingAdmin> admins = new HashSet<>(policies.keySet());
15128                     for (EnforcingAdmin admin : admins) {
15129                         if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
15130                             mDevicePolicyEngine.removeLocalPolicy(
15131                                     PolicyDefinition.LOCK_TASK, admin, userId);
15132                         }
15133                     }
15134                 } else {
15135                     final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
15136                     // TODO(b/278438525): handle in the policy engine
15137                     if (!lockTaskPackages.isEmpty()) {
15138                         Slogf.d(LOG_TAG,
15139                                 "User id " + userId
15140                                         + " not affiliated. Clearing lock task packages");
15141                         setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
15142                     }
15143                     final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
15144                     if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
15145                         Slogf.d(LOG_TAG,
15146                                 "User id " + userId
15147                                         + " not affiliated. Clearing lock task features");
15148                         setLockTaskFeaturesLocked(userId,
15149                                 DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
15150                     }
15151                 }
15152             }
15153         });
15154     }
15155 
enforceCanSetLockTaskFeaturesOnFinancedDevice(CallerIdentity caller, int flags)15156     private void enforceCanSetLockTaskFeaturesOnFinancedDevice(CallerIdentity caller, int flags) {
15157         int allowedFlags = LOCK_TASK_FEATURE_SYSTEM_INFO | LOCK_TASK_FEATURE_KEYGUARD
15158                 | LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_GLOBAL_ACTIONS
15159                 | LOCK_TASK_FEATURE_NOTIFICATIONS | LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK;
15160 
15161         if (!isFinancedDeviceOwner(caller)) {
15162             return;
15163         }
15164 
15165         if ((flags & ~(allowedFlags)) != 0) {
15166             throw new SecurityException(
15167                     "Permitted lock task features when managing a financed device: "
15168                             + "LOCK_TASK_FEATURE_SYSTEM_INFO, LOCK_TASK_FEATURE_KEYGUARD, "
15169                             + "LOCK_TASK_FEATURE_HOME, LOCK_TASK_FEATURE_GLOBAL_ACTIONS, "
15170                             + "LOCK_TASK_FEATURE_NOTIFICATIONS"
15171                             + " or LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK");
15172         }
15173     }
15174 
15175     @Override
notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle)15176     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
15177         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
15178                 String.format(NOT_SYSTEM_CALLER_MSG, "call notifyLockTaskModeChanged"));
15179         synchronized (getLockObject()) {
15180             final DevicePolicyData policy = getUserData(userHandle);
15181 
15182             if (policy.mStatusBarDisabled) {
15183                 // Status bar is managed by LockTaskController during LockTask, so we cancel this
15184                 // policy when LockTask starts, and reapply it when LockTask ends
15185                 setStatusBarDisabledInternal(!isEnabled, userHandle);
15186             }
15187 
15188             Bundle adminExtras = new Bundle();
15189             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
15190             for (ActiveAdmin admin : policy.mAdminList) {
15191                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
15192                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
15193                 // TODO(b/281738975): Should we be logging this for all admins?
15194                 if (ownsDevice || ownsProfile) {
15195                     if (isEnabled) {
15196                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
15197                                 adminExtras, null);
15198                     } else {
15199                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
15200                     }
15201                     DevicePolicyEventLogger
15202                             .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED)
15203                             .setAdmin(admin.info == null ? null : admin.info.getPackageName())
15204                             .setBoolean(isEnabled)
15205                             .setStrings(pkg)
15206                             .write();
15207                 }
15208             }
15209         }
15210         // TODO(b/281738975): Should we be logging this for all admins?
15211         for(EnforcingAdmin admin : mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
15212                 PolicyDefinition.LOCK_TASK, userHandle).keySet()) {
15213             if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
15214                 // already handled above
15215                 continue;
15216             }
15217             DevicePolicyEventLogger
15218                     .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED)
15219                     .setAdmin(admin.getPackageName())
15220                     .setBoolean(isEnabled)
15221                     .setStrings(pkg)
15222                     .write();
15223         }
15224     }
15225 
15226     @Override
setGlobalSetting(ComponentName who, String setting, String value)15227     public void setGlobalSetting(ComponentName who, String setting, String value) {
15228         final CallerIdentity caller = getCallerIdentity(who);
15229         if (Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS.equals(setting)) {
15230             Preconditions.checkCallAuthorization(isCallerDevicePolicyManagementRoleHolder(caller));
15231             mInjector.binderWithCleanCallingIdentity(
15232                     () -> mInjector.settingsGlobalPutString(setting, value));
15233             return;
15234         }
15235         Objects.requireNonNull(who, "ComponentName is null");
15236         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
15237 
15238         DevicePolicyEventLogger
15239                 .createEvent(DevicePolicyEnums.SET_GLOBAL_SETTING)
15240                 .setAdmin(who)
15241                 .setStrings(setting, value)
15242                 .write();
15243 
15244         synchronized (getLockObject()) {
15245             // Some settings are no supported any more. However we do not want to throw a
15246             // SecurityException to avoid breaking apps.
15247             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
15248                 Slogf.i(LOG_TAG, "Global setting no longer supported: %s", setting);
15249                 return;
15250             }
15251 
15252             if (!GLOBAL_SETTINGS_ALLOWLIST.contains(setting)
15253                     && !UserManager.isDeviceInDemoMode(mContext)) {
15254                 throw new SecurityException(String.format(
15255                         "Permission denial: device owners cannot update %1$s", setting));
15256             }
15257 
15258             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
15259                 // ignore if it contradicts an existing policy
15260                 long timeMs = getMaximumTimeToLock(
15261                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
15262                 if (timeMs > 0 && timeMs < Long.MAX_VALUE) {
15263                     return;
15264                 }
15265             }
15266 
15267             mInjector.binderWithCleanCallingIdentity(
15268                     () -> mInjector.settingsGlobalPutString(setting, value));
15269         }
15270     }
15271 
15272     @Override
setSystemSetting(ComponentName who, String setting, String value)15273     public void setSystemSetting(ComponentName who, String setting, String value) {
15274         Objects.requireNonNull(who, "ComponentName is null");
15275         Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
15276         final CallerIdentity caller = getCallerIdentity(who);
15277         Preconditions.checkCallAuthorization(
15278                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15279         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_SETTING);
15280 
15281         synchronized (getLockObject()) {
15282             if (!SYSTEM_SETTINGS_ALLOWLIST.contains(setting)) {
15283                 throw new SecurityException(String.format(
15284                         "Permission denial: device owners cannot update %1$s", setting));
15285             }
15286 
15287             mInjector.binderWithCleanCallingIdentity(() ->
15288                     mInjector.settingsSystemPutStringForUser(setting, value, caller.getUserId()));
15289         }
15290     }
15291 
15292     @Override
setConfiguredNetworksLockdownState( ComponentName who, String callerPackageName, boolean lockdown)15293     public void setConfiguredNetworksLockdownState(
15294             ComponentName who, String callerPackageName, boolean lockdown) {
15295         if (!mHasFeature) {
15296             return;
15297         }
15298         CallerIdentity caller;
15299 
15300         if (isPermissionCheckFlagEnabled()) {
15301             caller = getCallerIdentity(who, callerPackageName);
15302             enforcePermission(MANAGE_DEVICE_POLICY_WIFI, caller.getPackageName(),
15303                     UserHandle.USER_ALL);
15304         } else {
15305             caller = getCallerIdentity(who);
15306             Preconditions.checkNotNull(who, "ComponentName is null");
15307             Preconditions.checkCallAuthorization(
15308                     isDefaultDeviceOwner(caller)
15309                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
15310         }
15311 
15312         mInjector.binderWithCleanCallingIdentity(() ->
15313                 mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN,
15314                         lockdown ? 1 : 0));
15315 
15316         DevicePolicyEventLogger
15317                 .createEvent(DevicePolicyEnums.ALLOW_MODIFICATION_OF_ADMIN_CONFIGURED_NETWORKS)
15318                 .setAdmin(caller.getPackageName())
15319                 .setBoolean(lockdown)
15320                 .write();
15321     }
15322 
15323     @Override
hasLockdownAdminConfiguredNetworks(ComponentName who)15324     public boolean hasLockdownAdminConfiguredNetworks(ComponentName who) {
15325         if (!mHasFeature) {
15326             return false;
15327         }
15328         CallerIdentity caller = getCallerIdentity(who);
15329         if (isPermissionCheckFlagEnabled()) {
15330             enforcePermission(MANAGE_DEVICE_POLICY_WIFI, who.getPackageName(),
15331                     UserHandle.USER_ALL);
15332         } else {
15333             Preconditions.checkNotNull(who, "ComponentName is null");
15334 
15335             Preconditions.checkCallAuthorization(
15336                     isDefaultDeviceOwner(caller)
15337                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
15338         }
15339 
15340         return mInjector.binderWithCleanCallingIdentity(() ->
15341                 mInjector.settingsGlobalGetInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) > 0);
15342     }
15343 
15344     @Override
setLocationEnabled(ComponentName who, boolean locationEnabled)15345     public void setLocationEnabled(ComponentName who, boolean locationEnabled) {
15346         Preconditions.checkNotNull(who, "ComponentName is null");
15347 
15348         final CallerIdentity caller = getCallerIdentity(who);
15349         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
15350 
15351         UserHandle userHandle = caller.getUserHandle();
15352         if (mIsAutomotive && !locationEnabled) {
15353             Slogf.i(LOG_TAG, "setLocationEnabled(%s, %b): ignoring for user %s on automotive build",
15354                     who.flattenToShortString(), locationEnabled, userHandle);
15355             return;
15356         }
15357 
15358         mInjector.binderWithCleanCallingIdentity(() -> {
15359             boolean wasLocationEnabled = mInjector.getLocationManager().isLocationEnabledForUser(
15360                     userHandle);
15361             Slogf.v(LOG_TAG, "calling locationMgr.setLocationEnabledForUser(%b, %s) when it was %b",
15362                     locationEnabled, userHandle, wasLocationEnabled);
15363             mInjector.getLocationManager().setLocationEnabledForUser(locationEnabled, userHandle);
15364 
15365             // make a best effort to only show the notification if the admin is actually enabling
15366             // location. this is subject to race conditions with settings changes, but those are
15367             // unlikely to realistically interfere
15368             if (locationEnabled && !wasLocationEnabled) {
15369                 showLocationSettingsEnabledNotification(userHandle);
15370             }
15371         });
15372 
15373         DevicePolicyEventLogger
15374                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
15375                 .setAdmin(who)
15376                 .setStrings(Settings.Secure.LOCATION_MODE, Integer.toString(
15377                         locationEnabled ? Settings.Secure.LOCATION_MODE_ON
15378                                 : Settings.Secure.LOCATION_MODE_OFF))
15379                 .write();
15380     }
15381 
showLocationSettingsEnabledNotification(UserHandle user)15382     private void showLocationSettingsEnabledNotification(UserHandle user) {
15383         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
15384                 .addFlags(FLAG_ACTIVITY_NEW_TASK);
15385         // Fill the component explicitly to prevent the PendingIntent from being intercepted
15386         // and fired with crafted target. b/155183624
15387         ActivityInfo targetInfo = intent.resolveActivityInfo(
15388                 mInjector.getPackageManager(user.getIdentifier()),
15389                 PackageManager.MATCH_SYSTEM_ONLY);
15390         if (targetInfo != null) {
15391             intent.setComponent(targetInfo.getComponentName());
15392         } else {
15393             Slogf.wtf(LOG_TAG, "Failed to resolve intent for location settings");
15394         }
15395 
15396         // Simple notification clicks are immutable
15397         PendingIntent locationSettingsIntent = mInjector.pendingIntentGetActivityAsUser(mContext, 0,
15398                 intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE, null,
15399                 user);
15400         Notification notification = new Notification.Builder(mContext,
15401                 SystemNotificationChannels.DEVICE_ADMIN)
15402                 .setSmallIcon(R.drawable.ic_info_outline)
15403                 .setContentTitle(getLocationChangedTitle())
15404                 .setContentText(getLocationChangedText())
15405                 .setColor(mContext.getColor(R.color.system_notification_accent_color))
15406                 .setShowWhen(true)
15407                 .setContentIntent(locationSettingsIntent)
15408                 .setAutoCancel(true)
15409                 .build();
15410         mHandler.post(() -> mInjector.getNotificationManager().notify(
15411                 SystemMessage.NOTE_LOCATION_CHANGED, notification));
15412     }
15413 
getLocationChangedTitle()15414     private String getLocationChangedTitle() {
15415         return getUpdatableString(
15416                 LOCATION_CHANGED_TITLE, R.string.location_changed_notification_title);
15417     }
15418 
getLocationChangedText()15419     private String getLocationChangedText() {
15420         return getUpdatableString(
15421                 LOCATION_CHANGED_MESSAGE, R.string.location_changed_notification_text);
15422     }
15423 
15424     @Override
setTime(@ullable ComponentName who, String callerPackageName, long millis)15425     public boolean setTime(@Nullable ComponentName who, String callerPackageName, long millis) {
15426         CallerIdentity caller;
15427         if (isPermissionCheckFlagEnabled()) {
15428             caller = getCallerIdentity(who, callerPackageName);
15429             // This is a global action.
15430             enforcePermission(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
15431         } else {
15432             caller = getCallerIdentity(who);
15433             Objects.requireNonNull(who, "ComponentName is null");
15434             Preconditions.checkCallAuthorization(
15435                     isDefaultDeviceOwner(caller)
15436                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
15437         }
15438 
15439         // Don't allow set time when auto time is on.
15440         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
15441             return false;
15442         }
15443         DevicePolicyEventLogger
15444                 .createEvent(DevicePolicyEnums.SET_TIME)
15445                 .setAdmin(caller.getPackageName())
15446                 .write();
15447         mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
15448         return true;
15449     }
15450 
15451     @Override
setTimeZone(@ullable ComponentName who, String callerPackageName, String timeZone)15452     public boolean setTimeZone(@Nullable ComponentName who, String callerPackageName,
15453             String timeZone) {
15454         CallerIdentity caller;
15455         if (isPermissionCheckFlagEnabled()) {
15456             caller = getCallerIdentity(who, callerPackageName);
15457             // This is a global action.
15458             enforcePermission(SET_TIME_ZONE, caller.getPackageName(), UserHandle.USER_ALL);
15459         } else {
15460             caller = getCallerIdentity(who);
15461             Objects.requireNonNull(who, "ComponentName is null");
15462             Preconditions.checkCallAuthorization(
15463                     isDefaultDeviceOwner(caller)
15464                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
15465         }
15466 
15467         // Don't allow set timezone when auto timezone is on.
15468         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
15469             return false;
15470         }
15471         String logInfo = "DevicePolicyManager.setTimeZone()";
15472         mInjector.binderWithCleanCallingIdentity(() ->
15473                 mInjector.getAlarmManagerInternal()
15474                         .setTimeZone(timeZone, TIME_ZONE_CONFIDENCE_HIGH, logInfo));
15475 
15476         DevicePolicyEventLogger
15477                 .createEvent(DevicePolicyEnums.SET_TIME_ZONE)
15478                 .setAdmin(caller.getPackageName())
15479                 .write();
15480         return true;
15481     }
15482 
15483     @Override
setSecureSetting(ComponentName who, String setting, String value)15484     public void setSecureSetting(ComponentName who, String setting, String value) {
15485         Objects.requireNonNull(who, "ComponentName is null");
15486         final CallerIdentity caller = getCallerIdentity(who);
15487         Preconditions.checkCallAuthorization(
15488                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15489 
15490         int callingUserId = caller.getUserId();
15491         synchronized (getLockObject()) {
15492             if (isDeviceOwner(who, callingUserId)) {
15493                 if (!SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.contains(setting)
15494                         && !isCurrentUserDemo()) {
15495                     throw new SecurityException(String.format(
15496                             "Permission denial: Device owners cannot update %1$s", setting));
15497                 }
15498             } else if (!SECURE_SETTINGS_ALLOWLIST.contains(setting) && !isCurrentUserDemo()) {
15499                 throw new SecurityException(String.format(
15500                         "Permission denial: Profile owners cannot update %1$s", setting));
15501             }
15502             if (setting.equals(Settings.Secure.LOCATION_MODE)
15503                     && isSetSecureSettingLocationModeCheckEnabled(who.getPackageName(),
15504                     callingUserId)) {
15505                 throw new UnsupportedOperationException(Settings.Secure.LOCATION_MODE + " is "
15506                         + "deprecated. Please use setLocationEnabled() instead.");
15507             }
15508             if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
15509                 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
15510                     throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
15511                             + " is deprecated. Please use one of the user restrictions "
15512                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
15513                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY + " instead.");
15514                 }
15515                 if (!mUserManager.isManagedProfile(callingUserId)) {
15516                     Slogf.e(LOG_TAG, "Ignoring setSecureSetting request for "
15517                             + setting + ". User restriction "
15518                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
15519                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY
15520                             + " should be used instead.");
15521                 } else {
15522                     try {
15523                         setUserRestriction(who, who.getPackageName(),
15524                                 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
15525                                 (Integer.parseInt(value) == 0) ? true : false, /* parent */ false);
15526                         DevicePolicyEventLogger
15527                                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
15528                                 .setAdmin(who)
15529                                 .setStrings(setting, value)
15530                                 .write();
15531                     } catch (NumberFormatException exc) {
15532                         Slogf.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
15533                     }
15534                 }
15535                 return;
15536             }
15537             mInjector.binderWithCleanCallingIdentity(() -> {
15538                 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
15539                     final String currentValue = mInjector.settingsSecureGetStringForUser(
15540                             Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
15541                     if (!TextUtils.equals(currentValue, value)) {
15542                         // Tell the content observer that the next change will be due to the owner
15543                         // changing the value. There is a small race condition here that we cannot
15544                         // avoid: Change notifications are sent asynchronously, so it is possible
15545                         // that there are prior notifications queued up before the one we are about
15546                         // to trigger. This is a corner case that will have no impact in practice.
15547                         mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
15548                     }
15549                     getUserData(callingUserId).mCurrentInputMethodSet = true;
15550                     saveSettingsLocked(callingUserId);
15551                 }
15552                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
15553                 // Notify the user if it's the location mode setting that's been set, to any value
15554                 // other than 'off'.
15555                 if (setting.equals(Settings.Secure.LOCATION_MODE)
15556                         && (Integer.parseInt(value) != 0)) {
15557                     showLocationSettingsEnabledNotification(UserHandle.of(callingUserId));
15558                 }
15559             });
15560         }
15561         DevicePolicyEventLogger
15562                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
15563                 .setAdmin(who)
15564                 .setStrings(setting, value)
15565                 .write();
15566     }
15567 
isSetSecureSettingLocationModeCheckEnabled(String packageName, int userId)15568     private boolean isSetSecureSettingLocationModeCheckEnabled(String packageName, int userId) {
15569         return mInjector.isChangeEnabled(USE_SET_LOCATION_ENABLED, packageName, userId);
15570     }
15571 
15572     @Override
setMasterVolumeMuted(ComponentName who, boolean on)15573     public void setMasterVolumeMuted(ComponentName who, boolean on) {
15574         Objects.requireNonNull(who, "ComponentName is null");
15575         final CallerIdentity caller = getCallerIdentity(who);
15576         Preconditions.checkCallAuthorization(
15577                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15578         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_MASTER_VOLUME_MUTED);
15579 
15580         synchronized (getLockObject()) {
15581             setUserRestriction(who, who.getPackageName(), UserManager.DISALLOW_UNMUTE_DEVICE, on,
15582                     /* parent */ false);
15583             DevicePolicyEventLogger
15584                     .createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED)
15585                     .setAdmin(who)
15586                     .setBoolean(on)
15587                     .write();
15588         }
15589     }
15590 
15591     @Override
isMasterVolumeMuted(ComponentName who)15592     public boolean isMasterVolumeMuted(ComponentName who) {
15593         Objects.requireNonNull(who, "ComponentName is null");
15594         final CallerIdentity caller = getCallerIdentity(who);
15595         Preconditions.checkCallAuthorization(
15596                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15597 
15598         synchronized (getLockObject()) {
15599             AudioManager audioManager =
15600                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
15601             return audioManager.isMasterMute();
15602         }
15603     }
15604 
15605     @Override
setUserIcon(ComponentName who, Bitmap icon)15606     public void setUserIcon(ComponentName who, Bitmap icon) {
15607         Objects.requireNonNull(who, "ComponentName is null");
15608         final CallerIdentity caller = getCallerIdentity(who);
15609         Preconditions.checkCallAuthorization(
15610                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15611 
15612         synchronized (getLockObject()) {
15613             mInjector.binderWithCleanCallingIdentity(
15614                     () -> mUserManagerInternal.setUserIcon(caller.getUserId(), icon));
15615         }
15616         DevicePolicyEventLogger
15617                 .createEvent(DevicePolicyEnums.SET_USER_ICON)
15618                 .setAdmin(who)
15619                 .write();
15620     }
15621 
15622     @Override
setKeyguardDisabled(ComponentName who, boolean disabled)15623     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
15624         Objects.requireNonNull(who, "ComponentName is null");
15625         final CallerIdentity caller = getCallerIdentity(who);
15626         Preconditions.checkCallAuthorization(
15627                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15628 
15629         final int userId = caller.getUserId();
15630         synchronized (getLockObject()) {
15631             Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
15632                     String.format(
15633                             "Admin %s is neither the device owner or affiliated user's profile "
15634                                     + "owner.", who));
15635         }
15636         if (isManagedProfile(userId)) {
15637             throw new SecurityException("Managed profile cannot disable keyguard");
15638         }
15639         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEYGUARD_DISABLED);
15640 
15641         long ident = mInjector.binderClearCallingIdentity();
15642         try {
15643             // disallow disabling the keyguard if a password is currently set
15644             if (disabled && mLockPatternUtils.isSecure(userId)) {
15645                 return false;
15646             }
15647             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
15648             if (disabled) {
15649                 mInjector
15650                         .getIWindowManager()
15651                         .dismissKeyguard(null /* callback */, null /* message */);
15652             }
15653             DevicePolicyEventLogger
15654                     .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED)
15655                     .setAdmin(who)
15656                     .setBoolean(disabled)
15657                     .write();
15658         } catch (RemoteException e) {
15659             // Same process, does not happen.
15660         } finally {
15661             mInjector.binderRestoreCallingIdentity(ident);
15662         }
15663         return true;
15664     }
15665 
15666     @Override
setStatusBarDisabled(ComponentName who, String callerPackageName, boolean disabled)15667     public boolean setStatusBarDisabled(ComponentName who, String callerPackageName,
15668             boolean disabled) {
15669         CallerIdentity caller;
15670         if (isUnicornFlagEnabled()) {
15671             caller = getCallerIdentity(who, callerPackageName);
15672         } else {
15673             caller = getCallerIdentity(who);
15674         }
15675         if (isUnicornFlagEnabled()) {
15676             enforcePermission(MANAGE_DEVICE_POLICY_STATUS_BAR, caller.getPackageName(),
15677                     UserHandle.USER_ALL);
15678         } else {
15679             Objects.requireNonNull(who, "ComponentName is null");
15680             Preconditions.checkCallAuthorization(
15681                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15682         }
15683 
15684         int userId = caller.getUserId();
15685         synchronized (getLockObject()) {
15686             if (!isUnicornFlagEnabled()) {
15687                 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
15688                         "Admin " + who + " is neither the device owner or affiliated "
15689                                 + "user's profile owner.");
15690                 if (isManagedProfile(userId)) {
15691                     throw new SecurityException("Managed profile cannot disable status bar");
15692                 }
15693             }
15694             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_STATUS_BAR_DISABLED);
15695 
15696             DevicePolicyData policy = getUserData(userId);
15697             if (policy.mStatusBarDisabled != disabled) {
15698                 boolean isLockTaskMode = false;
15699                 try {
15700                     isLockTaskMode = mInjector.getIActivityTaskManager().getLockTaskModeState()
15701                             != LOCK_TASK_MODE_NONE;
15702                 } catch (RemoteException e) {
15703                     Slogf.e(LOG_TAG, "Failed to get LockTask mode");
15704                 }
15705                 if (!isLockTaskMode) {
15706                     if (!setStatusBarDisabledInternal(disabled, userId)) {
15707                         return false;
15708                     }
15709                 }
15710                 policy.mStatusBarDisabled = disabled;
15711                 saveSettingsLocked(userId);
15712             }
15713         }
15714         DevicePolicyEventLogger
15715                 .createEvent(DevicePolicyEnums.SET_STATUS_BAR_DISABLED)
15716                 .setAdmin(caller.getPackageName())
15717                 .setBoolean(disabled)
15718                 .write();
15719         return true;
15720     }
15721 
setStatusBarDisabledInternal(boolean disabled, int userId)15722     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
15723         long ident = mInjector.binderClearCallingIdentity();
15724         try {
15725             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
15726                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
15727             if (statusBarService != null) {
15728                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
15729                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
15730                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
15731                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
15732                 return true;
15733             }
15734         } catch (RemoteException e) {
15735             Slogf.e(LOG_TAG, "Failed to disable the status bar", e);
15736         } finally {
15737             mInjector.binderRestoreCallingIdentity(ident);
15738         }
15739         return false;
15740     }
15741 
15742     @Override
isStatusBarDisabled(String callerPackage)15743     public boolean isStatusBarDisabled(String callerPackage) {
15744         final CallerIdentity caller = getCallerIdentity(callerPackage);
15745         if (isUnicornFlagEnabled()) {
15746             enforceCanQuery(
15747                     MANAGE_DEVICE_POLICY_STATUS_BAR, caller.getPackageName(), caller.getUserId());
15748         } else {
15749             Preconditions.checkCallAuthorization(
15750                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15751         }
15752 
15753         int userId = caller.getUserId();
15754         synchronized (getLockObject()) {
15755             if (!isUnicornFlagEnabled()) {
15756                 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
15757                         "Admin " + callerPackage
15758                                 + " is neither the device owner or affiliated user's profile owner.");
15759                 if (isManagedProfile(userId)) {
15760                     throw new SecurityException("Managed profile cannot disable status bar");
15761                 }
15762             }
15763             DevicePolicyData policy = getUserData(userId);
15764             return policy.mStatusBarDisabled;
15765         }
15766     }
15767 
getPackagesSuspendedByAdmin(@serIdInt int userId)15768     private Set<String> getPackagesSuspendedByAdmin(@UserIdInt int userId) {
15769         synchronized (getLockObject()) {
15770             ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
15771             if (admin == null || admin.suspendedPackages == null) {
15772                 return Collections.emptySet();
15773             } else {
15774                 return new ArraySet<>(admin.suspendedPackages);
15775             }
15776         }
15777     }
15778 
15779     /**
15780      * We need to update the internal state of whether a user has completed setup or a
15781      * device has paired once. After that, we ignore any changes that reset the
15782      * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
15783      * as we don't trust any apps that might try to reset them.
15784      * <p>
15785      * Unfortunately, we don't know which user's setup state was changed, so we write all of
15786      * them.
15787      */
updateUserSetupCompleteAndPaired()15788     void updateUserSetupCompleteAndPaired() {
15789         List<UserInfo> users = mUserManager.getAliveUsers();
15790         final int N = users.size();
15791         for (int i = 0; i < N; i++) {
15792             int userHandle = users.get(i).id;
15793             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
15794                     userHandle) != 0) {
15795                 DevicePolicyData policy = getUserData(userHandle);
15796                 if (!policy.mUserSetupComplete) {
15797                     policy.mUserSetupComplete = true;
15798                     if (userHandle == UserHandle.USER_SYSTEM) {
15799                         mStateCache.setDeviceProvisioned(true);
15800                     }
15801                     synchronized (getLockObject()) {
15802                         saveSettingsLocked(userHandle);
15803                     }
15804                 }
15805             }
15806             if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
15807                     userHandle) != 0) {
15808                 DevicePolicyData policy = getUserData(userHandle);
15809                 if (!policy.mPaired) {
15810                     policy.mPaired = true;
15811                     synchronized (getLockObject()) {
15812                         saveSettingsLocked(userHandle);
15813                     }
15814                 }
15815             }
15816         }
15817     }
15818 
15819     private class SetupContentObserver extends ContentObserver {
15820         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
15821                 Settings.Secure.USER_SETUP_COMPLETE);
15822         private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
15823                 Settings.Global.DEVICE_PROVISIONED);
15824         private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
15825         private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
15826                 Settings.Secure.DEFAULT_INPUT_METHOD);
15827 
15828         @GuardedBy("getLockObject()")
15829         private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
15830 
SetupContentObserver(Handler handler)15831         public SetupContentObserver(Handler handler) {
15832             super(handler);
15833         }
15834 
register()15835         void register() {
15836             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
15837             mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
15838             if (mIsWatch) {
15839                 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
15840             }
15841             mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
15842         }
15843 
15844         @GuardedBy("getLockObject()")
addPendingChangeByOwnerLocked(int userId)15845         private void addPendingChangeByOwnerLocked(int userId) {
15846             mUserIdsWithPendingChangesByOwner.add(userId);
15847         }
15848 
15849         @Override
onChange(boolean selfChange, Uri uri, int userId)15850         public void onChange(boolean selfChange, Uri uri, int userId) {
15851             if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
15852                 updateUserSetupCompleteAndPaired();
15853             } else if (mDeviceProvisioned.equals(uri)) {
15854                 synchronized (getLockObject()) {
15855                     // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
15856                     // is delayed until device is marked as provisioned.
15857                     setDeviceOwnershipSystemPropertyLocked();
15858                 }
15859             } else if (mDefaultImeChanged.equals(uri)) {
15860                 synchronized (getLockObject()) {
15861                     if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
15862                         // This change notification was triggered by the owner changing the current
15863                         // IME. Ignore it.
15864                         mUserIdsWithPendingChangesByOwner.remove(userId);
15865                     } else {
15866                         // This change notification was triggered by the user manually changing the
15867                         // current IME.
15868                         getUserData(userId).mCurrentInputMethodSet = false;
15869                         saveSettingsLocked(userId);
15870                     }
15871                 }
15872             }
15873         }
15874     }
15875 
15876     private class DevicePolicyConstantsObserver extends ContentObserver {
15877         final Uri mConstantsUri =
15878                 Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS);
15879 
DevicePolicyConstantsObserver(Handler handler)15880         DevicePolicyConstantsObserver(Handler handler) {
15881             super(handler);
15882         }
15883 
register()15884         void register() {
15885             mInjector.registerContentObserver(
15886                     mConstantsUri, /* notifyForDescendents= */ false, this, UserHandle.USER_ALL);
15887         }
15888 
15889         @Override
onChange(boolean selfChange, Uri uri, int userId)15890         public void onChange(boolean selfChange, Uri uri, int userId) {
15891             mConstants = loadConstants();
15892             invalidateBinderCaches();
15893 
15894             mInjector.binderWithCleanCallingIdentity(() -> {
15895                 final Intent intent = new Intent(
15896                         DevicePolicyManager.ACTION_DEVICE_POLICY_CONSTANTS_CHANGED);
15897                 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
15898                 final List<UserInfo> users = mUserManager.getAliveUsers();
15899                 for (int i = 0; i < users.size(); i++) {
15900                     mContext.sendBroadcastAsUser(intent, UserHandle.of(users.get(i).id));
15901                 }
15902             });
15903         }
15904     }
15905 
15906     @VisibleForTesting
15907     final class LocalService extends DevicePolicyManagerInternal
15908             implements DevicePolicyManagerLiteInternal {
15909         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
15910 
15911         @Override
getCrossProfileWidgetProviders(int profileId)15912         public List<String> getCrossProfileWidgetProviders(int profileId) {
15913             synchronized (getLockObject()) {
15914                 if (mOwners == null) {
15915                     return Collections.emptyList();
15916                 }
15917                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
15918                 if (ownerComponent == null) {
15919                     return Collections.emptyList();
15920                 }
15921 
15922                 DevicePolicyData policy = getUserDataUnchecked(profileId);
15923                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
15924 
15925                 if (admin == null || admin.crossProfileWidgetProviders == null
15926                         || admin.crossProfileWidgetProviders.isEmpty()) {
15927                     return Collections.emptyList();
15928                 }
15929 
15930                 return admin.crossProfileWidgetProviders;
15931             }
15932         }
15933 
15934         @Override
addOnCrossProfileWidgetProvidersChangeListener( OnCrossProfileWidgetProvidersChangeListener listener)15935         public void addOnCrossProfileWidgetProvidersChangeListener(
15936                 OnCrossProfileWidgetProvidersChangeListener listener) {
15937             synchronized (getLockObject()) {
15938                 if (mWidgetProviderListeners == null) {
15939                     mWidgetProviderListeners = new ArrayList<>();
15940                 }
15941                 if (!mWidgetProviderListeners.contains(listener)) {
15942                     mWidgetProviderListeners.add(listener);
15943                 }
15944             }
15945         }
15946 
15947         @Override
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle userHandle)15948         public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
15949                 @NonNull UserHandle userHandle) {
15950             return DevicePolicyManagerService.this.getProfileOwnerOrDeviceOwnerSupervisionComponent(
15951                     userHandle);
15952         }
15953 
15954         @Override
isActiveDeviceOwner(int uid)15955         public boolean isActiveDeviceOwner(int uid) {
15956             return isDefaultDeviceOwner(new CallerIdentity(uid, null, null));
15957         }
15958 
15959         @Override
isActiveProfileOwner(int uid)15960         public boolean isActiveProfileOwner(int uid) {
15961             return isProfileOwner(new CallerIdentity(uid, null, null));
15962         }
15963 
15964         @Override
isActiveSupervisionApp(int uid)15965         public boolean isActiveSupervisionApp(int uid) {
15966             if (!isProfileOwner(new CallerIdentity(uid, null, null))) {
15967                 return false;
15968             }
15969             synchronized (getLockObject()) {
15970                 final ActiveAdmin admin = getProfileOwnerAdminLocked(UserHandle.getUserId(uid));
15971                 if (admin == null) {
15972                     return false;
15973                 }
15974 
15975                 return isSupervisionComponentLocked(admin.info.getComponent());
15976             }
15977         }
15978 
notifyCrossProfileProvidersChanged(int userId, List<String> packages)15979         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
15980             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
15981             synchronized (getLockObject()) {
15982                 listeners = new ArrayList<>(mWidgetProviderListeners);
15983             }
15984             final int listenerCount = listeners.size();
15985             for (int i = 0; i < listenerCount; i++) {
15986                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
15987                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
15988             }
15989         }
15990 
15991         @Override
createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin)15992         public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
15993             // This method is called from AM with its lock held, so don't take the DPMS lock.
15994             // b/29242568
15995 
15996             if (getEnforcingAdminAndUserDetailsInternal(userId, null) != null
15997                     || useDefaultIfNoAdmin) {
15998                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(userId);
15999             }
16000             return null;
16001         }
16002 
16003         @Override
createUserRestrictionSupportIntent(int userId, String userRestriction)16004         public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
16005             Intent intent = null;
16006             if (getEnforcingAdminAndUserDetailsInternal(userId, userRestriction) != null) {
16007                 intent = DevicePolicyManagerService.this.createShowAdminSupportIntent(userId);
16008                 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, userRestriction);
16009             }
16010             return intent;
16011         }
16012 
16013         @Override
isUserAffiliatedWithDevice(int userId)16014         public boolean isUserAffiliatedWithDevice(int userId) {
16015             return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
16016         }
16017 
16018         @Override
canSilentlyInstallPackage(String callerPackage, int callerUid)16019         public boolean canSilentlyInstallPackage(String callerPackage, int callerUid) {
16020             if (callerPackage == null) {
16021                 return false;
16022             }
16023 
16024             CallerIdentity caller = new CallerIdentity(callerUid, null, null);
16025             if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid))
16026                     && (isActiveProfileOwner(callerUid)
16027                     || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller))) {
16028                 // device owner or a profile owner affiliated with the device owner
16029                 return true;
16030             }
16031             return false;
16032         }
16033 
16034         @Override
reportSeparateProfileChallengeChanged(@serIdInt int userId)16035         public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) {
16036             mInjector.binderWithCleanCallingIdentity(() -> {
16037                 synchronized (getLockObject()) {
16038                     updateMaximumTimeToLockLocked(userId);
16039                     updatePasswordQualityCacheForUserGroup(userId);
16040                 }
16041             });
16042             DevicePolicyEventLogger
16043                     .createEvent(DevicePolicyEnums.SEPARATE_PROFILE_CHALLENGE_CHANGED)
16044                     .setBoolean(isSeparateProfileChallengeEnabled(userId))
16045                     .write();
16046             invalidateBinderCaches();
16047         }
16048 
16049         @Override
getPrintingDisabledReasonForUser(@serIdInt int userId)16050         public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) {
16051             synchronized (getLockObject()) {
16052                 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING,
16053                         UserHandle.of(userId))) {
16054                     Slogf.e(LOG_TAG, "printing is enabled for user %d", userId);
16055                     return null;
16056                 }
16057                 String ownerPackage = mOwners.getProfileOwnerPackage(userId);
16058                 if (ownerPackage == null) {
16059                     ownerPackage = mOwners.getDeviceOwnerPackageName();
16060                 }
16061                 final String packageName = ownerPackage;
16062                 PackageManager pm = mInjector.getPackageManager();
16063                 PackageInfo packageInfo = mInjector.binderWithCleanCallingIdentity(() -> {
16064                     try {
16065                         return pm.getPackageInfo(packageName, 0);
16066                     } catch (NameNotFoundException e) {
16067                         Slogf.e(LOG_TAG, "getPackageInfo error", e);
16068                         return null;
16069                     }
16070                 });
16071                 if (packageInfo == null) {
16072                     Slogf.e(LOG_TAG, "packageInfo is inexplicably null");
16073                     return null;
16074                 }
16075                 ApplicationInfo appInfo = packageInfo.applicationInfo;
16076                 if (appInfo == null) {
16077                     Slogf.e(LOG_TAG, "appInfo is inexplicably null");
16078                     return null;
16079                 }
16080                 CharSequence appLabel = pm.getApplicationLabel(appInfo);
16081                 if (appLabel == null) {
16082                     Slogf.e(LOG_TAG, "appLabel is inexplicably null");
16083                     return null;
16084                 }
16085                 return getUpdatableString(
16086                         PRINTING_DISABLED_NAMED_ADMIN,
16087                         R.string.printing_disabled_by,
16088                         appLabel);
16089             }
16090         }
16091 
16092         @Override
getDevicePolicyCache()16093         protected DevicePolicyCache getDevicePolicyCache() {
16094             return mPolicyCache;
16095         }
16096 
16097         @Override
getDeviceStateCache()16098         protected DeviceStateCache getDeviceStateCache() {
16099             return mStateCache;
16100         }
16101 
16102         @Override
getAllCrossProfilePackages(int userId)16103         public List<String> getAllCrossProfilePackages(int userId) {
16104             return DevicePolicyManagerService.this.getAllCrossProfilePackages(userId);
16105         }
16106 
16107         @Override
getDefaultCrossProfilePackages()16108         public List<String> getDefaultCrossProfilePackages() {
16109             return DevicePolicyManagerService.this.getDefaultCrossProfilePackages();
16110         }
16111 
16112         @Override
broadcastIntentToManifestReceivers( Intent intent, UserHandle parentHandle, boolean requiresPermission)16113         public void broadcastIntentToManifestReceivers(
16114                 Intent intent, UserHandle parentHandle, boolean requiresPermission) {
16115             Objects.requireNonNull(intent);
16116             Objects.requireNonNull(parentHandle);
16117             Slogf.i(LOG_TAG, "Sending %s broadcast to manifest receivers.", intent.getAction());
16118             broadcastIntentToCrossProfileManifestReceivers(
16119                     intent, parentHandle, requiresPermission);
16120             broadcastExplicitIntentToRoleHolder(
16121                     intent, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, parentHandle);
16122         }
16123 
16124         @Override
enforcePermission(String callerPackage, String permission, int targetUserId)16125         public void enforcePermission(String callerPackage, String permission, int targetUserId) {
16126             DevicePolicyManagerService.this.enforcePermission(permission, callerPackage,
16127                     targetUserId);
16128         }
16129 
16130         @Override
hasPermission(String callerPackage, String permission, int targetUserId)16131         public boolean hasPermission(String callerPackage, String permission, int targetUserId) {
16132             return DevicePolicyManagerService.this.hasPermission(permission, callerPackage,
16133                     targetUserId);
16134         }
16135 
broadcastIntentToCrossProfileManifestReceivers( Intent intent, UserHandle userHandle, boolean requiresPermission)16136         private void broadcastIntentToCrossProfileManifestReceivers(
16137                 Intent intent, UserHandle userHandle, boolean requiresPermission) {
16138             final int userId = userHandle.getIdentifier();
16139             try {
16140                 final List<ResolveInfo> receivers = mIPackageManager.queryIntentReceivers(
16141                         intent, /* resolvedType= */ null,
16142                         STOCK_PM_FLAGS, userId).getList();
16143                 for (ResolveInfo receiver : receivers) {
16144                     final String packageName = receiver.getComponentInfo().packageName;
16145                     if (checkCrossProfilePackagePermissions(packageName, userId,
16146                             requiresPermission)
16147                             || checkModifyQuietModePermission(packageName, userId)) {
16148                         Slogf.i(LOG_TAG, "Sending %s broadcast to %s.", intent.getAction(),
16149                                 packageName);
16150                         final Intent packageIntent = new Intent(intent)
16151                                 .setComponent(receiver.getComponentInfo().getComponentName())
16152                                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
16153                         mContext.sendBroadcastAsUser(packageIntent, userHandle);
16154                     }
16155                 }
16156             } catch (RemoteException ex) {
16157                 Slogf.w(LOG_TAG, "Cannot get list of broadcast receivers for %s because: %s.",
16158                         intent.getAction(), ex);
16159             }
16160         }
16161 
16162         /**
16163          * Checks whether the package {@code packageName} has the {@code MODIFY_QUIET_MODE}
16164          * permission granted for the user {@code userId}.
16165          */
checkModifyQuietModePermission(String packageName, @UserIdInt int userId)16166         private boolean checkModifyQuietModePermission(String packageName, @UserIdInt int userId) {
16167             try {
16168                 final int uid = Objects.requireNonNull(
16169                         mInjector.getPackageManager().getApplicationInfoAsUser(
16170                                 Objects.requireNonNull(packageName), /* flags= */ 0, userId)).uid;
16171                 return PackageManager.PERMISSION_GRANTED
16172                         == ActivityManager.checkComponentPermission(
16173                         android.Manifest.permission.MODIFY_QUIET_MODE, uid, /* owningUid= */
16174                         -1, /* exported= */ true);
16175             } catch (NameNotFoundException ex) {
16176                 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
16177                         packageName);
16178                 return false;
16179             }
16180         }
16181 
16182         /**
16183          * Checks whether the package {@code packageName} has the required permissions to receive
16184          * cross-profile broadcasts on behalf of the user {@code userId}.
16185          */
checkCrossProfilePackagePermissions(String packageName, @UserIdInt int userId, boolean requiresPermission)16186         private boolean checkCrossProfilePackagePermissions(String packageName,
16187                 @UserIdInt int userId, boolean requiresPermission) {
16188             final PackageManagerInternal pmInternal = LocalServices.getService(
16189                     PackageManagerInternal.class);
16190             final AndroidPackage androidPackage = pmInternal.getPackage(packageName);
16191             if (androidPackage == null || !androidPackage.isCrossProfile()) {
16192                 return false;
16193             }
16194             if (!requiresPermission) {
16195                 return true;
16196             }
16197             if (!isPackageEnabled(packageName, userId)) {
16198                 return false;
16199             }
16200             try {
16201                 final CrossProfileAppsInternal crossProfileAppsService = LocalServices.getService(
16202                         CrossProfileAppsInternal.class);
16203                 return crossProfileAppsService.verifyPackageHasInteractAcrossProfilePermission(
16204                         packageName, userId);
16205             } catch (NameNotFoundException ex) {
16206                 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
16207                         packageName);
16208                 return false;
16209             }
16210         }
16211 
isPackageEnabled(String packageName, @UserIdInt int userId)16212         private boolean isPackageEnabled(String packageName, @UserIdInt int userId) {
16213             final int callingUid = Binder.getCallingUid();
16214             final long ident = Binder.clearCallingIdentity();
16215             try {
16216                 final PackageInfo info = mInjector.getPackageManagerInternal()
16217                         .getPackageInfo(
16218                                 packageName,
16219                                 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
16220                                 callingUid,
16221                                 userId);
16222                 return info != null && info.applicationInfo.enabled;
16223             } finally {
16224                 Binder.restoreCallingIdentity(ident);
16225             }
16226         }
16227 
16228         @Override
getProfileOwnerAsUser(@serIdInt int userId)16229         public ComponentName getProfileOwnerAsUser(@UserIdInt int userId) {
16230             return DevicePolicyManagerService.this.getProfileOwnerAsUser(userId);
16231         }
16232 
16233         @Override
getDeviceOwnerComponent(boolean callingUserOnly)16234         public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
16235             return DevicePolicyManagerService.this.getDeviceOwnerComponent(callingUserOnly);
16236         }
16237 
16238         @Override
getDeviceOwnerUserId()16239         public int getDeviceOwnerUserId() {
16240             return DevicePolicyManagerService.this.getDeviceOwnerUserId();
16241         }
16242 
16243         @Override
isDeviceOrProfileOwnerInCallingUser(String packageName)16244         public boolean isDeviceOrProfileOwnerInCallingUser(String packageName) {
16245             return isDeviceOwnerInCallingUser(packageName)
16246                     || isProfileOwnerInCallingUser(packageName);
16247         }
16248 
isDeviceOwnerInCallingUser(String packageName)16249         private boolean isDeviceOwnerInCallingUser(String packageName) {
16250             final ComponentName deviceOwnerInCallingUser =
16251                     DevicePolicyManagerService.this.getDeviceOwnerComponent(
16252                             /* callingUserOnly= */ true);
16253             return deviceOwnerInCallingUser != null
16254                     && packageName.equals(deviceOwnerInCallingUser.getPackageName());
16255         }
16256 
isProfileOwnerInCallingUser(String packageName)16257         private boolean isProfileOwnerInCallingUser(String packageName) {
16258             final ComponentName profileOwnerInCallingUser =
16259                     getProfileOwnerAsUser(UserHandle.getCallingUserId());
16260             return profileOwnerInCallingUser != null
16261                     && packageName.equals(profileOwnerInCallingUser.getPackageName());
16262         }
16263 
16264         @Override
supportsResetOp(int op)16265         public boolean supportsResetOp(int op) {
16266             return op == AppOpsManager.OP_INTERACT_ACROSS_PROFILES
16267                     && LocalServices.getService(CrossProfileAppsInternal.class) != null;
16268         }
16269 
16270         @Override
resetOp(int op, String packageName, @UserIdInt int userId)16271         public void resetOp(int op, String packageName, @UserIdInt int userId) {
16272             if (op != AppOpsManager.OP_INTERACT_ACROSS_PROFILES) {
16273                 throw new IllegalArgumentException("Unsupported op for DPM reset: " + op);
16274             }
16275             LocalServices.getService(CrossProfileAppsInternal.class)
16276                     .setInteractAcrossProfilesAppOp(
16277                             packageName, findInteractAcrossProfilesResetMode(packageName), userId);
16278         }
16279 
16280         @Override
getPackagesSuspendedByAdmin(@serIdInt int userId)16281         public Set<String> getPackagesSuspendedByAdmin(@UserIdInt int userId) {
16282             return DevicePolicyManagerService.this.getPackagesSuspendedByAdmin(userId);
16283         }
16284 
16285         @Override
notifyUnsafeOperationStateChanged(DevicePolicySafetyChecker checker, int reason, boolean isSafe)16286         public void notifyUnsafeOperationStateChanged(DevicePolicySafetyChecker checker, int reason,
16287                 boolean isSafe) {
16288             // TODO(b/178494483): use EventLog instead
16289             // TODO(b/178494483): log metrics?
16290             if (VERBOSE_LOG) {
16291                 Slogf.v(LOG_TAG, "notifyUnsafeOperationStateChanged(): %s=%b",
16292                         DevicePolicyManager.operationSafetyReasonToString(reason), isSafe);
16293             }
16294             Preconditions.checkArgument(mSafetyChecker == checker,
16295                     "invalid checker: should be %s, was %s", mSafetyChecker, checker);
16296 
16297             Bundle extras = new Bundle();
16298             extras.putInt(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_REASON, reason);
16299             extras.putBoolean(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_STATE, isSafe);
16300 
16301             if (mOwners.hasDeviceOwner()) {
16302                 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying DO");
16303                 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED,
16304                         extras);
16305             }
16306             for (int profileOwnerId : mOwners.getProfileOwnerKeys()) {
16307                 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying PO for user " + profileOwnerId);
16308                 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED,
16309                         extras, profileOwnerId);
16310             }
16311         }
16312 
16313         @Override
isKeepProfilesRunningEnabled()16314         public boolean isKeepProfilesRunningEnabled() {
16315             return getUserDataUnchecked(UserHandle.USER_SYSTEM).mEffectiveKeepProfilesRunning;
16316         }
16317 
findInteractAcrossProfilesResetMode(String packageName)16318         private @Mode int findInteractAcrossProfilesResetMode(String packageName) {
16319             return getDefaultCrossProfilePackages().contains(packageName)
16320                     ? AppOpsManager.MODE_ALLOWED
16321                     : AppOpsManager.opToDefaultMode(AppOpsManager.OP_INTERACT_ACROSS_PROFILES);
16322         }
16323 
16324         @Override
isUserOrganizationManaged(@serIdInt int userHandle)16325         public boolean isUserOrganizationManaged(@UserIdInt int userHandle) {
16326             return getDeviceStateCache().isUserOrganizationManaged(userHandle);
16327         }
16328 
16329         @Override
isApplicationExemptionsFlagEnabled()16330         public boolean isApplicationExemptionsFlagEnabled() {
16331             return DeviceConfig.getBoolean(
16332                     NAMESPACE_DEVICE_POLICY_MANAGER,
16333                     APPLICATION_EXEMPTIONS_FLAG,
16334                     DEFAULT_APPLICATION_EXEMPTIONS_FLAG);
16335         }
16336 
16337         @Override
getApplicationRestrictionsPerAdminForUser( String packageName, @UserIdInt int userId)16338         public List<Bundle> getApplicationRestrictionsPerAdminForUser(
16339                 String packageName, @UserIdInt int userId) {
16340             if (UserHandle.getCallingUserId() != userId
16341                     || !UserHandle.isSameApp(
16342                     Binder.getCallingUid(), getUidForPackage(packageName, userId))) {
16343                 final int uid = Binder.getCallingUid();
16344                 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
16345                     throw new SecurityException("Only system may: get application restrictions for "
16346                             + "other user/app " + packageName);
16347                 }
16348             }
16349             LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
16350                     mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
16351                             PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
16352                             userId);
16353             List<Bundle> restrictions = new ArrayList<>();
16354             for (EnforcingAdmin admin : policies.keySet()) {
16355                 restrictions.add(policies.get(admin).getValue());
16356             }
16357             if (!restrictions.isEmpty()) {
16358                 return restrictions;
16359             }
16360 
16361             return mInjector.binderWithCleanCallingIdentity(() -> {
16362                 // Could be a device that has a DPC that hasn't migrated yet, so just return any
16363                 // restrictions saved in userManager.
16364                 Bundle bundle = mUserManager.getApplicationRestrictions(
16365                         packageName, UserHandle.of(userId));
16366                 if (bundle == null || bundle.isEmpty()) {
16367                     return new ArrayList<>();
16368                 }
16369                 return List.of(bundle);
16370             });
16371         }
16372 
getUserRestrictionSources(String restriction, @UserIdInt int userId)16373         public List<EnforcingUser> getUserRestrictionSources(String restriction,
16374                 @UserIdInt int userId) {
16375             PolicyDefinition<Boolean> policy =
16376                     PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction);
16377 
16378             Set<EnforcingAdmin> localAdmins =
16379                     mDevicePolicyEngine.getLocalPoliciesSetByAdmins(policy, userId).keySet();
16380 
16381             Set<EnforcingAdmin> globalAdmins =
16382                     mDevicePolicyEngine.getGlobalPoliciesSetByAdmins(policy).keySet();
16383 
16384             List<EnforcingUser> enforcingUsers = new ArrayList();
16385             enforcingUsers.addAll(getEnforcingUsers(localAdmins));
16386             enforcingUsers.addAll(getEnforcingUsers(globalAdmins));
16387             return enforcingUsers;
16388         }
16389 
getEnforcingUsers(Set<EnforcingAdmin> admins)16390         private List<EnforcingUser> getEnforcingUsers(Set<EnforcingAdmin> admins) {
16391             List<EnforcingUser> enforcingUsers = new ArrayList();
16392             ComponentName deviceOwner = mOwners.getDeviceOwnerComponent();
16393             for (EnforcingAdmin admin : admins) {
16394                 if (deviceOwner != null
16395                         && deviceOwner.getPackageName().equals(admin.getPackageName())) {
16396                     enforcingUsers.add(new EnforcingUser(admin.getUserId(),
16397                             UserManager.RESTRICTION_SOURCE_DEVICE_OWNER));
16398                 } else {
16399                     enforcingUsers.add(new EnforcingUser(admin.getUserId(),
16400                             UserManager.RESTRICTION_SOURCE_PROFILE_OWNER));
16401                 }
16402             }
16403             return enforcingUsers;
16404         }
16405     }
16406 
createShowAdminSupportIntent(int userId)16407     private Intent createShowAdminSupportIntent(int userId) {
16408         // This method is called with AMS lock held, so don't take DPMS lock
16409         final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
16410         intent.putExtra(Intent.EXTRA_USER_ID, userId);
16411         intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
16412         return intent;
16413     }
16414 
16415     /**
16416      * @param restriction The restriction enforced by admin. It could be any user restriction or
16417      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA},
16418      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE} and  {@link
16419      *                    DevicePolicyManager#POLICY_SUSPEND_PACKAGES}.
16420      */
getEnforcingAdminAndUserDetailsInternal(int userId, String restriction)16421     private Bundle getEnforcingAdminAndUserDetailsInternal(int userId, String restriction) {
16422         Bundle result = null;
16423 
16424         // For POLICY_SUSPEND_PACKAGES return PO or DO to keep the behavior same as
16425         // before the bug fix for b/192245204.
16426         if (restriction == null || DevicePolicyManager.POLICY_SUSPEND_PACKAGES.equals(
16427                 restriction)) {
16428             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
16429             if (profileOwner != null) {
16430                 result = new Bundle();
16431                 result.putInt(Intent.EXTRA_USER_ID, userId);
16432                 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16433                         profileOwner);
16434                 return result;
16435             }
16436             final Pair<Integer, ComponentName> deviceOwner =
16437                     mOwners.getDeviceOwnerUserIdAndComponent();
16438             if (deviceOwner != null && deviceOwner.first == userId) {
16439                 result = new Bundle();
16440                 result.putInt(Intent.EXTRA_USER_ID, userId);
16441                 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16442                         deviceOwner.second);
16443                 return result;
16444             }
16445         } else if (DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
16446             if (isPolicyEngineForFinanceFlagEnabled()) {
16447                 Boolean value = mDevicePolicyEngine.getResolvedPolicy(
16448                         PolicyDefinition.SCREEN_CAPTURE_DISABLED, userId);
16449                 if (value != null && value) {
16450                     result = new Bundle();
16451                     result.putInt(Intent.EXTRA_USER_ID, userId);
16452                     return result;
16453                 }
16454             } else {
16455                 synchronized (getLockObject()) {
16456                     final DevicePolicyData policy = getUserData(userId);
16457                     final int N = policy.mAdminList.size();
16458                     for (int i = 0; i < N; i++) {
16459                         final ActiveAdmin admin = policy.mAdminList.get(i);
16460                         if (admin.disableScreenCapture) {
16461                             result = new Bundle();
16462                             result.putInt(Intent.EXTRA_USER_ID, userId);
16463                             result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16464                                     admin.info.getComponent());
16465                             return result;
16466                         }
16467                     }
16468                 }
16469             }
16470         } else if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
16471             if (isPolicyEngineForFinanceFlagEnabled()) {
16472                 PolicyDefinition<Boolean> policyDefinition =
16473                         PolicyDefinition.getPolicyDefinitionForUserRestriction(
16474                                 UserManager.DISALLOW_CAMERA);
16475                 Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
16476                 if (value != null && value) {
16477                     result = new Bundle();
16478                     result.putInt(Intent.EXTRA_USER_ID, userId);
16479                     return result;
16480                 }
16481             } else {
16482                 synchronized (getLockObject()) {
16483                     final DevicePolicyData policy = getUserData(userId);
16484                     final int N = policy.mAdminList.size();
16485                     for (int i = 0; i < N; i++) {
16486                         final ActiveAdmin admin = policy.mAdminList.get(i);
16487                         if (admin.disableCamera) {
16488                             result = new Bundle();
16489                             result.putInt(Intent.EXTRA_USER_ID, userId);
16490                             result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16491                                     admin.info.getComponent());
16492                             return result;
16493                         }
16494                     }
16495                     // For the camera, a device owner on a different user can disable it globally,
16496                     // so we need an additional check.
16497                     if (result == null
16498                             && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
16499                         final ActiveAdmin admin = getDeviceOwnerAdminLocked();
16500                         if (admin != null && admin.disableCamera) {
16501                             result = new Bundle();
16502                             result.putInt(Intent.EXTRA_USER_ID, mOwners.getDeviceOwnerUserId());
16503                             result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16504                                     admin.info.getComponent());
16505                             return result;
16506                         }
16507                     }
16508                 }
16509             }
16510         } else {
16511             long ident = mInjector.binderClearCallingIdentity();
16512             try {
16513                 // TODO(b/277908283): check in the policy engine instead of calling user manager.
16514                 List<UserManager.EnforcingUser> sources = mUserManager
16515                         .getUserRestrictionSources(restriction, UserHandle.of(userId));
16516                 if (sources == null) {
16517                     // The restriction is not enforced.
16518                     return null;
16519                 }
16520                 int sizeBefore = sources.size();
16521                 if (sizeBefore > 1) {
16522                     Slogf.d(LOG_TAG, "getEnforcingAdminAndUserDetailsInternal(%d, %s): "
16523                             + "%d sources found, excluding those set by UserManager",
16524                             userId, restriction, sizeBefore);
16525                     sources = getDevicePolicySources(sources);
16526                 }
16527                 if (sources.isEmpty()) {
16528                     // The restriction is not enforced (or is just enforced by the system)
16529                     return null;
16530                 }
16531 
16532                 if (sources.size() > 1) {
16533                     // In this case, we'll show an admin support dialog that does not
16534                     // specify the admin.
16535                     // TODO(b/128928355): if this restriction is enforced by multiple DPCs, return
16536                     // the admin for the calling user.
16537                     Slogf.w(LOG_TAG, "getEnforcingAdminAndUserDetailsInternal(%d, %s): multiple "
16538                             + "sources for restriction %s on user %d",
16539                             userId, restriction, restriction, userId);
16540                     result = new Bundle();
16541                     result.putInt(Intent.EXTRA_USER_ID, userId);
16542                     return result;
16543                 }
16544                 final UserManager.EnforcingUser enforcingUser = sources.get(0);
16545                 final int sourceType = enforcingUser.getUserRestrictionSource();
16546                 if (sourceType == UserManager.RESTRICTION_SOURCE_PROFILE_OWNER
16547                         || sourceType == UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) {
16548                     ActiveAdmin admin = getMostProbableDPCAdminForLocalPolicy(userId);
16549                     if (admin != null) {
16550                         result = new Bundle();
16551                         result.putInt(Intent.EXTRA_USER_ID, admin.getUserHandle().getIdentifier());
16552                         result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16553                                 admin.info.getComponent());
16554                         return result;
16555                     }
16556                 } else if (sourceType == UserManager.RESTRICTION_SOURCE_SYSTEM) {
16557                     /*
16558                      * In this case, the user restriction is enforced by the system.
16559                      * So we won't show an admin support intent, even if it is also
16560                      * enforced by a profile/device owner.
16561                      */
16562                     return null;
16563                 }
16564             } finally {
16565                 mInjector.binderRestoreCallingIdentity(ident);
16566             }
16567         }
16568         return null;
16569     }
16570 
16571     /**
16572      * @param restriction The restriction enforced by admin. It could be any user restriction or
16573      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA},
16574      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE} and  {@link
16575      *                    DevicePolicyManager#POLICY_SUSPEND_PACKAGES}.
16576      */
getEnforcingAdminsForRestrictionInternal( int userId, @NonNull String restriction)16577     private Set<android.app.admin.EnforcingAdmin> getEnforcingAdminsForRestrictionInternal(
16578             int userId, @NonNull String restriction) {
16579         Objects.requireNonNull(restriction);
16580         Set<android.app.admin.EnforcingAdmin> admins = new HashSet<>();
16581         // For POLICY_SUSPEND_PACKAGES return PO or DO to keep the behavior same as
16582         // before the bug fix for b/192245204.
16583         if (DevicePolicyManager.POLICY_SUSPEND_PACKAGES.equals(
16584                 restriction)) {
16585             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
16586             if (profileOwner != null) {
16587                 EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
16588                         profileOwner, userId);
16589                 admins.add(admin.getParcelableAdmin());
16590                 return admins;
16591             }
16592             final Pair<Integer, ComponentName> deviceOwner =
16593                     mOwners.getDeviceOwnerUserIdAndComponent();
16594             if (deviceOwner != null && deviceOwner.first == userId) {
16595                 EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
16596                         deviceOwner.second, deviceOwner.first);
16597                 admins.add(admin.getParcelableAdmin());
16598                 return admins;
16599             }
16600         } else {
16601             long ident = mInjector.binderClearCallingIdentity();
16602             try {
16603                 PolicyDefinition<Boolean> policyDefinition = getPolicyDefinitionForRestriction(
16604                         restriction);
16605                 Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
16606                 if (value != null && value) {
16607                     Map<EnforcingAdmin, PolicyValue<Boolean>> globalPolicies =
16608                             mDevicePolicyEngine.getGlobalPoliciesSetByAdmins(policyDefinition);
16609                     for (EnforcingAdmin admin : globalPolicies.keySet()) {
16610                         if (globalPolicies.get(admin) != null
16611                                 && Boolean.TRUE.equals(globalPolicies.get(admin).getValue())) {
16612                             admins.add(admin.getParcelableAdmin());
16613                         }
16614                     }
16615 
16616                     Map<EnforcingAdmin, PolicyValue<Boolean>> localPolicies =
16617                             mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
16618                                     policyDefinition, userId);
16619                     for (EnforcingAdmin admin : localPolicies.keySet()) {
16620                         if (localPolicies.get(admin) != null
16621                                 && Boolean.TRUE.equals(localPolicies.get(admin).getValue())) {
16622                             admins.add(admin.getParcelableAdmin());
16623                         }
16624                     }
16625                     return admins;
16626                 }
16627             } finally {
16628                 mInjector.binderRestoreCallingIdentity(ident);
16629             }
16630         }
16631         return admins;
16632     }
16633 
getPolicyDefinitionForRestriction( @onNull String restriction)16634     private static PolicyDefinition<Boolean> getPolicyDefinitionForRestriction(
16635             @NonNull String restriction) {
16636         Objects.requireNonNull(restriction);
16637         if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
16638             return PolicyDefinition.getPolicyDefinitionForUserRestriction(
16639                     UserManager.DISALLOW_CAMERA);
16640         } else if (DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
16641             return PolicyDefinition.SCREEN_CAPTURE_DISABLED;
16642         } else {
16643             return PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction);
16644         }
16645     }
16646 
16647 
16648     /**
16649      *  Excludes restrictions imposed by UserManager.
16650      */
getDevicePolicySources( List<UserManager.EnforcingUser> sources)16651     private List<UserManager.EnforcingUser> getDevicePolicySources(
16652             List<UserManager.EnforcingUser> sources) {
16653         int sizeBefore = sources.size();
16654         List<UserManager.EnforcingUser> realSources = new ArrayList<>(sizeBefore);
16655         for (int i = 0; i < sizeBefore; i++) {
16656             UserManager.EnforcingUser source = sources.get(i);
16657             int type = source.getUserRestrictionSource();
16658             if (type != UserManager.RESTRICTION_SOURCE_PROFILE_OWNER
16659                     && type != UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) {
16660                 // TODO(b/128928355): add unit test
16661                 Slogf.d(LOG_TAG, "excluding source of type %s at index %d",
16662                         userRestrictionSourceToString(type), i);
16663                 continue;
16664             }
16665             realSources.add(source);
16666         }
16667         return realSources;
16668     }
16669 
userRestrictionSourceToString(@serRestrictionSource int source)16670     private static String userRestrictionSourceToString(@UserRestrictionSource int source) {
16671         return DebugUtils.flagsToString(UserManager.class, "RESTRICTION_", source);
16672     }
16673 
16674     /**
16675      * @param restriction The restriction enforced by admin. It could be any user restriction or
16676      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
16677      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
16678      * @return Details of admin and user which enforced the restriction for the userId.
16679      */
16680     @Override
getEnforcingAdminAndUserDetails(int userId, String restriction)16681     public Bundle getEnforcingAdminAndUserDetails(int userId, String restriction) {
16682         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()));
16683         return getEnforcingAdminAndUserDetailsInternal(userId, restriction);
16684     }
16685 
16686     @Override
getEnforcingAdminsForRestriction( int userId, String restriction)16687     public List<android.app.admin.EnforcingAdmin> getEnforcingAdminsForRestriction(
16688             int userId, String restriction) {
16689         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()));
16690         return new ArrayList<>(getEnforcingAdminsForRestrictionInternal(userId, restriction));
16691     }
16692 
16693     /**
16694      * @param restriction The restriction enforced by admin. It could be any user restriction or
16695      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
16696      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
16697      */
16698     @Override
createAdminSupportIntent(String restriction)16699     public Intent createAdminSupportIntent(String restriction) {
16700         Objects.requireNonNull(restriction);
16701         final CallerIdentity caller = getCallerIdentity();
16702         final int userId = caller.getUserId();
16703         Intent intent = null;
16704         if (getEnforcingAdminAndUserDetailsInternal(userId, restriction) != null) {
16705             intent = createShowAdminSupportIntent(userId);
16706             intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
16707         }
16708         return intent;
16709     }
16710 
16711     /**
16712      * Returns true if specified admin is allowed to limit passwords and has a
16713      * {@code mPasswordPolicy.quality} of at least {@code minPasswordQuality}
16714      */
isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality)16715     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
16716         if (admin.mPasswordPolicy.quality < minPasswordQuality) {
16717             return false;
16718         }
16719         return admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
16720     }
16721 
16722     @Override
setCredentialManagerPolicy(PackagePolicy policy)16723     public void setCredentialManagerPolicy(PackagePolicy policy) {
16724         if (!mHasFeature) {
16725             return;
16726         }
16727         final CallerIdentity caller = getCallerIdentity();
16728         Preconditions.checkCallAuthorization(canWriteCredentialManagerPolicy(caller));
16729 
16730         synchronized (getLockObject()) {
16731             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
16732             if (Objects.equals(admin.mCredentialManagerPolicy, policy)) {
16733                 return;
16734             }
16735 
16736             admin.mCredentialManagerPolicy = policy;
16737             saveSettingsLocked(caller.getUserId());
16738         }
16739     }
16740 
canWriteCredentialManagerPolicy(CallerIdentity caller)16741     private boolean canWriteCredentialManagerPolicy(CallerIdentity caller) {
16742         return (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))
16743                         || isDefaultDeviceOwner(caller)
16744                         || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS);
16745     }
16746 
16747     @Override
getCredentialManagerPolicy(int userId)16748     public PackagePolicy getCredentialManagerPolicy(int userId) {
16749         if (!mHasFeature) {
16750             return null;
16751         }
16752         final CallerIdentity caller = getCallerIdentity();
16753         Preconditions.checkCallAuthorization(
16754                 canWriteCredentialManagerPolicy(caller) || canQueryAdminPolicy(caller));
16755         if (userId != caller.getUserId()) {
16756             Preconditions.checkCallAuthorization(
16757                     hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
16758         }
16759 
16760         synchronized (getLockObject()) {
16761             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userId);
16762             return (admin != null) ? admin.mCredentialManagerPolicy : null;
16763         }
16764     }
16765 
16766     @Override
setSystemUpdatePolicy( ComponentName who, String callerPackageName, SystemUpdatePolicy policy)16767     public void setSystemUpdatePolicy(
16768             ComponentName who, String callerPackageName, SystemUpdatePolicy policy) {
16769         if (policy != null) {
16770             // throws exception if policy type is invalid
16771             policy.validateType();
16772             // throws exception if freeze period is invalid
16773             policy.validateFreezePeriods();
16774             Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
16775             // throws exception if freeze period is incompatible with previous freeze period record
16776             policy.validateAgainstPreviousFreezePeriod(record.first, record.second,
16777                     LocalDate.now());
16778         }
16779         CallerIdentity caller;
16780 
16781         synchronized (getLockObject()) {
16782             if (isPermissionCheckFlagEnabled()) {
16783                 caller = getCallerIdentity(who, callerPackageName);
16784                 enforcePermission(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, caller.getPackageName(),
16785                         UserHandle.USER_ALL);
16786             } else {
16787                 caller = getCallerIdentity(who);
16788                 Preconditions.checkCallAuthorization(
16789                         isProfileOwnerOfOrganizationOwnedDevice(caller)
16790                         || isDefaultDeviceOwner(caller));
16791             }
16792 
16793             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_UPDATE_POLICY);
16794 
16795             if (policy == null) {
16796                 mOwners.clearSystemUpdatePolicy();
16797             } else {
16798                 mOwners.setSystemUpdatePolicy(policy);
16799                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false);
16800             }
16801             mOwners.writeDeviceOwner();
16802         }
16803         mInjector.binderWithCleanCallingIdentity(() -> mContext.sendBroadcastAsUser(
16804                 new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM));
16805         DevicePolicyEventLogger
16806                 .createEvent(DevicePolicyEnums.SET_SYSTEM_UPDATE_POLICY)
16807                 .setAdmin(caller.getPackageName())
16808                 .setInt(policy != null ? policy.getPolicyType() : 0)
16809                 .write();
16810     }
16811 
16812     @Override
getSystemUpdatePolicy()16813     public SystemUpdatePolicy getSystemUpdatePolicy() {
16814         synchronized (getLockObject()) {
16815             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
16816             if (policy != null && !policy.isValid()) {
16817                 Slogf.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
16818                 return null;
16819             }
16820             return policy;
16821         }
16822     }
16823 
withinRange(Pair<LocalDate, LocalDate> range, LocalDate date)16824     private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) {
16825         return (!date.isBefore(range.first) && !date.isAfter(range.second));
16826     }
16827 
16828     /**
16829      * keeps track of the last continuous period when the system is under OTA freeze.
16830      *
16831      * DPMS keeps track of the previous dates during which OTA was freezed as a result of an
16832      * system update policy with freeze periods in effect. This is needed to make robust
16833      * validation on new system update polices, for example to prevent the OTA from being
16834      * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period
16835      * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting
16836      * a new freeze period after a few days.
16837      *
16838      * @param saveIfChanged whether to persist the result on disk if freeze period record is
16839      *            updated. This should only be set to {@code false} if there is a guaranteed
16840      *            mOwners.writeDeviceOwner() later in the control flow to reduce the number of
16841      *            disk writes. Otherwise you risk inconsistent on-disk state.
16842      *
16843      * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod
16844      */
updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged)16845     private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) {
16846         Slogf.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord");
16847         synchronized (getLockObject()) {
16848             final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
16849             if (policy == null) {
16850                 return;
16851             }
16852             final LocalDate now = LocalDate.now();
16853             final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now);
16854             if (currentPeriod == null) {
16855                 return;
16856             }
16857             final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
16858             final LocalDate start = record.first;
16859             final LocalDate end = record.second;
16860             final boolean changed;
16861             if (end == null || start == null) {
16862                 // Start a new period if there is none at the moment
16863                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
16864             } else if (now.equals(end.plusDays(1))) {
16865                 // Extend the existing period
16866                 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
16867             } else if (now.isAfter(end.plusDays(1))) {
16868                 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) {
16869                     // The device might be off for some period. If the past freeze record
16870                     // is within range of the current freeze period, assume the device was off
16871                     // during the period [end, now] and extend the freeze record to [start, now].
16872                     changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
16873                 } else {
16874                     changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
16875                 }
16876             } else if (now.isBefore(start)) {
16877                 // Systm clock was adjusted backwards, restart record
16878                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
16879             } else /* start <= now <= end */ {
16880                 changed = false;
16881             }
16882             if (changed && saveIfChanged) {
16883                 mOwners.writeDeviceOwner();
16884             }
16885         }
16886     }
16887 
16888     @Override
clearSystemUpdatePolicyFreezePeriodRecord()16889     public void clearSystemUpdatePolicyFreezePeriodRecord() {
16890         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
16891                         || hasCallingOrSelfPermission(permission.CLEAR_FREEZE_PERIOD),
16892                 "Caller must be shell, or hold CLEAR_FREEZE_PERIOD permission to call "
16893                         + "clearSystemUpdatePolicyFreezePeriodRecord");
16894         synchronized (getLockObject()) {
16895             // Print out current record to help diagnosed CTS failures
16896             Slogf.i(LOG_TAG, "Clear freeze period record: "
16897                     + mOwners.getSystemUpdateFreezePeriodRecordAsString());
16898             if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) {
16899                 mOwners.writeDeviceOwner();
16900             }
16901         }
16902     }
16903 
16904     /**
16905      * Checks if any of the packages associated with the UID of the app provided is that
16906      * of the device owner.
16907      * @param appUid UID of the app to check.
16908      * @return {@code true} if any of the packages are the device owner, {@code false} otherwise.
16909      */
isUidDeviceOwnerLocked(int appUid)16910     private boolean isUidDeviceOwnerLocked(int appUid) {
16911         ensureLocked();
16912         final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
16913                 .getPackageName();
16914         try {
16915             String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(appUid);
16916             if (pkgs == null) {
16917                 return false;
16918             }
16919 
16920             for (String pkg : pkgs) {
16921                 if (deviceOwnerPackageName.equals(pkg)) {
16922                     return true;
16923                 }
16924             }
16925         } catch (RemoteException e) {
16926             return false;
16927         }
16928         return false;
16929     }
16930 
16931     @Override
notifyPendingSystemUpdate(@ullable SystemUpdateInfo info)16932     public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
16933         Preconditions.checkCallAuthorization(
16934                 hasCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE),
16935                 "Only the system update service can broadcast update information");
16936 
16937         mInjector.binderWithCleanCallingIdentity(() -> {
16938             if (!mUserManager.getUserInfo(UserHandle.getCallingUserId()).isMain()) {
16939                 Slogf.w(LOG_TAG, "Only the system update service in the main user can broadcast "
16940                         + "update information.");
16941                 return;
16942             }
16943         });
16944 
16945         if (!mOwners.saveSystemUpdateInfo(info)) {
16946             // Pending system update hasn't changed, don't send duplicate notification.
16947             return;
16948         }
16949 
16950         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
16951                 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
16952                         info == null ? -1 : info.getReceivedTime());
16953 
16954         mInjector.binderWithCleanCallingIdentity(() -> {
16955             synchronized (getLockObject()) {
16956                 // Broadcast to device owner first if there is one.
16957                 if (mOwners.hasDeviceOwner()) {
16958                     final UserHandle deviceOwnerUser =
16959                             UserHandle.of(mOwners.getDeviceOwnerUserId());
16960                     intent.setComponent(mOwners.getDeviceOwnerComponent());
16961                     mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
16962                 }
16963             }
16964             // Get running users.
16965             final int runningUserIds[];
16966             try {
16967                 runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
16968             } catch (RemoteException e) {
16969                 // Shouldn't happen.
16970                 Slogf.e(LOG_TAG, "Could not retrieve the list of running users", e);
16971                 return;
16972             }
16973             // Send broadcasts to corresponding profile owners if any.
16974             for (final int userId : runningUserIds) {
16975                 synchronized (getLockObject()) {
16976                     final ComponentName profileOwnerPackage =
16977                             mOwners.getProfileOwnerComponent(userId);
16978                     if (profileOwnerPackage != null) {
16979                         intent.setComponent(profileOwnerPackage);
16980                         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
16981                     }
16982                 }
16983             }
16984         });
16985     }
16986 
16987     @Override
getPendingSystemUpdate(ComponentName admin)16988     public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
16989         Objects.requireNonNull(admin, "ComponentName is null");
16990 
16991         final CallerIdentity caller = getCallerIdentity(admin);
16992         Preconditions.checkCallAuthorization(
16993                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
16994 
16995         return mOwners.getSystemUpdateInfo();
16996     }
16997 
16998     @Override
setPermissionPolicy(ComponentName admin, String callerPackage, int policy)16999     public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) {
17000         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
17001         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
17002                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
17003                 || (caller.hasPackage() && isCallerDelegate(caller,
17004                 DELEGATION_PERMISSION_GRANT)));
17005         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_POLICY);
17006 
17007         final int forUser = caller.getUserId();
17008         synchronized (getLockObject()) {
17009             DevicePolicyData userPolicy = getUserData(forUser);
17010             if (userPolicy.mPermissionPolicy != policy) {
17011                 userPolicy.mPermissionPolicy = policy;
17012                 mPolicyCache.setPermissionPolicy(forUser, policy);
17013                 saveSettingsLocked(forUser);
17014             }
17015         }
17016         DevicePolicyEventLogger
17017                 .createEvent(DevicePolicyEnums.SET_PERMISSION_POLICY)
17018                 .setAdmin(caller.getPackageName())
17019                 .setInt(policy)
17020                 .setBoolean(/* isDelegate */ admin == null)
17021                 .write();
17022     }
17023 
updatePermissionPolicyCache(int userId)17024     private void updatePermissionPolicyCache(int userId) {
17025         synchronized (getLockObject()) {
17026             DevicePolicyData userPolicy = getUserData(userId);
17027             mPolicyCache.setPermissionPolicy(userId, userPolicy.mPermissionPolicy);
17028         }
17029     }
17030 
17031     @Override
getPermissionPolicy(ComponentName admin)17032     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
17033         int userId = UserHandle.getCallingUserId();
17034         return mPolicyCache.getPermissionPolicy(userId);
17035     }
17036 
17037     @Override
setPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission, int grantState, RemoteCallback callback)17038     public void setPermissionGrantState(ComponentName admin, String callerPackage,
17039             String packageName, String permission, int grantState, RemoteCallback callback)
17040             throws RemoteException {
17041         Objects.requireNonNull(callback);
17042 
17043         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
17044         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_GRANT_STATE);
17045 
17046         synchronized (getLockObject()) {
17047             if (isFinancedDeviceOwner(caller)) {
17048                 enforcePermissionGrantStateOnFinancedDevice(packageName, permission);
17049             }
17050         }
17051         EnforcingAdmin enforcingAdmin;
17052         if (isUnicornFlagEnabled()) {
17053             enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
17054                     admin,
17055                     MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
17056                     callerPackage,
17057                     caller.getUserId());
17058             if (SENSOR_PERMISSIONS.contains(permission)
17059                     && grantState == PERMISSION_GRANT_STATE_GRANTED
17060                     && (!canAdminGrantSensorsPermissions() || isCallerDelegate(caller))) {
17061                 if (mInjector.isChangeEnabled(THROW_SECURITY_EXCEPTION_FOR_SENSOR_PERMISSIONS,
17062                         caller.getPackageName(), caller.getUserId())) {
17063                     throw new SecurityException(
17064                             "Caller not permitted to grant sensor permissions.");
17065                 } else {
17066                     // This is to match the legacy behaviour.
17067                     callback.sendResult(Bundle.EMPTY);
17068                     return;
17069                 }
17070             }
17071             // Check all the states where Exceptions aren't thrown but the permission
17072             // isn't granted either.
17073             if (!canGrantPermission(caller, permission, packageName)) {
17074                 callback.sendResult(null);
17075                 return;
17076             }
17077         } else {
17078             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
17079                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)
17080                     || isFinancedDeviceOwner(caller)))
17081                     || (caller.hasPackage() && isCallerDelegate(caller,
17082                     DELEGATION_PERMISSION_GRANT)));
17083             synchronized (getLockObject()) {
17084                 long ident = mInjector.binderClearCallingIdentity();
17085                 try {
17086                     boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
17087                             >= android.os.Build.VERSION_CODES.Q;
17088                     if (!isPostQAdmin) {
17089                         // Legacy admins assume that they cannot control pre-M apps
17090                         if (getTargetSdk(packageName, caller.getUserId())
17091                                 < android.os.Build.VERSION_CODES.M) {
17092                             callback.sendResult(null);
17093                             return;
17094                         }
17095                     }
17096                     if (!isRuntimePermission(permission)) {
17097                         callback.sendResult(null);
17098                         return;
17099                     }
17100                 } catch (SecurityException e) {
17101                     Slogf.e(LOG_TAG, "Could not set permission grant state", e);
17102                     callback.sendResult(null);
17103                 } finally {
17104                     mInjector.binderRestoreCallingIdentity(ident);
17105                 }
17106             }
17107         }
17108         // TODO(b/278710449): enable when we stop policy enforecer callback from blocking the main
17109         //  thread
17110         if (false) {
17111             // TODO(b/266924257): decide how to handle the internal state if the package doesn't
17112             //  exist, or the permission isn't requested by the app, because we could end up with
17113             //  inconsistent state between the policy engine and package manager. Also a package
17114             //  might get removed or has it's permission updated after we've set the policy.
17115             if (grantState == PERMISSION_GRANT_STATE_DEFAULT) {
17116                 mDevicePolicyEngine.removeLocalPolicy(
17117                         PolicyDefinition.PERMISSION_GRANT(packageName, permission),
17118                         enforcingAdmin,
17119                         caller.getUserId());
17120             } else {
17121                 mDevicePolicyEngine.setLocalPolicy(
17122                         PolicyDefinition.PERMISSION_GRANT(packageName, permission),
17123                         enforcingAdmin,
17124                         new IntegerPolicyValue(grantState),
17125                         caller.getUserId());
17126             }
17127             int newState = mInjector.binderWithCleanCallingIdentity(() ->
17128                     getPermissionGrantStateForUser(
17129                             packageName, permission, caller, caller.getUserId()));
17130             if (newState == grantState) {
17131                 callback.sendResult(Bundle.EMPTY);
17132             } else {
17133                 callback.sendResult(null);
17134             }
17135         } else {
17136             synchronized (getLockObject()) {
17137                 long ident = mInjector.binderClearCallingIdentity();
17138                 try {
17139                     boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
17140                             >= android.os.Build.VERSION_CODES.Q;
17141                     if (grantState == PERMISSION_GRANT_STATE_GRANTED
17142                             || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED
17143                             || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
17144                         AdminPermissionControlParams permissionParams =
17145                                 new AdminPermissionControlParams(packageName, permission,
17146                                         grantState,
17147                                         canAdminGrantSensorsPermissions());
17148                         mInjector.getPermissionControllerManager(caller.getUserHandle())
17149                                 .setRuntimePermissionGrantStateByDeviceAdmin(
17150                                         caller.getPackageName(),
17151                                         permissionParams, mContext.getMainExecutor(),
17152                                         (permissionWasSet) -> {
17153                                             if (isPostQAdmin && !permissionWasSet) {
17154                                                 callback.sendResult(null);
17155                                                 return;
17156                                             }
17157                                             callback.sendResult(Bundle.EMPTY);
17158                                         });
17159                     }
17160                 } catch (SecurityException e) {
17161                     Slogf.e(LOG_TAG, "Could not set permission grant state", e);
17162 
17163                     callback.sendResult(null);
17164                 } finally {
17165                     mInjector.binderRestoreCallingIdentity(ident);
17166                 }
17167             }
17168         }
17169         DevicePolicyEventLogger.createEvent(DevicePolicyEnums.SET_PERMISSION_GRANT_STATE)
17170                 .setAdmin(caller.getPackageName())
17171                 .setStrings(permission)
17172                 .setInt(grantState)
17173                 .setBoolean(/* isDelegate */ isCallerDelegate(caller))
17174                 .write();
17175     }
17176 
17177     private static final List<String> SENSOR_PERMISSIONS = new ArrayList<>();
17178     {
17179         SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
17180         SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
17181         SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_COARSE_LOCATION);
17182         SENSOR_PERMISSIONS.add(Manifest.permission.CAMERA);
17183         SENSOR_PERMISSIONS.add(Manifest.permission.RECORD_AUDIO);
17184         SENSOR_PERMISSIONS.add(Manifest.permission.ACTIVITY_RECOGNITION);
17185         SENSOR_PERMISSIONS.add(Manifest.permission.BODY_SENSORS);
17186         SENSOR_PERMISSIONS.add(Manifest.permission.BACKGROUND_CAMERA);
17187         SENSOR_PERMISSIONS.add(Manifest.permission.RECORD_BACKGROUND_AUDIO);
17188         SENSOR_PERMISSIONS.add(Manifest.permission.BODY_SENSORS_BACKGROUND);
17189     }
17190 
canGrantPermission(CallerIdentity caller, String permission, String targetPackageName)17191     private boolean canGrantPermission(CallerIdentity caller, String permission,
17192             String targetPackageName) {
17193         boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
17194                 >= android.os.Build.VERSION_CODES.Q;
17195         if (!isPostQAdmin) {
17196             // Legacy admins assume that they cannot control pre-M apps
17197             if (getTargetSdk(targetPackageName, caller.getUserId())
17198                     < android.os.Build.VERSION_CODES.M) {
17199                 return false;
17200             }
17201         }
17202         if (!isRuntimePermission(permission)) {
17203             return false;
17204         }
17205         return true;
17206     }
17207 
enforcePermissionGrantStateOnFinancedDevice( String packageName, String permission)17208     private void enforcePermissionGrantStateOnFinancedDevice(
17209             String packageName, String permission) {
17210         if (!Manifest.permission.READ_PHONE_STATE.equals(permission)) {
17211             throw new SecurityException(permission + " cannot be used when managing a financed"
17212                     + " device for permission grant state");
17213         } else if (!mOwners.getDeviceOwnerPackageName().equals(packageName)) {
17214             throw new SecurityException("Device owner package is the only package that can be used"
17215                     + " for permission grant state when managing a financed device");
17216         }
17217     }
17218 
17219     @Override
getPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission)17220     public int getPermissionGrantState(ComponentName admin, String callerPackage,
17221             String packageName, String permission) throws RemoteException {
17222         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
17223         if (isUnicornFlagEnabled()) {
17224             enforceCanQuery(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, caller.getPackageName(),
17225                     caller.getUserId());
17226         } else {
17227             Preconditions.checkCallAuthorization(isSystemUid(caller) || (caller.hasAdminComponent()
17228                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)
17229                     || isFinancedDeviceOwner(caller)))
17230                     || (caller.hasPackage() && isCallerDelegate(caller,
17231                     DELEGATION_PERMISSION_GRANT)));
17232         }
17233 
17234         synchronized (getLockObject()) {
17235             if (isFinancedDeviceOwner(caller)) {
17236                 enforcePermissionGrantStateOnFinancedDevice(packageName, permission);
17237             }
17238             return mInjector.binderWithCleanCallingIdentity(() -> getPermissionGrantStateForUser(
17239                     packageName, permission, caller, caller.getUserId()));
17240         }
17241     }
17242 
getPermissionGrantStateForUser( String packageName, String permission, CallerIdentity caller, int userId)17243     private int getPermissionGrantStateForUser(
17244             String packageName, String permission, CallerIdentity caller, int userId)
17245             throws RemoteException {
17246         int granted;
17247         if (getTargetSdk(caller.getPackageName(), caller.getUserId())
17248                 < android.os.Build.VERSION_CODES.Q) {
17249             // The per-Q behavior was to not check the app-ops state.
17250             granted = mIPackageManager.checkPermission(permission, packageName, userId);
17251         } else {
17252             try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
17253                 var packageState = snapshot.getPackageStates().get(packageName);
17254                 if (packageState == null) {
17255                     Slog.w(LOG_TAG, "Can't get permission state for missing package "
17256                             + packageName);
17257                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
17258                 } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
17259                     Slog.w(LOG_TAG, "Can't get permission state for uninstalled package "
17260                             + packageName);
17261                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
17262                 } else {
17263                     if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
17264                             PermissionChecker.PID_UNKNOWN,
17265                             UserHandle.getUid(userId, packageState.getAppId()), packageName)
17266                             != PermissionChecker.PERMISSION_GRANTED) {
17267                         granted = PackageManager.PERMISSION_DENIED;
17268                     } else {
17269                         granted = PackageManager.PERMISSION_GRANTED;
17270                     }
17271 
17272                 }
17273             }
17274         }
17275         int permFlags = mInjector.getPackageManager().getPermissionFlags(
17276                 permission, packageName, UserHandle.of(userId));
17277         if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
17278                 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
17279             // Not controlled by policy
17280             return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
17281         } else {
17282             // Policy controlled so return result based on permission grant state
17283             return granted == PackageManager.PERMISSION_GRANTED
17284                     ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
17285                     : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
17286         }
17287     }
17288 
isPackageInstalledForUser(String packageName, int userHandle)17289     boolean isPackageInstalledForUser(String packageName, int userHandle) {
17290         return mInjector.binderWithCleanCallingIdentity(() -> {
17291             try {
17292                 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
17293                         userHandle);
17294                 return (pi != null) && (pi.applicationInfo.flags != 0);
17295             } catch (RemoteException re) {
17296                 throw new RuntimeException("Package manager has died", re);
17297             }
17298         });
17299     }
17300 
17301     private boolean isRuntimePermission(String permissionName) {
17302         try {
17303             final PackageManager packageManager = mInjector.getPackageManager();
17304             PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
17305             return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17306                     == PermissionInfo.PROTECTION_DANGEROUS;
17307         } catch (NameNotFoundException e) {
17308             return false;
17309         }
17310     }
17311 
17312     @Override
17313     public boolean isProvisioningAllowed(String action, String packageName) {
17314         Objects.requireNonNull(packageName);
17315         final CallerIdentity caller = getCallerIdentity();
17316         final long ident = mInjector.binderClearCallingIdentity();
17317         try {
17318             final List<String> callerUidPackageNames = Arrays.asList(
17319                     mInjector.getPackageManager().getPackagesForUid(caller.getUid()));
17320             Preconditions.checkArgument(callerUidPackageNames.contains(packageName),
17321                     "Caller uid doesn't match the one for the provided package.");
17322 
17323             return checkProvisioningPreconditionSkipPermission(action, packageName, caller.getUserId())
17324                     == STATUS_OK;
17325         } finally {
17326             mInjector.binderRestoreCallingIdentity(ident);
17327         }
17328     }
17329 
17330     @Override
17331     public int checkProvisioningPrecondition(String action, String packageName) {
17332         Objects.requireNonNull(packageName, "packageName is null");
17333         final CallerIdentity caller = getCallerIdentity();
17334         Preconditions.checkCallAuthorization(
17335                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
17336 
17337         long originalId = mInjector.binderClearCallingIdentity();
17338         try {
17339             return checkProvisioningPreconditionSkipPermission(
17340                     action, packageName, caller.getUserId());
17341         } finally {
17342             mInjector.binderRestoreCallingIdentity(originalId);
17343         }
17344 
17345     }
17346     private int checkProvisioningPreconditionSkipPermission(String action,
17347             String packageName, int userId) {
17348         if (!mHasFeature) {
17349             logMissingFeatureAction("Cannot check provisioning for action " + action);
17350             return STATUS_DEVICE_ADMIN_NOT_SUPPORTED;
17351         }
17352         if (!isProvisioningAllowed()) {
17353             return STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
17354         }
17355         final int code = checkProvisioningPreConditionSkipPermissionNoLog(
17356                 action, packageName, userId);
17357         if (code != STATUS_OK) {
17358             Slogf.d(LOG_TAG, "checkProvisioningPreCondition(" + action + ", " + packageName
17359                     + ") failed: "
17360                     + computeProvisioningErrorString(code, mInjector.userHandleGetCallingUserId()));
17361         }
17362         return code;
17363     }
17364 
17365     /**
17366      *  Checks if provisioning is allowed during regular usage (non-developer/CTS). This could
17367      *  return {@code false} if the device has an overlaid config value set to false. If not set,
17368      *  the default is true.
17369      */
17370     private boolean isProvisioningAllowed() {
17371         boolean isDeveloperMode = isDeveloperMode(mContext);
17372         boolean isProvisioningAllowedForNormalUsers = SystemProperties.getBoolean(
17373                 ALLOW_USER_PROVISIONING_KEY, /* defValue= */ true);
17374 
17375         return isDeveloperMode || isProvisioningAllowedForNormalUsers;
17376     }
17377 
17378     private static boolean isDeveloperMode(Context context) {
17379         return Global.getInt(context.getContentResolver(), Global.ADB_ENABLED, 0) > 0;
17380     }
17381 
17382     private int checkProvisioningPreConditionSkipPermissionNoLog(String action,
17383             String packageName, int userId) {
17384         if (action != null) {
17385             switch (action) {
17386                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
17387                     return checkManagedProfileProvisioningPreCondition(packageName, userId);
17388                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
17389                 case DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE:
17390                     return checkDeviceOwnerProvisioningPreCondition(userId);
17391             }
17392         }
17393         throw new IllegalArgumentException("Unknown provisioning action " + action);
17394     }
17395 
17396     /**
17397      * The device owner can only be set before the setup phase of the primary user has completed,
17398      * except for adb command if no accounts or additional users are present on the device.
17399      */
17400     private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
17401             @UserIdInt int deviceOwnerUserId, @UserIdInt int callingUserId, boolean isAdb,
17402             boolean hasIncompatibleAccountsOrNonAdb) {
17403         if (mOwners.hasDeviceOwner()) {
17404             return STATUS_HAS_DEVICE_OWNER;
17405         }
17406         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
17407             return STATUS_USER_HAS_PROFILE_OWNER;
17408         }
17409 
17410         if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
17411             return STATUS_USER_NOT_RUNNING;
17412         }
17413         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
17414             return STATUS_HAS_PAIRED;
17415         }
17416 
17417         boolean isHeadlessSystemUserMode = mInjector.userManagerIsHeadlessSystemUserMode();
17418 
17419         if (isHeadlessSystemUserMode) {
17420             if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
17421                 Slogf.e(LOG_TAG, "In headless system user mode, "
17422                         + "device owner can only be set on headless system user.");
17423                 return STATUS_NOT_SYSTEM_USER;
17424             }
17425 
17426             if (owner != null) {
17427                 DeviceAdminInfo adminInfo = findAdmin(
17428                         owner, deviceOwnerUserId, /* throwForMissingPermission= */ false);
17429 
17430                 if (adminInfo.getHeadlessDeviceOwnerMode()
17431                         != HEADLESS_DEVICE_OWNER_MODE_AFFILIATED) {
17432                     return STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED;
17433                 }
17434             }
17435         }
17436 
17437         if (isAdb) {
17438             // If shell command runs after user setup completed check device status. Otherwise, OK.
17439             if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
17440                 // DO can be setup only if there are no users which are neither created by default
17441                 // nor marked as FOR_TESTING
17442 
17443                 if (nonTestNonPrecreatedUsersExist()) {
17444                     return STATUS_NONSYSTEM_USER_EXISTS;
17445                 }
17446 
17447                 int currentForegroundUser = getCurrentForegroundUserId();
17448                 if (callingUserId != currentForegroundUser
17449                         && mInjector.userManagerIsHeadlessSystemUserMode()
17450                         && currentForegroundUser == UserHandle.USER_SYSTEM) {
17451                     Slogf.wtf(LOG_TAG, "In headless system user mode, "
17452                             + "current user cannot be system user when setting device owner");
17453                     return STATUS_SYSTEM_USER;
17454                 }
17455                 if (hasIncompatibleAccountsOrNonAdb) {
17456                     return STATUS_ACCOUNTS_NOT_EMPTY;
17457                 }
17458             }
17459             return STATUS_OK;
17460         } else {
17461             // DO has to be user 0
17462             if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
17463                 return STATUS_NOT_SYSTEM_USER;
17464             }
17465             // Only provision DO before setup wizard completes
17466             if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
17467                 return STATUS_USER_SETUP_COMPLETED;
17468             }
17469             return STATUS_OK;
17470         }
17471     }
17472 
17473     /**
17474      * True if there are any users on the device which were not setup by default (1 usually, 2 for
17475      * devices with a headless system user) and also are not marked as FOR_TESTING.
17476      */
17477     private boolean nonTestNonPrecreatedUsersExist() {
17478         int allowedUsers = UserManager.isHeadlessSystemUserMode() ? 2 : 1;
17479         return mUserManagerInternal.getUsers(/* excludeDying= */ true).stream()
17480                 .filter(u -> !u.isForTesting())
17481                 .count() > allowedUsers;
17482     }
17483 
17484     private int checkDeviceOwnerProvisioningPreCondition(@UserIdInt int callingUserId) {
17485         synchronized (getLockObject()) {
17486             final int deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode()
17487                     ? UserHandle.USER_SYSTEM
17488                     : callingUserId;
17489             Slogf.i(LOG_TAG, "Calling user %d, device owner will be set on user %d",
17490                     callingUserId, deviceOwnerUserId);
17491             // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
17492             return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
17493                     deviceOwnerUserId, callingUserId, /* isAdb= */ false,
17494                     /* hasIncompatibleAccountsOrNonAdb=*/ true);
17495         }
17496     }
17497 
17498     private int checkManagedProfileProvisioningPreCondition(String packageName,
17499             @UserIdInt int callingUserId) {
17500         if (!hasFeatureManagedUsers()) {
17501             return STATUS_MANAGED_USERS_NOT_SUPPORTED;
17502         }
17503         if (getProfileOwnerAsUser(callingUserId) != null) {
17504             // Managed user cannot have a managed profile.
17505             return STATUS_USER_HAS_PROFILE_OWNER;
17506         }
17507 
17508         final long ident = mInjector.binderClearCallingIdentity();
17509         try {
17510             final UserHandle callingUserHandle = UserHandle.of(callingUserId);
17511             final boolean hasDeviceOwner;
17512             synchronized (getLockObject()) {
17513                 hasDeviceOwner = getDeviceOwnerAdminLocked() != null;
17514             }
17515 
17516             final boolean addingProfileRestricted = mUserManager.hasUserRestriction(
17517                     UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserHandle);
17518 
17519             if (mUserManager.getUserInfo(callingUserId).isProfile()) {
17520                 Slogf.i(LOG_TAG, "Calling user %d is a profile, cannot add another.",
17521                         callingUserId);
17522                 // The check is called from inside a managed profile. A managed profile cannot
17523                 // be provisioned from within another managed profile.
17524                 return STATUS_CANNOT_ADD_MANAGED_PROFILE;
17525             }
17526 
17527             // If there's a device owner, the restriction on adding a managed profile must be set.
17528             if (hasDeviceOwner && !addingProfileRestricted) {
17529                 Slogf.wtf(LOG_TAG, "Has a device owner but no restriction on adding a profile.");
17530             }
17531 
17532             // Do not allow adding a managed profile if there's a restriction.
17533             if (addingProfileRestricted) {
17534                 Slogf.i(LOG_TAG, "Adding a profile is restricted: User %s Has device owner? %b",
17535                         callingUserHandle, hasDeviceOwner);
17536                 return STATUS_CANNOT_ADD_MANAGED_PROFILE;
17537             }
17538 
17539             // Bail out if we are trying to provision a work profile but one already exists.
17540             if (!mUserManager.canAddMoreManagedProfiles(
17541                     callingUserId, /* allowedToRemoveOne= */ false)) {
17542                 Slogf.i(LOG_TAG, "Cannot add more managed profiles.");
17543                 return STATUS_CANNOT_ADD_MANAGED_PROFILE;
17544             }
17545         } finally {
17546             mInjector.binderRestoreCallingIdentity(ident);
17547         }
17548         return STATUS_OK;
17549     }
17550 
17551     private void checkIsDeviceOwner(CallerIdentity caller) {
17552         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller), caller.getUid()
17553                 + " is not device owner");
17554     }
17555 
17556     /**
17557      * Return device owner or profile owner set on a given user.
17558      */
17559     private @Nullable ComponentName getOwnerComponent(int userId) {
17560         synchronized (getLockObject()) {
17561             if (mOwners.getDeviceOwnerUserId() == userId) {
17562                 return mOwners.getDeviceOwnerComponent();
17563             }
17564             if (mOwners.hasProfileOwner(userId)) {
17565                 return mOwners.getProfileOwnerComponent(userId);
17566             }
17567         }
17568         return null;
17569     }
17570 
17571     private boolean hasFeatureManagedUsers() {
17572         try {
17573             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
17574         } catch (RemoteException e) {
17575             return false;
17576         }
17577     }
17578 
17579     @Override
17580     public String getWifiMacAddress(ComponentName admin, String callerPackageName) {
17581 //        if (!isPermissionCheckFlagEnabled()) {
17582             Objects.requireNonNull(admin, "ComponentName is null");
17583 //        }
17584 
17585         final CallerIdentity caller = getCallerIdentity(admin, callerPackageName);
17586 //        if (isPermissionCheckFlagEnabled()) {
17587 //            enforcePermission(MANAGE_DEVICE_POLICY_WIFI, UserHandle.USER_ALL);
17588 //        } else {
17589             Preconditions.checkCallAuthorization(
17590                     isDefaultDeviceOwner(caller)
17591                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
17592 //        }
17593 
17594         return mInjector.binderWithCleanCallingIdentity(() -> {
17595             String[] macAddresses = mInjector.getWifiManager().getFactoryMacAddresses();
17596             if (macAddresses == null) {
17597                 return null;
17598             }
17599             DevicePolicyEventLogger
17600                     .createEvent(DevicePolicyEnums.GET_WIFI_MAC_ADDRESS)
17601                     .setAdmin(caller.getPackageName())
17602                     .write();
17603             return macAddresses.length > 0 ? macAddresses[0] : null;
17604         });
17605     }
17606 
17607     /**
17608      * Returns the target sdk version number that the given packageName was built for
17609      * in the given user.
17610      */
17611     private int getTargetSdk(String packageName, int userId) {
17612         final ApplicationInfo ai;
17613         try {
17614             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
17615             return ai == null ? 0 : ai.targetSdkVersion;
17616         } catch (RemoteException e) {
17617             // Shouldn't happen
17618             Slogf.wtf(LOG_TAG, "Error getting application info", e);
17619             return 0;
17620         }
17621     }
17622 
17623     @Override
17624     public boolean isManagedProfile(ComponentName admin) {
17625         Objects.requireNonNull(admin, "ComponentName is null");
17626 
17627         final CallerIdentity caller = getCallerIdentity(admin);
17628         Preconditions.checkCallAuthorization(
17629                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
17630 
17631         return isManagedProfile(caller.getUserId());
17632     }
17633 
17634     @Override
17635     public void reboot(ComponentName admin) {
17636         Objects.requireNonNull(admin, "ComponentName is null");
17637         final CallerIdentity caller = getCallerIdentity(admin);
17638         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
17639         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REBOOT);
17640         mInjector.binderWithCleanCallingIdentity(() -> {
17641             // Make sure there are no ongoing calls on the device.
17642             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
17643                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
17644             }
17645             DevicePolicyEventLogger
17646                     .createEvent(DevicePolicyEnums.REBOOT)
17647                     .setAdmin(admin)
17648                     .write();
17649             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
17650         });
17651     }
17652 
17653     @Override
17654     public void setShortSupportMessage(@Nullable ComponentName who, String callerPackageName,
17655             CharSequence message) {
17656         if (!mHasFeature) {
17657             return;
17658         }
17659         CallerIdentity caller;
17660         ActiveAdmin admin;
17661 
17662         message = truncateIfLonger(message, MAX_SHORT_SUPPORT_MESSAGE_LENGTH);
17663 
17664         if (isPermissionCheckFlagEnabled()) {
17665             caller = getCallerIdentity(who, callerPackageName);
17666             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
17667                     who,
17668                     MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
17669                     caller.getPackageName(),
17670                     caller.getUserId());
17671             admin = enforcingAdmin.getActiveAdmin();
17672         } else {
17673             caller = getCallerIdentity(who);
17674             Objects.requireNonNull(who, "ComponentName is null");
17675             synchronized (getLockObject()) {
17676                 admin = getActiveAdminForUidLocked(who, caller.getUid());
17677             }
17678         }
17679 
17680         synchronized (getLockObject()) {
17681             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
17682                 admin.shortSupportMessage = message;
17683                 saveSettingsLocked(caller.getUserId());
17684             }
17685         }
17686         DevicePolicyEventLogger
17687                 .createEvent(DevicePolicyEnums.SET_SHORT_SUPPORT_MESSAGE)
17688                 .setAdmin(caller.getPackageName())
17689                 .write();
17690     }
17691 
17692     @Override
17693     public CharSequence getShortSupportMessage(@Nullable ComponentName who,
17694             String callerPackageName) {
17695         if (!mHasFeature) {
17696             return null;
17697         }
17698         CallerIdentity caller;
17699         ActiveAdmin admin;
17700 
17701         if (isPermissionCheckFlagEnabled()) {
17702             caller = getCallerIdentity(who, callerPackageName);
17703             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
17704                     who,
17705                     MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
17706                     caller.getPackageName(),
17707                     caller.getUserId());
17708             admin = enforcingAdmin.getActiveAdmin();
17709         } else {
17710             caller = getCallerIdentity(who);
17711             Objects.requireNonNull(who, "ComponentName is null");
17712             synchronized (getLockObject()) {
17713                 admin = getActiveAdminForUidLocked(who, caller.getUid());
17714             }
17715         }
17716         return admin.shortSupportMessage;
17717     }
17718 
17719     @Override
17720     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
17721         if (!mHasFeature) {
17722             return;
17723         }
17724 
17725         message = truncateIfLonger(message, MAX_LONG_SUPPORT_MESSAGE_LENGTH);
17726 
17727         Objects.requireNonNull(who, "ComponentName is null");
17728         final CallerIdentity caller = getCallerIdentity(who);
17729         synchronized (getLockObject()) {
17730             ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
17731             if (!TextUtils.equals(admin.longSupportMessage, message)) {
17732                 admin.longSupportMessage = message;
17733                 saveSettingsLocked(caller.getUserId());
17734             }
17735         }
17736         DevicePolicyEventLogger
17737                 .createEvent(DevicePolicyEnums.SET_LONG_SUPPORT_MESSAGE)
17738                 .setAdmin(who)
17739                 .write();
17740     }
17741 
17742     @Override
17743     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
17744         if (!mHasFeature) {
17745             return null;
17746         }
17747         Objects.requireNonNull(who, "ComponentName is null");
17748         final CallerIdentity caller = getCallerIdentity(who);
17749         synchronized (getLockObject()) {
17750             ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
17751             return admin.longSupportMessage;
17752         }
17753     }
17754 
17755     @Override
17756     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
17757         if (!mHasFeature) {
17758             return null;
17759         }
17760         Objects.requireNonNull(who, "ComponentName is null");
17761         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
17762                 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user"));
17763 
17764         synchronized (getLockObject()) {
17765             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
17766             if (admin != null) {
17767                 return admin.shortSupportMessage;
17768             }
17769         }
17770         return null;
17771     }
17772 
17773     @Override
17774     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
17775         if (!mHasFeature) {
17776             return null;
17777         }
17778         Objects.requireNonNull(who, "ComponentName is null");
17779         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
17780                 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user"));
17781 
17782         synchronized (getLockObject()) {
17783             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
17784             if (admin != null) {
17785                 return admin.longSupportMessage;
17786             }
17787         }
17788         return null;
17789     }
17790 
17791     @Override
17792     public void setOrganizationColor(@NonNull ComponentName who, int color) {
17793         if (!mHasFeature) {
17794             return;
17795         }
17796         Objects.requireNonNull(who, "ComponentName is null");
17797 
17798         final CallerIdentity caller = getCallerIdentity(who);
17799         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
17800         Preconditions.checkCallAuthorization(isProfileOwner(caller));
17801 
17802         synchronized (getLockObject()) {
17803             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
17804             admin.organizationColor = color;
17805             saveSettingsLocked(caller.getUserId());
17806         }
17807         DevicePolicyEventLogger
17808                 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_COLOR)
17809                 .setAdmin(caller.getComponentName())
17810                 .write();
17811     }
17812 
17813     @Override
17814     public void setOrganizationColorForUser(int color, int userId) {
17815         if (!mHasFeature) {
17816             return;
17817         }
17818         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
17819 
17820         final CallerIdentity caller = getCallerIdentity();
17821         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
17822         Preconditions.checkCallAuthorization(canManageUsers(caller));
17823         Preconditions.checkCallAuthorization(isManagedProfile(userId), "You can not "
17824                 + "set organization color outside a managed profile, userId = %d", userId);
17825 
17826         synchronized (getLockObject()) {
17827             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
17828             admin.organizationColor = color;
17829             saveSettingsLocked(userId);
17830         }
17831     }
17832 
17833     @Override
17834     public int getOrganizationColor(@NonNull ComponentName who) {
17835         if (!mHasFeature) {
17836             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
17837         }
17838         Objects.requireNonNull(who, "ComponentName is null");
17839 
17840         final CallerIdentity caller = getCallerIdentity(who);
17841         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
17842         Preconditions.checkCallAuthorization(isProfileOwner(caller));
17843 
17844         synchronized (getLockObject()) {
17845             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
17846             return admin.organizationColor;
17847         }
17848     }
17849 
17850     @Override
17851     public int getOrganizationColorForUser(int userHandle) {
17852         if (!mHasFeature) {
17853             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
17854         }
17855         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
17856 
17857         final CallerIdentity caller = getCallerIdentity();
17858         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
17859         Preconditions.checkCallAuthorization(isManagedProfile(userHandle), "You can "
17860                 + "not get organization color outside a managed profile, userId = %d", userHandle);
17861 
17862         synchronized (getLockObject()) {
17863             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
17864             return (profileOwner != null)
17865                     ? profileOwner.organizationColor
17866                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
17867         }
17868     }
17869 
17870     @Override
17871     public void setOrganizationName(@Nullable ComponentName who, String callerPackageName,
17872             CharSequence text) {
17873         if (!mHasFeature) {
17874             return;
17875         }
17876         CallerIdentity caller = getCallerIdentity(who);
17877         ActiveAdmin admin = null;
17878 
17879         if (isPermissionCheckFlagEnabled()) {
17880             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
17881                     who,
17882                     MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
17883                     caller.getPackageName(),
17884                     caller.getUserId());
17885             admin = enforcingAdmin.getActiveAdmin();
17886         } else {
17887             Objects.requireNonNull(who, "ComponentName is null");
17888             Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
17889         }
17890 
17891         text = truncateIfLonger(text, MAX_ORG_NAME_LENGTH);
17892 
17893         synchronized (getLockObject()) {
17894             if (!isPermissionCheckFlagEnabled()) {
17895                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
17896             }
17897             if (!TextUtils.equals(admin.organizationName, text)) {
17898                 admin.organizationName = (text == null || text.length() == 0)
17899                         ? null : text.toString();
17900                 saveSettingsLocked(caller.getUserId());
17901             }
17902         }
17903     }
17904 
17905     @Override
17906     public CharSequence getOrganizationName(@Nullable ComponentName who, String callerPackageName) {
17907         if (!mHasFeature) {
17908             return null;
17909         }
17910         CallerIdentity caller = getCallerIdentity(who);
17911         ActiveAdmin admin;
17912 
17913         if (isPermissionCheckFlagEnabled()) {
17914             EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
17915                     who,
17916                     MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
17917                     caller.getPackageName(),
17918                     caller.getUserId());
17919             admin = enforcingAdmin.getActiveAdmin();
17920         } else {
17921             Objects.requireNonNull(who, "ComponentName is null");
17922             Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
17923             Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
17924 
17925             synchronized (getLockObject()) {
17926                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
17927             }
17928         }
17929 
17930         return admin.organizationName;
17931     }
17932 
17933     /**
17934      * This API is cached: invalidate with invalidateBinderCaches().
17935      */
17936     @Override
17937     public CharSequence getDeviceOwnerOrganizationName() {
17938         if (!mHasFeature) {
17939             return null;
17940         }
17941         final CallerIdentity caller = getCallerIdentity();
17942         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
17943                 || canManageUsers(caller) || isFinancedDeviceOwner(caller));
17944         synchronized (getLockObject()) {
17945             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
17946             return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
17947         }
17948     }
17949 
17950     /**
17951      * This API is cached: invalidate with invalidateBinderCaches().
17952      */
17953     @Override
17954     public CharSequence getOrganizationNameForUser(int userHandle) {
17955         if (!mHasFeature) {
17956             return null;
17957         }
17958         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
17959 
17960         final CallerIdentity caller = getCallerIdentity();
17961         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
17962         Preconditions.checkCallAuthorization(canManageUsers(caller));
17963         Preconditions.checkCallAuthorization(isManagedProfile(userHandle),
17964                 "You can not get organization name outside a managed profile, userId = %d",
17965                 userHandle);
17966 
17967         synchronized (getLockObject()) {
17968             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
17969             return (profileOwner != null)
17970                     ? profileOwner.organizationName
17971                     : null;
17972         }
17973     }
17974 
17975     @Override
17976     public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) {
17977         Objects.requireNonNull(who);
17978         Objects.requireNonNull(packageNames);
17979         final CallerIdentity caller = getCallerIdentity(who);
17980         Preconditions.checkCallAuthorization(
17981                 isDefaultDeviceOwner(caller) || isProfileOwner(caller),
17982                 "Admin %s does not own the profile", caller.getComponentName());
17983 
17984         if (!mHasFeature) {
17985             return packageNames;
17986         }
17987         synchronized (getLockObject()) {
17988             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
17989             return mInjector.binderWithCleanCallingIdentity(() -> {
17990                 final List<String> excludedPkgs = removeInvalidPkgsForMeteredDataRestriction(
17991                         caller.getUserId(), packageNames);
17992                 admin.meteredDisabledPackages = packageNames;
17993                 pushMeteredDisabledPackages(caller.getUserId());
17994                 saveSettingsLocked(caller.getUserId());
17995                 return excludedPkgs;
17996             });
17997         }
17998     }
17999 
18000     private List<String> removeInvalidPkgsForMeteredDataRestriction(
18001             int userId, List<String> pkgNames) {
18002         final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId);
18003         final List<String> excludedPkgs = new ArrayList<>();
18004         for (int i = pkgNames.size() - 1; i >= 0; --i) {
18005             final String pkgName = pkgNames.get(i);
18006             // If the package is an active admin, don't restrict it.
18007             if (activeAdmins.contains(pkgName)) {
18008                 excludedPkgs.add(pkgName);
18009                 continue;
18010             }
18011             // If the package doesn't exist, don't restrict it.
18012             try {
18013                 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) {
18014                     excludedPkgs.add(pkgName);
18015                 }
18016             } catch (RemoteException e) {
18017                 // Should not happen
18018             }
18019         }
18020         pkgNames.removeAll(excludedPkgs);
18021         return excludedPkgs;
18022     }
18023 
18024     @Override
18025     public List<String> getMeteredDataDisabledPackages(ComponentName who) {
18026         Objects.requireNonNull(who);
18027 
18028         if (!mHasFeature) {
18029             return new ArrayList<>();
18030         }
18031         final CallerIdentity caller = getCallerIdentity(who);
18032         Preconditions.checkCallAuthorization(
18033                 isDefaultDeviceOwner(caller) || isProfileOwner(caller),
18034                 "Admin %s does not own the profile", caller.getComponentName());
18035 
18036         synchronized (getLockObject()) {
18037             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
18038             return admin.meteredDisabledPackages == null
18039                     ? new ArrayList<>() : admin.meteredDisabledPackages;
18040         }
18041     }
18042 
18043     @Override
18044     public boolean isMeteredDataDisabledPackageForUser(ComponentName who,
18045             String packageName, int userId) {
18046         Objects.requireNonNull(who);
18047 
18048         if (!mHasFeature) {
18049             return false;
18050         }
18051         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
18052                 String.format(NOT_SYSTEM_CALLER_MSG, "query restricted pkgs for a specific user"));
18053 
18054         synchronized (getLockObject()) {
18055             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
18056             if (admin != null && admin.meteredDisabledPackages != null) {
18057                 return admin.meteredDisabledPackages.contains(packageName);
18058             }
18059         }
18060         return false;
18061     }
18062 
18063     @Override
18064     public void setProfileOwnerOnOrganizationOwnedDevice(ComponentName who, int userId,
18065             boolean isProfileOwnerOnOrganizationOwnedDevice) {
18066         if (!mHasFeature) {
18067             return;
18068         }
18069         // As the caller is the system, it must specify the component name of the profile owner
18070         // as a safety check.
18071         Objects.requireNonNull(who);
18072 
18073         final CallerIdentity caller = getCallerIdentity();
18074         // Only adb or system apps with the right permission can mark a profile owner on
18075         // organization-owned device.
18076         if (!(isAdb(caller) || hasCallingPermission(permission.MARK_DEVICE_ORGANIZATION_OWNED)
18077                 || hasCallingPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS))) {
18078             throw new SecurityException(
18079                     "Only the system can mark a profile owner of organization-owned device.");
18080         }
18081         // Only a test admin can be unmarked as a profile owner on an organization-owned device.
18082         synchronized (getLockObject()) {
18083             if (!isProfileOwnerOnOrganizationOwnedDevice && !isAdminTestOnlyLocked(who, userId)) {
18084                 throw new SecurityException("Only a test admin can be unmarked as a "
18085                         + "profile owner of organization-owned device.");
18086             }
18087         }
18088 
18089         if (isAdb(caller)) {
18090             if (hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, who)) {
18091                 throw new SecurityException(
18092                         "Can only be called from ADB if the device has no accounts.");
18093             }
18094         } else {
18095             if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
18096                 throw new IllegalStateException(
18097                         "Cannot mark profile owner as managing an organization-owned device after"
18098                                 + " set-up");
18099             }
18100         }
18101 
18102         // Grant access under lock.
18103         synchronized (getLockObject()) {
18104             setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(who, userId,
18105                     isProfileOwnerOnOrganizationOwnedDevice);
18106         }
18107     }
18108 
18109     @GuardedBy("getLockObject()")
18110     private void setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(
18111             ComponentName who, int userId, boolean isProfileOwnerOnOrganizationOwnedDevice) {
18112         // Make sure that the user has a profile owner and that the specified
18113         // component is the profile owner of that user.
18114         if (!isProfileOwner(who, userId)) {
18115             throw new IllegalArgumentException(String.format(
18116                     "Component %s is not a Profile Owner of user %d",
18117                     who.flattenToString(), userId));
18118         }
18119 
18120         Slogf.i(LOG_TAG, "%s %s as profile owner on organization-owned device for user %d",
18121                 isProfileOwnerOnOrganizationOwnedDevice ? "Marking" : "Unmarking",
18122                 who.flattenToString(), userId);
18123 
18124         // First, set restriction on removing the profile.
18125         mInjector.binderWithCleanCallingIdentity(() -> {
18126             // Clear restriction as user.
18127             final UserHandle parentUser = mUserManager.getProfileParent(UserHandle.of(userId));
18128             if (parentUser == null) {
18129                 throw new IllegalStateException(String.format("User %d is not a profile", userId));
18130             }
18131 
18132             mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
18133                     isProfileOwnerOnOrganizationOwnedDevice,
18134                     parentUser);
18135             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER,
18136                     isProfileOwnerOnOrganizationOwnedDevice,
18137                     parentUser);
18138         });
18139 
18140         // setProfileOwnerOfOrganizationOwnedDevice will trigger writing of the profile owner
18141         // data, no need to do it manually.
18142         mOwners.setProfileOwnerOfOrganizationOwnedDevice(userId,
18143                 isProfileOwnerOnOrganizationOwnedDevice);
18144     }
18145 
18146     private void pushMeteredDisabledPackages(int userId) {
18147         wtfIfInLock();
18148         mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages(
18149                 getMeteredDisabledPackages(userId), userId);
18150     }
18151 
18152     private Set<String> getMeteredDisabledPackages(int userId) {
18153         synchronized (getLockObject()) {
18154             final Set<String> restrictedPkgs = new ArraySet<>();
18155             final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
18156             if (admin != null && admin.meteredDisabledPackages != null) {
18157                 restrictedPkgs.addAll(admin.meteredDisabledPackages);
18158             }
18159 
18160             return restrictedPkgs;
18161         }
18162     }
18163 
18164     @Override
18165     public void setAffiliationIds(ComponentName admin, List<String> ids) {
18166         if (!mHasFeature) {
18167             return;
18168         }
18169         if (ids == null) {
18170             throw new IllegalArgumentException("ids must not be null");
18171         }
18172         for (String id : ids) {
18173             Preconditions.checkArgument(!TextUtils.isEmpty(id), "ids must not have empty string");
18174             enforceMaxStringLength(id, "affiliation id");
18175         }
18176 
18177         final Set<String> affiliationIds = new ArraySet<>(ids);
18178         final CallerIdentity caller = getCallerIdentity(admin);
18179         Preconditions.checkCallAuthorization(
18180                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
18181         final int callingUserId = caller.getUserId();
18182 
18183         synchronized (getLockObject()) {
18184             getUserData(callingUserId).mAffiliationIds = affiliationIds;
18185             saveSettingsLocked(callingUserId);
18186             mStateCache.setHasAffiliationWithDevice(callingUserId,
18187                     isUserAffiliatedWithDeviceLocked(callingUserId));
18188             if (callingUserId == UserHandle.USER_SYSTEM) {
18189                 resetAffiliationCacheLocked();
18190             } else if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin,
18191                     callingUserId)) {
18192                 // Affiliation ids specified by the device owner are additionally stored in
18193                 // UserHandle.USER_SYSTEM's DevicePolicyData.
18194                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
18195                 mStateCache.setHasAffiliationWithDevice(UserHandle.USER_SYSTEM, true);
18196                 saveSettingsLocked(UserHandle.USER_SYSTEM);
18197             }
18198 
18199             // Affiliation status for any user, not just the calling user, might have changed.
18200             // The device owner user will still be affiliated after changing its affiliation ids,
18201             // but as a result of that other users might become affiliated or un-affiliated.
18202             maybePauseDeviceWideLoggingLocked();
18203             maybeResumeDeviceWideLoggingLocked();
18204             maybeClearLockTaskPolicyLocked();
18205             updateAdminCanGrantSensorsPermissionCache(callingUserId);
18206         }
18207     }
18208 
18209     private void resetAffiliationCacheLocked() {
18210         mInjector.binderWithCleanCallingIdentity(() -> {
18211             for (UserInfo user : mUserManager.getUsers()) {
18212                 mStateCache.setHasAffiliationWithDevice(user.id,
18213                         isUserAffiliatedWithDeviceLocked(user.id));
18214             }
18215         });
18216     }
18217 
18218     @Override
18219     public List<String> getAffiliationIds(ComponentName admin) {
18220         if (!mHasFeature) {
18221             return Collections.emptyList();
18222         }
18223 
18224         Objects.requireNonNull(admin);
18225         final CallerIdentity caller = getCallerIdentity(admin);
18226         Preconditions.checkCallAuthorization(
18227                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
18228 
18229         synchronized (getLockObject()) {
18230             return new ArrayList<String>(getUserData(caller.getUserId()).mAffiliationIds);
18231         }
18232     }
18233 
18234     @Override
18235     public boolean isCallingUserAffiliated() {
18236         if (!mHasFeature) {
18237             return false;
18238         }
18239 
18240         synchronized (getLockObject()) {
18241             return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
18242         }
18243     }
18244 
18245     @Override
18246     public boolean isAffiliatedUser(@UserIdInt int userId) {
18247         if (!mHasFeature) {
18248             return false;
18249         }
18250         final CallerIdentity caller = getCallerIdentity();
18251         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
18252 
18253         return isUserAffiliatedWithDevice(userId);
18254     }
18255 
18256     private boolean isUserAffiliatedWithDevice(@UserIdInt int userId) {
18257         synchronized (getLockObject()) {
18258             return isUserAffiliatedWithDeviceLocked(userId);
18259         }
18260     }
18261 
18262     private boolean isUserAffiliatedWithDeviceLocked(@UserIdInt int userId) {
18263         if (!mOwners.hasDeviceOwner()) {
18264             return false;
18265         }
18266         if (userId == UserHandle.USER_SYSTEM) {
18267             // The system user is always affiliated in a DO device,
18268             // even if in headless system user mode.
18269             return true;
18270         }
18271         if (userId == mOwners.getDeviceOwnerUserId()) {
18272             // The user that the DO is installed on is always affiliated with the device.
18273             return true;
18274         }
18275 
18276         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
18277         if (profileOwner == null) {
18278             return false;
18279         }
18280 
18281         final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
18282         final Set<String> deviceAffiliationIds =
18283                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
18284         for (String id : userAffiliationIds) {
18285             if (deviceAffiliationIds.contains(id)) {
18286                 return true;
18287             }
18288         }
18289         return false;
18290     }
18291 
18292     private boolean areAllUsersAffiliatedWithDeviceLocked() {
18293         return mInjector.binderWithCleanCallingIdentity(() -> {
18294             final List<UserInfo> userInfos = mUserManager.getAliveUsers();
18295             for (int i = 0; i < userInfos.size(); i++) {
18296                 int userId = userInfos.get(i).id;
18297                 if (!isUserAffiliatedWithDeviceLocked(userId)) {
18298                     Slogf.d(LOG_TAG, "User id " + userId + " not affiliated.");
18299                     return false;
18300                 }
18301             }
18302             return true;
18303         });
18304     }
18305 
18306     private @UserIdInt int getSecurityLoggingEnabledUser() {
18307         synchronized (getLockObject()) {
18308             if (mOwners.hasDeviceOwner()) {
18309                 return UserHandle.USER_ALL;
18310             }
18311         }
18312         // TODO: Add check for permission-based
18313         return getOrganizationOwnedProfileUserId();
18314     }
18315 
18316     @Override
18317     public void setSecurityLoggingEnabled(ComponentName admin, String packageName,
18318             boolean enabled) {
18319         if (!mHasFeature) {
18320             return;
18321         }
18322         final CallerIdentity caller = getCallerIdentity(admin, packageName);
18323 
18324         synchronized (getLockObject()) {
18325             if (isPermissionCheckFlagEnabled()) {
18326                 enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
18327                         UserHandle.USER_ALL);
18328             } else {
18329                 if (admin != null) {
18330                     Preconditions.checkCallAuthorization(
18331                             isProfileOwnerOfOrganizationOwnedDevice(caller)
18332                                     || isDefaultDeviceOwner(caller));
18333                 } else {
18334                     // A delegate app passes a null admin component, which is expected
18335                     Preconditions.checkCallAuthorization(
18336                             isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
18337                 }
18338             }
18339 
18340             if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
18341                 return;
18342             }
18343             mInjector.securityLogSetLoggingEnabledProperty(enabled);
18344             if (enabled) {
18345                 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
18346                 maybePauseDeviceWideLoggingLocked();
18347             } else {
18348                 mSecurityLogMonitor.stop();
18349             }
18350         }
18351         DevicePolicyEventLogger
18352                 .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED)
18353                 .setAdmin(caller.getPackageName())
18354                 .setBoolean(enabled)
18355                 .write();
18356     }
18357 
18358     @Override
18359     public boolean isSecurityLoggingEnabled(ComponentName admin, String packageName) {
18360         if (!mHasFeature) {
18361             return false;
18362         }
18363 
18364         synchronized (getLockObject()) {
18365             if (!isSystemUid(getCallerIdentity())) {
18366                 final CallerIdentity caller = getCallerIdentity(admin, packageName);
18367                 if (isPermissionCheckFlagEnabled()) {
18368                     enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
18369                             caller.getPackageName(), UserHandle.USER_ALL);
18370                 } else {
18371                     if (admin != null) {
18372                         Preconditions.checkCallAuthorization(
18373                                 isProfileOwnerOfOrganizationOwnedDevice(caller)
18374                                         || isDefaultDeviceOwner(caller));
18375                     } else {
18376                         // A delegate app passes a null admin component, which is expected
18377                         Preconditions.checkCallAuthorization(
18378                                 isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
18379                     }
18380                 }
18381             }
18382             return mInjector.securityLogGetLoggingEnabledProperty();
18383         }
18384     }
18385 
18386     private void recordSecurityLogRetrievalTime() {
18387         synchronized (getLockObject()) {
18388             final long currentTime = System.currentTimeMillis();
18389             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
18390             if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
18391                 policyData.mLastSecurityLogRetrievalTime = currentTime;
18392                 saveSettingsLocked(UserHandle.USER_SYSTEM);
18393             }
18394         }
18395     }
18396 
18397     @Override
18398     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin,
18399             String packageName) {
18400         if (!mHasFeature) {
18401             return null;
18402         }
18403 
18404         final CallerIdentity caller = getCallerIdentity(admin, packageName);
18405         if (isPermissionCheckFlagEnabled()) {
18406             Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
18407                     || areAllUsersAffiliatedWithDeviceLocked());
18408             enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
18409                     UserHandle.USER_ALL);
18410         } else {
18411             if (admin != null) {
18412                 Preconditions.checkCallAuthorization(
18413                         isProfileOwnerOfOrganizationOwnedDevice(caller)
18414                                 || isDefaultDeviceOwner(caller));
18415             } else {
18416                 // A delegate app passes a null admin component, which is expected
18417                 Preconditions.checkCallAuthorization(
18418                         isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
18419             }
18420 
18421             Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
18422                     || areAllUsersAffiliatedWithDeviceLocked());
18423         }
18424 
18425         DevicePolicyEventLogger
18426                 .createEvent(DevicePolicyEnums.RETRIEVE_PRE_REBOOT_SECURITY_LOGS)
18427                 .setAdmin(caller.getPackageName())
18428                 .write();
18429 
18430         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
18431                 || !mInjector.securityLogGetLoggingEnabledProperty()) {
18432             return null;
18433         }
18434 
18435         recordSecurityLogRetrievalTime();
18436         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
18437         try {
18438             SecurityLog.readPreviousEvents(output);
18439             int enabledUser = getSecurityLoggingEnabledUser();
18440             if (enabledUser != UserHandle.USER_ALL) {
18441                 SecurityLog.redactEvents(output, enabledUser);
18442             }
18443             return new ParceledListSlice<SecurityEvent>(output);
18444         } catch (IOException e) {
18445             Slogf.w(LOG_TAG, "Fail to read previous events" , e);
18446             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
18447         }
18448     }
18449 
18450     @Override
18451     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin,
18452             String packageName) {
18453         if (!mHasFeature) {
18454             return null;
18455         }
18456 
18457         final CallerIdentity caller = getCallerIdentity(admin, packageName);
18458         if (isPermissionCheckFlagEnabled()) {
18459             Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
18460                     || areAllUsersAffiliatedWithDeviceLocked());
18461 
18462             enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
18463                     UserHandle.USER_ALL);
18464         } else {
18465             if (admin != null) {
18466                 Preconditions.checkCallAuthorization(
18467                         isProfileOwnerOfOrganizationOwnedDevice(caller)
18468                         || isDefaultDeviceOwner(caller));
18469             } else {
18470                 // A delegate app passes a null admin component, which is expected
18471                 Preconditions.checkCallAuthorization(
18472                         isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
18473             }
18474             Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
18475                     || areAllUsersAffiliatedWithDeviceLocked());
18476         }
18477 
18478         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
18479             return null;
18480         }
18481 
18482         recordSecurityLogRetrievalTime();
18483 
18484         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
18485         DevicePolicyEventLogger
18486                 .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS)
18487                 .setAdmin(caller.getPackageName())
18488                 .write();
18489         return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
18490     }
18491 
18492     @Override
18493     public long forceSecurityLogs() {
18494         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
18495                         || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS),
18496                 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call "
18497                         + "forceSecurityLogs");
18498         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
18499             throw new IllegalStateException("logging is not available");
18500         }
18501         return mSecurityLogMonitor.forceLogs();
18502     }
18503 
18504     @Override
18505     public boolean isUninstallInQueue(final String packageName) {
18506         final CallerIdentity caller = getCallerIdentity();
18507         Preconditions.checkCallAuthorization(
18508                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
18509 
18510         UserPackage packageUserPair = UserPackage.of(caller.getUserId(), packageName);
18511         synchronized (getLockObject()) {
18512             return mPackagesToRemove.contains(packageUserPair);
18513         }
18514     }
18515 
18516     @Override
18517     public void uninstallPackageWithActiveAdmins(final String packageName) {
18518         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
18519 
18520         final CallerIdentity caller = getCallerIdentity();
18521         Preconditions.checkCallAuthorization(
18522                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
18523 
18524         final int userId = caller.getUserId();
18525         enforceUserUnlocked(userId);
18526 
18527         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
18528         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
18529             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
18530         }
18531 
18532         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
18533         if (getDeviceOwnerUserId() == userId && deviceOwner != null
18534                 && packageName.equals(deviceOwner.getPackageName())) {
18535             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
18536         }
18537 
18538         final UserPackage packageUserPair = UserPackage.of(userId, packageName);
18539         synchronized (getLockObject()) {
18540             mPackagesToRemove.add(packageUserPair);
18541         }
18542 
18543         // All active admins on the user.
18544         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
18545 
18546         // Active admins in the target package.
18547         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
18548         if (allActiveAdmins != null) {
18549             for (ComponentName activeAdmin : allActiveAdmins) {
18550                 if (packageName.equals(activeAdmin.getPackageName())) {
18551                     packageActiveAdmins.add(activeAdmin);
18552                     removeActiveAdmin(activeAdmin, userId);
18553                 }
18554             }
18555         }
18556         if (packageActiveAdmins.size() == 0) {
18557             startUninstallIntent(packageName, userId);
18558         } else {
18559             mHandler.postDelayed(new Runnable() {
18560                 @Override
18561                 public void run() {
18562                     for (ComponentName activeAdmin : packageActiveAdmins) {
18563                         removeAdminArtifacts(activeAdmin, userId);
18564                     }
18565                     startUninstallIntent(packageName, userId);
18566                 }
18567             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
18568         }
18569     }
18570 
18571     @Override
18572     public boolean isDeviceProvisioned() {
18573         final CallerIdentity caller = getCallerIdentity();
18574         Preconditions.checkCallAuthorization(canManageUsers(caller));
18575 
18576         synchronized (getLockObject()) {
18577             return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
18578         }
18579     }
18580 
18581     private boolean isCurrentUserDemo() {
18582         if (UserManager.isDeviceInDemoMode(mContext)) {
18583             final int userId = mInjector.userHandleGetCallingUserId();
18584             return mInjector.binderWithCleanCallingIdentity(
18585                     () -> mUserManager.getUserInfo(userId).isDemo());
18586         }
18587         return false;
18588     }
18589 
18590     private void removePackageIfRequired(final String packageName, final int userId) {
18591         if (!packageHasActiveAdmins(packageName, userId)) {
18592             // Will not do anything if uninstall was not requested or was already started.
18593             startUninstallIntent(packageName, userId);
18594         }
18595     }
18596 
18597     private void startUninstallIntent(final String packageName, final int userId) {
18598         final UserPackage packageUserPair = UserPackage.of(userId, packageName);
18599         synchronized (getLockObject()) {
18600             if (!mPackagesToRemove.contains(packageUserPair)) {
18601                 // Do nothing if uninstall was not requested or was already started.
18602                 return;
18603             }
18604             mPackagesToRemove.remove(packageUserPair);
18605         }
18606         if (!isPackageInstalledForUser(packageName, userId)) {
18607             // Package does not exist. Nothing to do.
18608             return;
18609         }
18610 
18611         try { // force stop the package before uninstalling
18612             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
18613         } catch (RemoteException re) {
18614             Slogf.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
18615         }
18616         final Uri packageURI = Uri.parse("package:" + packageName);
18617         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
18618         uninstallIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
18619         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
18620     }
18621 
18622     /**
18623      * Removes the admin from the policy. Ideally called after the admin's
18624      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
18625      *
18626      * @param adminReceiver The admin to remove
18627      * @param userHandle The user for which this admin has to be removed.
18628      */
18629     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
18630         synchronized (getLockObject()) {
18631             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
18632             if (admin == null) {
18633                 return;
18634             }
18635             final DevicePolicyData policy = getUserData(userHandle);
18636             final boolean doProxyCleanup = admin.info.usesPolicy(
18637                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
18638             policy.mAdminList.remove(admin);
18639             policy.mAdminMap.remove(adminReceiver);
18640             policy.validatePasswordOwner();
18641             if (doProxyCleanup) {
18642                 resetGlobalProxyLocked(policy);
18643             }
18644             pushActiveAdminPackagesLocked(userHandle);
18645             saveSettingsLocked(userHandle);
18646             updateMaximumTimeToLockLocked(userHandle);
18647             policy.mRemovingAdmins.remove(adminReceiver);
18648             pushScreenCapturePolicy(userHandle);
18649 
18650             Slogf.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
18651         }
18652         pushMeteredDisabledPackages(userHandle);
18653         // The removed admin might have disabled camera, so update user
18654         // restrictions.
18655         pushUserRestrictions(userHandle);
18656     }
18657 
18658     @Override
18659     public void setDeviceProvisioningConfigApplied() {
18660         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
18661 
18662         synchronized (getLockObject()) {
18663             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
18664             policy.mDeviceProvisioningConfigApplied = true;
18665             saveSettingsLocked(UserHandle.USER_SYSTEM);
18666         }
18667     }
18668 
18669     @Override
18670     public boolean isDeviceProvisioningConfigApplied() {
18671         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
18672 
18673         synchronized (getLockObject()) {
18674             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
18675             return policy.mDeviceProvisioningConfigApplied;
18676         }
18677     }
18678 
18679     /**
18680      * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
18681      *
18682      * It's added for testing only. Please use this API carefully if it's used by other system app
18683      * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
18684      * apps.
18685      */
18686     @Override
18687     public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
18688         Preconditions.checkCallAuthorization(
18689                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
18690 
18691         boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
18692                 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
18693         DevicePolicyData policy = getUserData(userId);
18694         policy.mUserSetupComplete = isUserCompleted;
18695         mStateCache.setDeviceProvisioned(isUserCompleted);
18696         synchronized (getLockObject()) {
18697             saveSettingsLocked(userId);
18698         }
18699     }
18700 
18701     @Override
18702     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
18703         if (!mHasFeature) {
18704             return;
18705         }
18706         Objects.requireNonNull(admin, "ComponentName is null");
18707 
18708         final CallerIdentity caller = getCallerIdentity(admin);
18709         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
18710                 || isProfileOwner(caller) || isFinancedDeviceOwner(caller));
18711 
18712         toggleBackupServiceActive(caller.getUserId(), enabled);
18713     }
18714 
18715     @Override
18716     public boolean isBackupServiceEnabled(ComponentName admin) {
18717         if (!mHasFeature) {
18718             return true;
18719         }
18720         Objects.requireNonNull(admin, "ComponentName is null");
18721 
18722         final CallerIdentity caller = getCallerIdentity(admin);
18723         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
18724                 || isProfileOwner(caller) || isFinancedDeviceOwner(caller));
18725 
18726         return mInjector.binderWithCleanCallingIdentity(() -> {
18727             synchronized (getLockObject()) {
18728                 try {
18729                     IBackupManager ibm = mInjector.getIBackupManager();
18730                     return ibm != null && ibm.isBackupServiceActive(caller.getUserId());
18731                 } catch (RemoteException e) {
18732                     throw new IllegalStateException("Failed requesting backup service state.", e);
18733                 }
18734             }
18735         });
18736     }
18737 
18738     @Override
18739     public boolean bindDeviceAdminServiceAsUser(
18740             @NonNull ComponentName admin, @NonNull IApplicationThread caller,
18741             @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
18742             @NonNull IServiceConnection connection, long flags, @UserIdInt int targetUserId) {
18743         if (!mHasFeature) {
18744             return false;
18745         }
18746         Objects.requireNonNull(admin);
18747         Objects.requireNonNull(caller);
18748         Objects.requireNonNull(serviceIntent);
18749         Preconditions.checkArgument(
18750                 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
18751                 "Service intent must be explicit (with a package name or component): "
18752                         + serviceIntent);
18753         Objects.requireNonNull(connection);
18754         Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
18755                 "target user id must be different from the calling user id");
18756 
18757         if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
18758             throw new SecurityException("Not allowed to bind to target user id");
18759         }
18760 
18761         final String targetPackage;
18762         synchronized (getLockObject()) {
18763             targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
18764         }
18765 
18766         final long callingIdentity = mInjector.binderClearCallingIdentity();
18767         try {
18768             // Validate and sanitize the incoming service intent.
18769             final Intent sanitizedIntent =
18770                     createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
18771             if (sanitizedIntent == null) {
18772                 // Fail, cannot lookup the target service.
18773                 return false;
18774             }
18775             // Ask ActivityManager to bind it. Notice that we are binding the service with the
18776             // caller app instead of DevicePolicyManagerService.
18777             return mInjector.getIActivityManager().bindService(
18778                     caller, activtiyToken, serviceIntent,
18779                     serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
18780                     connection, flags, mContext.getOpPackageName(),
18781                     targetUserId) != 0;
18782         } catch (RemoteException ex) {
18783             // Same process, should not happen.
18784         } finally {
18785             mInjector.binderRestoreCallingIdentity(callingIdentity);
18786         }
18787 
18788         // Failed to bind.
18789         return false;
18790     }
18791 
18792     @Override
18793     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
18794         if (!mHasFeature) {
18795             return Collections.emptyList();
18796         }
18797         Objects.requireNonNull(admin);
18798         final CallerIdentity caller = getCallerIdentity(admin);
18799         Preconditions.checkCallAuthorization(
18800                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
18801 
18802         synchronized (getLockObject()) {
18803             final int callingUserId = caller.getUserId();
18804             return mInjector.binderWithCleanCallingIdentity(() -> {
18805                 ArrayList<UserHandle> targetUsers = new ArrayList<>();
18806                 if (!isDeviceOwner(admin, callingUserId)) {
18807                     // Profile owners can only bind to the device owner.
18808                     if (canUserBindToDeviceOwnerLocked(callingUserId)) {
18809                         targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
18810                     }
18811                 } else {
18812                     // Caller is the device owner: Look for profile owners that it can bind to.
18813                     final List<UserInfo> userInfos = mUserManager.getAliveUsers();
18814                     for (int i = 0; i < userInfos.size(); i++) {
18815                         final int userId = userInfos.get(i).id;
18816                         if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
18817                             targetUsers.add(UserHandle.of(userId));
18818                         }
18819                     }
18820                 }
18821 
18822                 return targetUsers;
18823             });
18824         }
18825     }
18826 
18827     private boolean canUserBindToDeviceOwnerLocked(int userId) {
18828         // There has to be a device owner, under another user id.
18829         if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
18830             return false;
18831         }
18832 
18833         // The user must have a profile owner that belongs to the same package as the device owner.
18834         if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
18835                 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
18836             return false;
18837         }
18838 
18839         // The user must be affiliated.
18840         return isUserAffiliatedWithDeviceLocked(userId);
18841     }
18842 
18843     private boolean hasIncompatibleAccountsOnAnyUser() {
18844         if (mHasIncompatibleAccounts == null) {
18845             // Hasn't loaded for the first time yet - assume the worst
18846             return true;
18847         }
18848 
18849         for (boolean hasIncompatible : mHasIncompatibleAccounts.values()) {
18850             if (hasIncompatible) {
18851                 return true;
18852             }
18853         }
18854 
18855         return false;
18856     }
18857 
18858     private boolean hasIncompatibleAccounts(int userId) {
18859         return mHasIncompatibleAccounts == null ? true
18860                 : mHasIncompatibleAccounts.getOrDefault(userId, /* default= */ false);
18861     }
18862 
18863     /**
18864      * Return true if a given user has any accounts that'll prevent installing a device or profile
18865      * owner {@code owner}.
18866      * - If the user has no accounts, then return false.
18867      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
18868      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
18869      *   ..._DISALLOWED, return true.
18870      * - Otherwise return false.
18871      *
18872      * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
18873      * when the caller is not ADB.
18874      *
18875      * DO NOT CALL IT WITH THE DPMS LOCK HELD.
18876      */
18877     private boolean hasIncompatibleAccountsOrNonAdbNoLock(CallerIdentity caller,
18878             int userId, @Nullable ComponentName owner) {
18879         if (!isAdb(caller)) {
18880             return true;
18881         }
18882         wtfIfInLock();
18883 
18884         return mInjector.binderWithCleanCallingIdentity(() -> {
18885             AccountManager am =
18886                     mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0)
18887                             .getSystemService(AccountManager.class);
18888             Account[] accounts = am.getAccounts();
18889             if (accounts.length == 0) {
18890                 return false;
18891             }
18892             synchronized (getLockObject()) {
18893                 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
18894                     Slogf.w(LOG_TAG,
18895                             "Non test-only owner can't be installed with existing accounts.");
18896                     return true;
18897                 }
18898             }
18899 
18900             boolean compatible = !hasIncompatibleAccounts(userId);
18901             if (compatible) {
18902                 Slogf.w(LOG_TAG, "All accounts are compatible");
18903             } else {
18904                 Slogf.e(LOG_TAG, "Found incompatible accounts");
18905             }
18906             return !compatible;
18907         });
18908     }
18909 
18910     ThreadPoolExecutor calculateHasIncompatibleAccountsExecutor = new ThreadPoolExecutor(
18911             1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
18912 
18913     @Override
18914     public void calculateHasIncompatibleAccounts() {
18915         if (calculateHasIncompatibleAccountsExecutor.getQueue().size() > 1) {
18916             return;
18917         }
18918         new CalculateHasIncompatibleAccountsTask().executeOnExecutor(
18919                 calculateHasIncompatibleAccountsExecutor, null);
18920     }
18921 
18922     @Nullable
18923     private volatile Map<Integer, Boolean> mHasIncompatibleAccounts;
18924 
18925     class CalculateHasIncompatibleAccountsTask extends AsyncTask<
18926             Void, Void, Map<Integer, Boolean>> {
18927         private static final String[] FEATURE_ALLOW =
18928                 {DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED};
18929         private static final String[] FEATURE_DISALLOW =
18930                 {DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED};
18931 
18932         @Override
18933         protected Map<Integer, Boolean> doInBackground(Void... args) {
18934             List<UserInfo> users = mUserManagerInternal.getUsers(/* excludeDying= */ true);
18935             Map<Integer, Boolean> results = new HashMap<>();
18936             for (UserInfo userInfo : users) {
18937                 results.put(userInfo.id, userHasIncompatibleAccounts(userInfo.id));
18938             }
18939 
18940             return results;
18941         }
18942 
18943         private boolean userHasIncompatibleAccounts(int id) {
18944             AccountManager am = mContext.createContextAsUser(UserHandle.of(id), /* flags= */ 0)
18945                     .getSystemService(AccountManager.class);
18946             Account[] accounts = am.getAccounts();
18947 
18948             for (Account account : accounts) {
18949                 if (hasAccountFeatures(am, account, FEATURE_DISALLOW)) {
18950                     return true;
18951                 }
18952                 if (!hasAccountFeatures(am, account, FEATURE_ALLOW)) {
18953                     return true;
18954                 }
18955             }
18956 
18957             return false;
18958         }
18959 
18960         @Override
18961         protected void onPostExecute(Map<Integer, Boolean> results) {
18962             mHasIncompatibleAccounts = Collections.unmodifiableMap(results);
18963 
18964             Slogf.i(LOG_TAG, "Finished calculating hasIncompatibleAccountsTask");
18965         }
18966 
18967         private static boolean hasAccountFeatures(AccountManager am, Account account,
18968                 String[] features) {
18969             try {
18970                 return am.hasFeatures(account, features, null, null).getResult();
18971             } catch (Exception e) {
18972                 Slogf.w(LOG_TAG, "Failed to get account feature", e);
18973                 return false;
18974             }
18975         }
18976     };
18977 
18978     private boolean isAdb(CallerIdentity caller) {
18979         return isShellUid(caller) || isRootUid(caller);
18980     }
18981 
18982     @Override
18983     public void setNetworkLoggingEnabled(@Nullable ComponentName admin,
18984             @NonNull String packageName, boolean enabled) {
18985         if (!mHasFeature) {
18986             return;
18987         }
18988         final CallerIdentity caller = getCallerIdentity(admin, packageName);
18989         final boolean isManagedProfileOwner = isProfileOwner(caller)
18990                 && isManagedProfile(caller.getUserId());
18991         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
18992                 && (isDefaultDeviceOwner(caller) || isManagedProfileOwner))
18993                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)));
18994 
18995         synchronized (getLockObject()) {
18996             if (enabled == isNetworkLoggingEnabledInternalLocked()) {
18997                 // already in the requested state
18998                 return;
18999             }
19000             final ActiveAdmin activeAdmin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
19001             activeAdmin.isNetworkLoggingEnabled = enabled;
19002             if (!enabled) {
19003                 activeAdmin.numNetworkLoggingNotifications = 0;
19004                 activeAdmin.lastNetworkLoggingNotificationTimeMs = 0;
19005             }
19006             saveSettingsLocked(caller.getUserId());
19007             setNetworkLoggingActiveInternal(enabled);
19008 
19009             DevicePolicyEventLogger
19010                     .createEvent(DevicePolicyEnums.SET_NETWORK_LOGGING_ENABLED)
19011                     .setAdmin(caller.getPackageName())
19012                     .setBoolean(/* isDelegate */ admin == null)
19013                     .setInt(enabled ? 1 : 0)
19014                     .setStrings(isManagedProfileOwner
19015                             ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER)
19016                     .write();
19017         }
19018     }
19019 
19020     private void setNetworkLoggingActiveInternal(boolean active) {
19021         mInjector.binderWithCleanCallingIdentity(() -> {
19022             boolean shouldSendNotification = false;
19023             synchronized (getLockObject()) {
19024                 if (active) {
19025                     if (mNetworkLogger == null) {
19026                         final int affectedUserId = getNetworkLoggingAffectedUser();
19027                         mNetworkLogger = new NetworkLogger(this,
19028                                 mInjector.getPackageManagerInternal(),
19029                                 affectedUserId == UserHandle.USER_SYSTEM
19030                                         ? UserHandle.USER_ALL : affectedUserId);
19031                     }
19032                     if (!mNetworkLogger.startNetworkLogging()) {
19033                         mNetworkLogger = null;
19034                         Slogf.wtf(LOG_TAG, "Network logging could not be started due to the logging"
19035                                 + " service not being available yet.");
19036                     }
19037                     maybePauseDeviceWideLoggingLocked();
19038                     shouldSendNotification = shouldSendNetworkLoggingNotificationLocked();
19039                 } else {
19040                     if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
19041                         Slogf.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
19042                                 + " service not being available yet.");
19043                     }
19044                     mNetworkLogger = null;
19045                 }
19046             }
19047             if (active) {
19048                 if (shouldSendNotification) {
19049                     mHandler.post(() -> handleSendNetworkLoggingNotification());
19050                 }
19051             } else {
19052                 mHandler.post(() -> handleCancelNetworkLoggingNotification());
19053             }
19054         });
19055     }
19056 
19057     private @UserIdInt int getNetworkLoggingAffectedUser() {
19058         synchronized (getLockObject()) {
19059             if (mOwners.hasDeviceOwner()) {
19060                 return mOwners.getDeviceOwnerUserId();
19061             } else {
19062                 return mInjector.binderWithCleanCallingIdentity(
19063                         () -> getManagedUserId());
19064             }
19065         }
19066     }
19067 
19068     private ActiveAdmin getNetworkLoggingControllingAdminLocked() {
19069         int affectedUserId = getNetworkLoggingAffectedUser();
19070         if (affectedUserId < 0) {
19071             return null;
19072         }
19073         return getDeviceOrProfileOwnerAdminLocked(affectedUserId);
19074     }
19075 
19076     @Override
19077     public long forceNetworkLogs() {
19078         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
19079                 || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS),
19080                 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call "
19081                         + "forceNetworkLogs");
19082         synchronized (getLockObject()) {
19083             if (!isNetworkLoggingEnabledInternalLocked()) {
19084                 throw new IllegalStateException("logging is not available");
19085             }
19086             if (mNetworkLogger != null) {
19087                 return mInjector.binderWithCleanCallingIdentity(
19088                         () -> mNetworkLogger.forceBatchFinalization());
19089             }
19090             return 0;
19091         }
19092     }
19093 
19094     /** Pauses security and network logging if there are unaffiliated users on the device */
19095     @GuardedBy("getLockObject()")
19096     private void maybePauseDeviceWideLoggingLocked() {
19097         if (!areAllUsersAffiliatedWithDeviceLocked()) {
19098             if (mOwners.hasDeviceOwner()) {
19099                 Slogf.i(LOG_TAG, "There are unaffiliated users, network logging will be "
19100                         + "paused if enabled.");
19101                 if (mNetworkLogger != null) {
19102                     mNetworkLogger.pause();
19103                 }
19104             }
19105             // TODO: We need to also enable this when someone is managing using permission
19106             if (!isOrganizationOwnedDeviceWithManagedProfile()) {
19107                 Slogf.i(LOG_TAG,
19108                         "Not org-owned managed profile device, security logging will be "
19109                                 + "paused if enabled.");
19110                 mSecurityLogMonitor.pause();
19111             }
19112         }
19113     }
19114 
19115     /** Resumes security and network logging (if they are enabled) if all users are affiliated */
19116     @GuardedBy("getLockObject()")
19117     private void maybeResumeDeviceWideLoggingLocked() {
19118         boolean allUsersAffiliated = areAllUsersAffiliatedWithDeviceLocked();
19119         boolean orgOwnedProfileDevice = isOrganizationOwnedDeviceWithManagedProfile();
19120         mInjector.binderWithCleanCallingIdentity(() -> {
19121             if (allUsersAffiliated || orgOwnedProfileDevice) {
19122                 mSecurityLogMonitor.resume();
19123             }
19124             // If there is no device owner, then per-user network logging may be enabled for the
19125             // managed profile. In which case, all users do not need to be affiliated.
19126             if (allUsersAffiliated || !mOwners.hasDeviceOwner()) {
19127                 if (mNetworkLogger != null) {
19128                     mNetworkLogger.resume();
19129                 }
19130             }
19131         });
19132     }
19133 
19134     /** Deletes any security and network logs that might have been collected so far */
19135     @GuardedBy("getLockObject()")
19136     private void discardDeviceWideLogsLocked() {
19137         mSecurityLogMonitor.discardLogs();
19138         if (mNetworkLogger != null) {
19139             mNetworkLogger.discardLogs();
19140         }
19141         // TODO: We should discard pre-boot security logs here too, as otherwise those
19142         // logs (which might contain data from the user just removed) will be
19143         // available after next boot.
19144     }
19145 
19146     /**
19147      * This API is cached: invalidate with invalidateBinderCaches().
19148      */
19149     @Override
19150     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin,
19151             @NonNull String packageName) {
19152         if (!mHasFeature) {
19153             return false;
19154         }
19155         final CallerIdentity caller = getCallerIdentity(admin, packageName);
19156         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
19157                 &&  (isDefaultDeviceOwner(caller)
19158                 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))))
19159                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING))
19160                 || hasCallingOrSelfPermission(permission.MANAGE_USERS));
19161 
19162         synchronized (getLockObject()) {
19163             return isNetworkLoggingEnabledInternalLocked();
19164         }
19165     }
19166 
19167     private boolean isNetworkLoggingEnabledInternalLocked() {
19168         ActiveAdmin activeAdmin = getNetworkLoggingControllingAdminLocked();
19169         return (activeAdmin != null) && activeAdmin.isNetworkLoggingEnabled;
19170     }
19171 
19172     /*
19173      * A maximum of 1200 events are returned, and the total marshalled size is in the order of
19174      * 100kB, so returning a List instead of ParceledListSlice is acceptable.
19175      * Ideally this would be done with ParceledList, however it only supports homogeneous types.
19176      *
19177      * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
19178      */
19179     @Override
19180     public List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
19181             @NonNull String packageName, long batchToken) {
19182         if (!mHasFeature) {
19183             return null;
19184         }
19185         final CallerIdentity caller = getCallerIdentity(admin, packageName);
19186         final boolean isManagedProfileOwner = isProfileOwner(caller)
19187                 && isManagedProfile(caller.getUserId());
19188         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
19189                 &&  (isDefaultDeviceOwner(caller) || isManagedProfileOwner))
19190                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)));
19191         if (mOwners.hasDeviceOwner()) {
19192             checkAllUsersAreAffiliatedWithDevice();
19193         }
19194 
19195         synchronized (getLockObject()) {
19196             if (mNetworkLogger == null || !isNetworkLoggingEnabledInternalLocked()) {
19197                 return null;
19198             }
19199             DevicePolicyEventLogger
19200                     .createEvent(DevicePolicyEnums.RETRIEVE_NETWORK_LOGS)
19201                     .setAdmin(caller.getPackageName())
19202                     .setBoolean(/* isDelegate */ admin == null)
19203                     .setStrings(isManagedProfileOwner
19204                             ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER)
19205                     .write();
19206 
19207             final long currentTime = System.currentTimeMillis();
19208             DevicePolicyData policyData = getUserData(caller.getUserId());
19209             if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
19210                 policyData.mLastNetworkLogsRetrievalTime = currentTime;
19211                 saveSettingsLocked(caller.getUserId());
19212             }
19213             return mNetworkLogger.retrieveLogs(batchToken);
19214         }
19215     }
19216 
19217     /**
19218      * Returns whether it's time to post another network logging notification. When returning true,
19219      * this method has the side-effect of updating the recorded last network logging notification
19220      * time to now.
19221      */
19222     private boolean shouldSendNetworkLoggingNotificationLocked() {
19223         ensureLocked();
19224         // Send a network logging notification if the admin is a device owner, not profile owner.
19225         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19226         if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
19227             return false;
19228         }
19229         if (deviceOwner.numNetworkLoggingNotifications
19230                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
19231             return false;
19232         }
19233         final long now = System.currentTimeMillis();
19234         if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
19235             return false;
19236         }
19237         deviceOwner.numNetworkLoggingNotifications++;
19238         if (deviceOwner.numNetworkLoggingNotifications
19239                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
19240             deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
19241         } else {
19242             deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
19243         }
19244         saveSettingsLocked(deviceOwner.getUserHandle().getIdentifier());
19245         return true;
19246     }
19247 
19248     private void handleSendNetworkLoggingNotification() {
19249         final PackageManagerInternal pm = mInjector.getPackageManagerInternal();
19250         final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
19251         intent.setPackage(pm.getSystemUiServiceComponent().getPackageName());
19252         mNetworkLoggingNotificationUserId = getCurrentForegroundUserId();
19253         // Simple notification clicks are immutable
19254         final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent,
19255                 PendingIntent.FLAG_IMMUTABLE, UserHandle.CURRENT);
19256 
19257         final String title = getNetworkLoggingTitle();
19258         final String text = getNetworkLoggingText();
19259         Notification notification =
19260                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
19261                 .setSmallIcon(R.drawable.ic_info_outline)
19262                 .setContentTitle(title)
19263                 .setContentText(text)
19264                 .setTicker(title)
19265                 .setShowWhen(true)
19266                 .setContentIntent(pendingIntent)
19267                 .setStyle(new Notification.BigTextStyle().bigText(text))
19268                 .build();
19269         Slogf.i(LOG_TAG, "Sending network logging notification to user %d",
19270                 mNetworkLoggingNotificationUserId);
19271         mInjector.getNotificationManager().notifyAsUser(/* tag= */ null,
19272                 SystemMessage.NOTE_NETWORK_LOGGING, notification,
19273                 UserHandle.of(mNetworkLoggingNotificationUserId));
19274     }
19275 
19276     private String getNetworkLoggingTitle() {
19277         return getUpdatableString(
19278                 NETWORK_LOGGING_TITLE, R.string.network_logging_notification_title);
19279     }
19280 
19281     private String getNetworkLoggingText() {
19282         return getUpdatableString(
19283                 NETWORK_LOGGING_MESSAGE, R.string.network_logging_notification_text);
19284     }
19285 
19286     private void handleCancelNetworkLoggingNotification() {
19287         if (mNetworkLoggingNotificationUserId == UserHandle.USER_NULL) {
19288             // Happens when setNetworkLoggingActive(false) is called before called with true
19289             Slogf.d(LOG_TAG, "Not cancelling network logging notification for USER_NULL");
19290             return;
19291         }
19292 
19293         Slogf.i(LOG_TAG, "Cancelling network logging notification for user %d",
19294                 mNetworkLoggingNotificationUserId);
19295         mInjector.getNotificationManager().cancelAsUser(/* tag= */ null,
19296                 SystemMessage.NOTE_NETWORK_LOGGING,
19297                 UserHandle.of(mNetworkLoggingNotificationUserId));
19298         mNetworkLoggingNotificationUserId = UserHandle.USER_NULL;
19299     }
19300 
19301     /**
19302      * Return the package name of owner in a given user.
19303      */
19304     private String getOwnerPackageNameForUserLocked(int userId) {
19305         return mOwners.getDeviceOwnerUserId() == userId
19306                 ? mOwners.getDeviceOwnerPackageName()
19307                 : mOwners.getProfileOwnerPackage(userId);
19308     }
19309 
19310     /**
19311      * @param rawIntent Original service intent specified by caller. It must be explicit.
19312      * @param expectedPackageName The expected package name of the resolved service.
19313      * @return Intent that have component explicitly set. {@code null} if no service is resolved
19314      *     with the given intent.
19315      * @throws SecurityException if the intent is resolved to an invalid service.
19316      */
19317     private Intent createCrossUserServiceIntent(
19318             @NonNull Intent rawIntent, @NonNull String expectedPackageName,
19319             @UserIdInt int targetUserId) throws RemoteException, SecurityException {
19320         ResolveInfo info = mIPackageManager.resolveService(
19321                 rawIntent,
19322                 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
19323                 0,  // flags
19324                 targetUserId);
19325         if (info == null || info.serviceInfo == null) {
19326             Slogf.e(LOG_TAG, "Fail to look up the service: %s or user %d is not running", rawIntent,
19327                     targetUserId);
19328             return null;
19329         }
19330         if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
19331             throw new SecurityException("Only allow to bind service in " + expectedPackageName);
19332         }
19333         // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
19334         if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
19335             throw new SecurityException(
19336                     "Service must be protected by BIND_DEVICE_ADMIN permission");
19337         }
19338         // It is the system server to bind the service, it would be extremely dangerous if it
19339         // can be exploited to bind any service. Set the component explicitly to make sure we
19340         // do not bind anything accidentally.
19341         rawIntent.setComponent(info.serviceInfo.getComponentName());
19342         return rawIntent;
19343     }
19344 
19345     @Override
19346     public long getLastSecurityLogRetrievalTime() {
19347         final CallerIdentity caller = getCallerIdentity();
19348         Preconditions.checkCallAuthorization(
19349                 isDefaultDeviceOwner(caller) || canManageUsers(caller));
19350         return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
19351      }
19352 
19353     @Override
19354     public long getLastBugReportRequestTime() {
19355         final CallerIdentity caller = getCallerIdentity();
19356         Preconditions.checkCallAuthorization(
19357                 isDefaultDeviceOwner(caller) || canManageUsers(caller));
19358         return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
19359      }
19360 
19361     @Override
19362     public long getLastNetworkLogRetrievalTime() {
19363         final CallerIdentity caller = getCallerIdentity();
19364 
19365         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19366                 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))
19367                 || canManageUsers(caller));
19368         final int affectedUserId = getNetworkLoggingAffectedUser();
19369         return affectedUserId >= 0 ? getUserData(affectedUserId).mLastNetworkLogsRetrievalTime : -1;
19370     }
19371 
19372     @Override
19373     public boolean setResetPasswordToken(ComponentName admin, String callerPackageName,
19374             byte[] token) {
19375         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
19376             return false;
19377         }
19378         if (token == null || token.length < 32) {
19379             throw new IllegalArgumentException("token must be at least 32-byte long");
19380         }
19381         CallerIdentity caller;
19382         if (isUnicornFlagEnabled()) {
19383             caller = getCallerIdentity(admin, callerPackageName);
19384         } else {
19385             caller = getCallerIdentity(admin);
19386         }
19387         final int userId = caller.getUserId();
19388 
19389         if (isUnicornFlagEnabled()) {
19390             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
19391                     admin,
19392                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
19393                     caller.getPackageName(),
19394                     userId);
19395             Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
19396                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19397                     enforcingAdmin,
19398                     userId);
19399             long tokenHandle = addEscrowToken(
19400                     token, currentTokenHandle == null ? 0 : currentTokenHandle, userId);
19401             if (tokenHandle == 0) {
19402                 return false;
19403             }
19404             mDevicePolicyEngine.setLocalPolicy(
19405                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19406                     enforcingAdmin,
19407                     new LongPolicyValue(tokenHandle),
19408                     userId);
19409             return true;
19410         } else {
19411             Objects.requireNonNull(admin, "ComponentName is null");
19412             Preconditions.checkCallAuthorization(
19413                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19414             synchronized (getLockObject()) {
19415                 DevicePolicyData policy = getUserData(userId);
19416                 policy.mPasswordTokenHandle = addEscrowToken(
19417                         token, policy.mPasswordTokenHandle, userId);
19418                 saveSettingsLocked(userId);
19419                 return policy.mPasswordTokenHandle != 0;
19420             }
19421         }
19422     }
19423 
19424     private long addEscrowToken(byte[] token, long currentPasswordTokenHandle, int userId) {
19425         resetEscrowToken(currentPasswordTokenHandle, userId);
19426         return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.addEscrowToken(
19427                 token, userId, /* EscrowTokenStateChangeCallback= */ null));
19428     }
19429 
19430     private boolean resetEscrowToken(long tokenHandle, int userId) {
19431         return mInjector.binderWithCleanCallingIdentity(() -> {
19432             if (tokenHandle != 0) {
19433                 return mLockPatternUtils.removeEscrowToken(tokenHandle, userId);
19434             }
19435             return false;
19436         });
19437     }
19438 
19439     @Override
19440     public boolean clearResetPasswordToken(ComponentName admin, String callerPackageName) {
19441         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
19442             return false;
19443         }
19444         CallerIdentity caller;
19445         if (isUnicornFlagEnabled()) {
19446             caller = getCallerIdentity(admin, callerPackageName);
19447         } else {
19448             caller = getCallerIdentity(admin);
19449         }
19450         final int userId = caller.getUserId();
19451         boolean result = false;
19452 
19453         if (isUnicornFlagEnabled()) {
19454             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
19455                     admin,
19456                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
19457                     caller.getPackageName(),
19458                     userId);
19459             Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
19460                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19461                     enforcingAdmin,
19462                     userId);
19463             if (currentTokenHandle != null) {
19464                 result = resetEscrowToken(currentTokenHandle, userId);
19465                 mDevicePolicyEngine.removeLocalPolicy(
19466                         PolicyDefinition.RESET_PASSWORD_TOKEN,
19467                         enforcingAdmin,
19468                         userId);
19469             }
19470         } else {
19471             Objects.requireNonNull(admin, "ComponentName is null");
19472             Preconditions.checkCallAuthorization(
19473                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19474             synchronized (getLockObject()) {
19475                 DevicePolicyData policy = getUserData(userId);
19476                 if (policy.mPasswordTokenHandle != 0) {
19477                     result = resetEscrowToken(policy.mPasswordTokenHandle, userId);
19478                     policy.mPasswordTokenHandle = 0;
19479                     saveSettingsLocked(userId);
19480                 }
19481             }
19482         }
19483         return result;
19484     }
19485 
19486     @Override
19487     public boolean isResetPasswordTokenActive(ComponentName admin, String callerPackageName) {
19488         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
19489             return false;
19490         }
19491         CallerIdentity caller;
19492         if (isUnicornFlagEnabled()) {
19493             caller = getCallerIdentity(admin, callerPackageName);
19494         } else {
19495             caller = getCallerIdentity(admin);
19496         }
19497         int userId = caller.getUserId();
19498 
19499         if (isUnicornFlagEnabled()) {
19500             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
19501                     admin,
19502                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
19503                     caller.getPackageName(),
19504                     userId);
19505             Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
19506                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19507                     enforcingAdmin,
19508                     userId);
19509             return isResetPasswordTokenActiveForUserLocked(
19510                     currentTokenHandle == null ? 0 : currentTokenHandle, userId);
19511         } else {
19512             Objects.requireNonNull(admin, "ComponentName is null");
19513             Preconditions.checkCallAuthorization(
19514                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19515             synchronized (getLockObject()) {
19516                 DevicePolicyData policy = getUserData(userId);
19517                 return isResetPasswordTokenActiveForUserLocked(policy.mPasswordTokenHandle, userId);
19518             }
19519         }
19520     }
19521 
19522     private boolean isResetPasswordTokenActiveForUserLocked(
19523             long passwordTokenHandle, int userHandle) {
19524         if (passwordTokenHandle != 0) {
19525             return mInjector.binderWithCleanCallingIdentity(() ->
19526                     mLockPatternUtils.isEscrowTokenActive(passwordTokenHandle, userHandle));
19527         }
19528         return false;
19529     }
19530 
19531     @Override
19532     public boolean resetPasswordWithToken(ComponentName admin, String callerPackageName,
19533             String passwordOrNull, byte[] token,
19534             int flags) {
19535         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
19536             return false;
19537         }
19538         Objects.requireNonNull(token);
19539 
19540         CallerIdentity caller;
19541         if (isUnicornFlagEnabled()) {
19542             caller = getCallerIdentity(admin, callerPackageName);
19543         } else {
19544             caller = getCallerIdentity(admin);
19545         }
19546 
19547         int userId = caller.getUserId();
19548         boolean result = false;
19549         final String password = passwordOrNull != null ? passwordOrNull : "";
19550 
19551         if (isUnicornFlagEnabled()) {
19552             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
19553                     admin,
19554                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
19555                     caller.getPackageName(),
19556                     userId);
19557             Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
19558                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19559                     enforcingAdmin,
19560                     userId);
19561             if (currentTokenHandle != null && currentTokenHandle != 0) {
19562                 result = resetPasswordInternal(password, currentTokenHandle, token, flags, caller);
19563             } else {
19564                 Slogf.w(LOG_TAG, "No saved token handle");
19565             }
19566         } else {
19567             Objects.requireNonNull(admin, "ComponentName is null");
19568             Preconditions.checkCallAuthorization(
19569                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19570             synchronized (getLockObject()) {
19571                 DevicePolicyData policy = getUserData(userId);
19572                 if (policy.mPasswordTokenHandle != 0) {
19573                     result = resetPasswordInternal(
19574                             password, policy.mPasswordTokenHandle, token, flags, caller);
19575                 } else {
19576                     Slogf.w(LOG_TAG, "No saved token handle");
19577                 }
19578             }
19579         }
19580 
19581         if (result) {
19582             if (isUnicornFlagEnabled()) {
19583                 DevicePolicyEventLogger
19584                         .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN)
19585                         .setAdmin(callerPackageName)
19586                         .write();
19587             } else {
19588                 DevicePolicyEventLogger
19589                         .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN)
19590                         .setAdmin(caller.getComponentName())
19591                         .write();
19592             }
19593         }
19594         return result;
19595     }
19596 
19597     @Override
19598     public boolean isCurrentInputMethodSetByOwner() {
19599         final CallerIdentity caller = getCallerIdentity();
19600         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19601                 || isProfileOwner(caller) || isSystemUid(caller),
19602                 "Only profile owner, device owner and system may call this method.");
19603         return getUserData(caller.getUserId()).mCurrentInputMethodSet;
19604     }
19605 
19606     @Override
19607     public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
19608         final int userId = user.getIdentifier();
19609         final CallerIdentity caller = getCallerIdentity();
19610         Preconditions.checkCallAuthorization(
19611                 (isProfileOwner(caller) || isDefaultDeviceOwner(caller) || canQueryAdminPolicy(
19612                         caller)) && hasFullCrossUsersPermission(caller, userId));
19613 
19614         synchronized (getLockObject()) {
19615             return new StringParceledListSlice(
19616                     new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
19617         }
19618     }
19619 
19620     @Override
19621     public void clearApplicationUserData(ComponentName admin, String packageName,
19622             IPackageDataObserver callback) {
19623         Objects.requireNonNull(admin, "ComponentName is null");
19624         Objects.requireNonNull(packageName, "packageName is null");
19625         Objects.requireNonNull(callback, "callback is null");
19626 
19627         final CallerIdentity caller = getCallerIdentity(admin);
19628         Preconditions.checkCallAuthorization(
19629                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
19630         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CLEAR_APPLICATION_USER_DATA);
19631 
19632         long ident = mInjector.binderClearCallingIdentity();
19633         try {
19634             ActivityManager.getService().clearApplicationUserData(packageName, false, callback,
19635                     caller.getUserId());
19636         } catch(RemoteException re) {
19637             // Same process, should not happen.
19638         } catch (SecurityException se) {
19639             // This can happen e.g. for device admin packages, do not throw out the exception,
19640             // because callers have no means to know beforehand for which packages this might
19641             // happen. If so, we send back that removal failed.
19642             Slogf.w(LOG_TAG, "Not allowed to clear application user data for package "
19643                     + packageName, se);
19644             try {
19645                 callback.onRemoveCompleted(packageName, false);
19646             } catch (RemoteException re) {
19647                 // Caller is no longer available, ignore
19648             }
19649         } finally {
19650             mInjector.binderRestoreCallingIdentity(ident);
19651         }
19652     }
19653 
19654     @Override
19655     public void setLogoutEnabled(ComponentName admin, boolean enabled) {
19656         if (!mHasFeature) {
19657             return;
19658         }
19659         Objects.requireNonNull(admin, "ComponentName is null");
19660         final CallerIdentity caller = getCallerIdentity(admin);
19661         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19662         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOGOUT_ENABLED);
19663 
19664         synchronized (getLockObject()) {
19665             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19666             if (deviceOwner.isLogoutEnabled == enabled) {
19667                 // already in the requested state
19668                 return;
19669             }
19670             deviceOwner.isLogoutEnabled = enabled;
19671             saveSettingsLocked(caller.getUserId());
19672         }
19673     }
19674 
19675     @Override
19676     public boolean isLogoutEnabled() {
19677         if (!mHasFeature) {
19678             return false;
19679         }
19680         synchronized (getLockObject()) {
19681             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19682             return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
19683         }
19684     }
19685 
19686     @Override
19687     public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
19688             String provisioningAction) throws RemoteException {
19689         Preconditions.checkCallAuthorization(
19690                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
19691 
19692         return new ArrayList<>(
19693                 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
19694     }
19695 
19696     @Override
19697     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
19698             @Nullable PersistableBundle bundle) {
19699         if (!mHasFeature) {
19700             return;
19701         }
19702         Objects.requireNonNull(admin, "ComponentName is null");
19703         Objects.requireNonNull(target, "Target cannot be null.");
19704         Preconditions.checkArgument(!admin.equals(target),
19705                 "Provided administrator and target are the same object.");
19706         Preconditions.checkArgument(!admin.getPackageName().equals(target.getPackageName()),
19707                 "Provided administrator and target have the same package name.");
19708         if (bundle != null) {
19709             enforceMaxStringLength(bundle, "bundle");
19710         }
19711 
19712         final CallerIdentity caller = getCallerIdentity(admin);
19713         Preconditions.checkCallAuthorization(
19714                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
19715 
19716         final int callingUserId = caller.getUserId();
19717         final DevicePolicyData policy = getUserData(callingUserId);
19718         final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId,
19719                 /* throwForMissingPermission= */ true);
19720         checkActiveAdminPrecondition(target, incomingDeviceInfo, policy);
19721         Preconditions.checkArgument(incomingDeviceInfo.supportsTransferOwnership(),
19722                 "Provided target does not support ownership transfer.");
19723 
19724         final long id = mInjector.binderClearCallingIdentity();
19725         String ownerType = null;
19726         try {
19727             synchronized (getLockObject()) {
19728                 /*
19729                 * We must ensure the whole process is atomic to prevent the device from ending up
19730                 * in an invalid state (e.g. no active admin). This could happen if the device
19731                 * is rebooted or work mode is turned off mid-transfer.
19732                 * In order to guarantee atomicity, we:
19733                 *
19734                 * 1. Save an atomic journal file describing the transfer process
19735                 * 2. Perform the transfer itself
19736                 * 3. Delete the journal file
19737                 *
19738                 * That way if the journal file exists on device boot, we know that the transfer
19739                 * must be reverted back to the original administrator. This logic is implemented in
19740                 * revertTransferOwnershipIfNecessaryLocked.
19741                 * */
19742                 if (bundle == null) {
19743                     bundle = new PersistableBundle();
19744                 }
19745                 if (isProfileOwner(caller)) {
19746                     ownerType = ADMIN_TYPE_PROFILE_OWNER;
19747                     prepareTransfer(admin, target, bundle, callingUserId,
19748                             ADMIN_TYPE_PROFILE_OWNER);
19749                     transferProfileOwnershipLocked(admin, target, callingUserId);
19750                     sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
19751                             getTransferOwnershipAdminExtras(bundle), callingUserId);
19752                     postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId);
19753                     if (isUserAffiliatedWithDeviceLocked(callingUserId)) {
19754                         notifyAffiliatedProfileTransferOwnershipComplete(callingUserId);
19755                     }
19756                 } else if (isDefaultDeviceOwner(caller)) {
19757                     ownerType = ADMIN_TYPE_DEVICE_OWNER;
19758                     prepareTransfer(admin, target, bundle, callingUserId,
19759                             ADMIN_TYPE_DEVICE_OWNER);
19760                     transferDeviceOwnershipLocked(admin, target, callingUserId);
19761                     sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
19762                             getTransferOwnershipAdminExtras(bundle));
19763                     postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId);
19764                 }
19765             }
19766         } finally {
19767             mInjector.binderRestoreCallingIdentity(id);
19768         }
19769         DevicePolicyEventLogger
19770                 .createEvent(DevicePolicyEnums.TRANSFER_OWNERSHIP)
19771                 .setAdmin(admin)
19772                 .setStrings(target.getPackageName(), ownerType)
19773                 .write();
19774     }
19775 
19776     private void prepareTransfer(ComponentName admin, ComponentName target,
19777             PersistableBundle bundle, int callingUserId, String adminType) {
19778         saveTransferOwnershipBundleLocked(bundle, callingUserId);
19779         mTransferOwnershipMetadataManager.saveMetadataFile(
19780                 new TransferOwnershipMetadataManager.Metadata(admin, target,
19781                         callingUserId, adminType));
19782     }
19783 
19784     private void postTransfer(String broadcast, int callingUserId) {
19785         deleteTransferOwnershipMetadataFileLocked();
19786         sendOwnerChangedBroadcast(broadcast, callingUserId);
19787     }
19788 
19789     private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) {
19790         final Bundle extras = new Bundle();
19791         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId));
19792         sendDeviceOwnerCommand(
19793                 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras);
19794     }
19795 
19796     /**
19797      * Transfers the profile owner for user with id profileOwnerUserId from admin to target.
19798      */
19799     private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target,
19800             int profileOwnerUserId) {
19801         transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId);
19802         mOwners.transferProfileOwner(target, profileOwnerUserId);
19803         Slogf.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId);
19804         mOwners.writeProfileOwner(profileOwnerUserId);
19805         mDeviceAdminServiceController.startServiceForAdmin(
19806                 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner");
19807     }
19808 
19809     /**
19810      * Transfers the device owner for user with id userId from admin to target.
19811      */
19812     private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) {
19813         transferActiveAdminUncheckedLocked(target, admin, userId);
19814         mOwners.transferDeviceOwnership(target);
19815         Slogf.i(LOG_TAG, "Device owner set: " + target + " on user " + userId);
19816         mOwners.writeDeviceOwner();
19817         mDeviceAdminServiceController.startServiceForAdmin(
19818                 target.getPackageName(), userId, "transfer-device-owner");
19819     }
19820 
19821     private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) {
19822         Bundle extras = new Bundle();
19823         if (bundle != null) {
19824             extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle);
19825         }
19826         return extras;
19827     }
19828 
19829     @Override
19830     public void setStartUserSessionMessage(
19831             ComponentName admin, CharSequence startUserSessionMessage) {
19832         if (!mHasFeature) {
19833             return;
19834         }
19835         Objects.requireNonNull(admin, "ComponentName is null");
19836         final CallerIdentity caller = getCallerIdentity(admin);
19837         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19838 
19839         final String startUserSessionMessageString =
19840                 startUserSessionMessage != null ? startUserSessionMessage.toString() : null;
19841 
19842         synchronized (getLockObject()) {
19843             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19844             if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) {
19845                 return;
19846             }
19847             deviceOwner.startUserSessionMessage = startUserSessionMessageString;
19848             saveSettingsLocked(caller.getUserId());
19849         }
19850 
19851         mInjector.getActivityManagerInternal()
19852                 .setSwitchingFromSystemUserMessage(startUserSessionMessageString);
19853     }
19854 
19855     @Override
19856     public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) {
19857         if (!mHasFeature) {
19858             return;
19859         }
19860         Objects.requireNonNull(admin, "ComponentName is null");
19861         final CallerIdentity caller = getCallerIdentity(admin);
19862         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19863 
19864         final String endUserSessionMessageString =
19865                 endUserSessionMessage != null ? endUserSessionMessage.toString() : null;
19866 
19867         synchronized (getLockObject()) {
19868             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19869             if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) {
19870                 return;
19871             }
19872             deviceOwner.endUserSessionMessage = endUserSessionMessageString;
19873             saveSettingsLocked(caller.getUserId());
19874         }
19875 
19876         mInjector.getActivityManagerInternal()
19877                 .setSwitchingToSystemUserMessage(endUserSessionMessageString);
19878     }
19879 
19880     @Override
19881     public String getStartUserSessionMessage(ComponentName admin) {
19882         if (!mHasFeature) {
19883             return null;
19884         }
19885         Objects.requireNonNull(admin, "ComponentName is null");
19886         final CallerIdentity caller = getCallerIdentity(admin);
19887         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19888 
19889         synchronized (getLockObject()) {
19890             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19891             return deviceOwner.startUserSessionMessage;
19892         }
19893     }
19894 
19895     @Override
19896     public String getEndUserSessionMessage(ComponentName admin) {
19897         if (!mHasFeature) {
19898             return null;
19899         }
19900         Objects.requireNonNull(admin, "ComponentName is null");
19901         final CallerIdentity caller = getCallerIdentity(admin);
19902         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19903 
19904         synchronized (getLockObject()) {
19905             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19906             return deviceOwner.endUserSessionMessage;
19907         }
19908     }
19909 
19910     private void deleteTransferOwnershipMetadataFileLocked() {
19911         mTransferOwnershipMetadataManager.deleteMetadataFile();
19912     }
19913 
19914     @Override
19915     @Nullable
19916     public PersistableBundle getTransferOwnershipBundle() {
19917         final CallerIdentity caller = getCallerIdentity();
19918         Preconditions.checkCallAuthorization(
19919                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19920 
19921         synchronized (getLockObject()) {
19922             final int callingUserId = caller.getUserId();
19923             final File bundleFile = new File(
19924                     mPathProvider.getUserSystemDirectory(callingUserId),
19925                     TRANSFER_OWNERSHIP_PARAMETERS_XML);
19926             if (!bundleFile.exists()) {
19927                 return null;
19928             }
19929             try (FileInputStream stream = new FileInputStream(bundleFile)) {
19930                 TypedXmlPullParser parser = Xml.resolvePullParser(stream);
19931                 parser.next();
19932                 return PersistableBundle.restoreFromXml(parser);
19933             } catch (IOException | XmlPullParserException | IllegalArgumentException e) {
19934                 Slogf.e(LOG_TAG, "Caught exception while trying to load the "
19935                         + "owner transfer parameters from file " + bundleFile, e);
19936                 return null;
19937             }
19938         }
19939     }
19940 
19941     @Override
19942     public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) {
19943         if (!mHasFeature || !mHasTelephonyFeature) {
19944             return -1;
19945         }
19946         Objects.requireNonNull(who, "ComponentName is null");
19947         Objects.requireNonNull(apnSetting, "ApnSetting is null in addOverrideApn");
19948         final CallerIdentity caller = getCallerIdentity(who);
19949         if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
19950             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19951                     || isManagedProfileOwner(caller));
19952         } else {
19953             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19954         }
19955 
19956         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
19957         if (tm != null) {
19958             return mInjector.binderWithCleanCallingIdentity(
19959                     () -> tm.addDevicePolicyOverrideApn(mContext, apnSetting));
19960         } else {
19961             Slogf.w(LOG_TAG, "TelephonyManager is null when trying to add override apn");
19962             return INVALID_APN_ID;
19963         }
19964     }
19965 
19966     @Override
19967     public boolean updateOverrideApn(@NonNull ComponentName who, int apnId,
19968             @NonNull ApnSetting apnSetting) {
19969         if (!mHasFeature || !mHasTelephonyFeature) {
19970             return false;
19971         }
19972         Objects.requireNonNull(who, "ComponentName is null");
19973         Objects.requireNonNull(apnSetting, "ApnSetting is null in updateOverrideApn");
19974         final CallerIdentity caller = getCallerIdentity(who);
19975         ApnSetting apn = getApnSetting(apnId);
19976         if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE
19977                 && apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
19978             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19979                     || isManagedProfileOwner(caller));
19980         } else {
19981             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19982         }
19983 
19984         if (apnId < 0) {
19985             return false;
19986         }
19987         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
19988         if (tm != null) {
19989             return mInjector.binderWithCleanCallingIdentity(
19990                     () -> tm.modifyDevicePolicyOverrideApn(mContext, apnId, apnSetting));
19991         } else {
19992             Slogf.w(LOG_TAG, "TelephonyManager is null when trying to modify override apn");
19993             return false;
19994         }
19995     }
19996 
19997     @Override
19998     public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) {
19999         if (!mHasFeature || !mHasTelephonyFeature) {
20000             return false;
20001         }
20002         Objects.requireNonNull(who, "ComponentName is null");
20003         final CallerIdentity caller = getCallerIdentity(who);
20004         ApnSetting apn = getApnSetting(apnId);
20005         if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
20006             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
20007                     || isManagedProfileOwner(caller));
20008         } else {
20009             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20010         }
20011         return removeOverrideApnUnchecked(apnId);
20012     }
20013 
20014     private boolean removeOverrideApnUnchecked(int apnId) {
20015         if(apnId < 0) {
20016             return false;
20017         }
20018         int numDeleted = mInjector.binderWithCleanCallingIdentity(
20019                 () -> mContext.getContentResolver().delete(
20020                         Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null));
20021         return numDeleted > 0;
20022     }
20023 
20024     private ApnSetting getApnSetting(int apnId) {
20025         if (apnId < 0) {
20026             return null;
20027         }
20028         ApnSetting apnSetting = null;
20029         Cursor cursor = mInjector.binderWithCleanCallingIdentity(
20030                 () -> mContext.getContentResolver().query(
20031                         Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null, null,
20032                         Telephony.Carriers.DEFAULT_SORT_ORDER));
20033         if (cursor != null) {
20034             while (cursor.moveToNext()) {
20035                 apnSetting = ApnSetting.makeApnSetting(cursor);
20036                 if (apnSetting != null) {
20037                     break;
20038                 }
20039             }
20040             cursor.close();
20041         }
20042         return apnSetting;
20043     }
20044 
20045     @Override
20046     public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) {
20047         if (!mHasFeature || !mHasTelephonyFeature) {
20048             return Collections.emptyList();
20049         }
20050         Objects.requireNonNull(who, "ComponentName is null");
20051         final CallerIdentity caller = getCallerIdentity(who);
20052         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
20053                 || isManagedProfileOwner(caller));
20054         List<ApnSetting> apnSettings = getOverrideApnsUnchecked();
20055         if (isProfileOwner(caller)) {
20056             List<ApnSetting> apnSettingList = new ArrayList<>();
20057             for (ApnSetting apnSetting : apnSettings) {
20058                 if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
20059                     apnSettingList.add(apnSetting);
20060                 }
20061             }
20062             return apnSettingList;
20063         } else {
20064             return apnSettings;
20065         }
20066     }
20067 
20068     private List<ApnSetting> getOverrideApnsUnchecked() {
20069         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
20070         if (tm != null) {
20071             return mInjector.binderWithCleanCallingIdentity(
20072                     () -> tm.getDevicePolicyOverrideApns(mContext));
20073         }
20074         Slogf.w(LOG_TAG, "TelephonyManager is null when trying to get override apns");
20075         return Collections.emptyList();
20076     }
20077 
20078     @Override
20079     public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) {
20080         if (!mHasFeature || !mHasTelephonyFeature) {
20081             return;
20082         }
20083         Objects.requireNonNull(who, "ComponentName is null");
20084         final CallerIdentity caller = getCallerIdentity(who);
20085         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20086         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_OVERRIDE_APNS_ENABLED);
20087 
20088         setOverrideApnsEnabledUnchecked(enabled);
20089     }
20090 
20091     private void setOverrideApnsEnabledUnchecked(boolean enabled) {
20092         ContentValues value = new ContentValues();
20093         value.put(ENFORCE_KEY, enabled);
20094         mInjector.binderWithCleanCallingIdentity(() -> mContext.getContentResolver().update(
20095                     ENFORCE_MANAGED_URI, value, null, null));
20096     }
20097 
20098     @Override
20099     public boolean isOverrideApnEnabled(@NonNull ComponentName who) {
20100         if (!mHasFeature || !mHasTelephonyFeature) {
20101             return false;
20102         }
20103         Objects.requireNonNull(who, "ComponentName is null");
20104         final CallerIdentity caller = getCallerIdentity(who);
20105         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20106 
20107         Cursor enforceCursor = mInjector.binderWithCleanCallingIdentity(
20108                 () -> mContext.getContentResolver().query(
20109                         ENFORCE_MANAGED_URI, null, null, null, null));
20110 
20111         if (enforceCursor == null) {
20112             return false;
20113         }
20114         try {
20115             if (enforceCursor.moveToFirst()) {
20116                 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1;
20117             }
20118         } catch (IllegalArgumentException e) {
20119             Slogf.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain "
20120                     + "correct info.", e);
20121         } finally {
20122             enforceCursor.close();
20123         }
20124         return false;
20125     }
20126 
20127     @VisibleForTesting
20128     void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) {
20129         final File parametersFile = new File(
20130                 mPathProvider.getUserSystemDirectory(userId),
20131                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
20132         final AtomicFile atomicFile = new AtomicFile(parametersFile);
20133         FileOutputStream stream = null;
20134         try {
20135             stream = atomicFile.startWrite();
20136             final TypedXmlSerializer serializer = Xml.resolveSerializer(stream);
20137             serializer.startDocument(null, true);
20138             serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
20139             bundle.saveToXml(serializer);
20140             serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
20141             serializer.endDocument();
20142             atomicFile.finishWrite(stream);
20143         } catch (IOException | XmlPullParserException e) {
20144             Slogf.e(LOG_TAG, "Caught exception while trying to save the "
20145                     + "owner transfer parameters to file " + parametersFile, e);
20146             parametersFile.delete();
20147             atomicFile.failWrite(stream);
20148         }
20149     }
20150 
20151     void deleteTransferOwnershipBundleLocked(int userId) {
20152         final File parametersFile = new File(mPathProvider.getUserSystemDirectory(userId),
20153                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
20154         parametersFile.delete();
20155     }
20156 
20157     private void logPasswordQualitySetIfSecurityLogEnabled(ComponentName who, int userId,
20158             boolean parent, PasswordPolicy passwordPolicy) {
20159         if (SecurityLog.isLoggingEnabled()) {
20160             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
20161             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(),
20162                     userId, affectedUserId, passwordPolicy.length, passwordPolicy.quality,
20163                     passwordPolicy.letters, passwordPolicy.nonLetter, passwordPolicy.numeric,
20164                     passwordPolicy.upperCase, passwordPolicy.lowerCase, passwordPolicy.symbols);
20165         }
20166     }
20167 
20168     private static String getManagedProvisioningPackage(Context context) {
20169         return context.getResources().getString(R.string.config_managed_provisioning_package);
20170     }
20171 
20172     private void putPrivateDnsSettings(int mode, @Nullable String host) {
20173         // Set Private DNS settings using system permissions, as apps cannot write
20174         // to global settings.
20175         mInjector.binderWithCleanCallingIdentity(() -> {
20176             ConnectivitySettingsManager.setPrivateDnsMode(mContext, mode);
20177             ConnectivitySettingsManager.setPrivateDnsHostname(mContext, host);
20178         });
20179     }
20180 
20181     @Override
20182     public int setGlobalPrivateDns(@NonNull ComponentName who, int mode, String privateDnsHost) {
20183         if (!mHasFeature) {
20184             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
20185         }
20186         Objects.requireNonNull(who, "ComponentName is null");
20187         final CallerIdentity caller = getCallerIdentity(who);
20188         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20189         checkAllUsersAreAffiliatedWithDevice();
20190         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_GLOBAL_PRIVATE_DNS);
20191 
20192         switch (mode) {
20193             case PRIVATE_DNS_MODE_OPPORTUNISTIC:
20194                 if (!TextUtils.isEmpty(privateDnsHost)) {
20195                     throw new IllegalArgumentException(
20196                             "Host provided for opportunistic mode, but is not needed.");
20197                 }
20198                 putPrivateDnsSettings(ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC,
20199                         null);
20200                 return PRIVATE_DNS_SET_NO_ERROR;
20201             case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
20202                 if (TextUtils.isEmpty(privateDnsHost)
20203                         || !NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
20204                     throw new IllegalArgumentException(
20205                             String.format("Provided hostname %s is not valid", privateDnsHost));
20206                 }
20207 
20208                 // Connectivity check will have been performed in the DevicePolicyManager before
20209                 // the call here.
20210                 putPrivateDnsSettings(
20211                         ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
20212                         privateDnsHost);
20213                 return PRIVATE_DNS_SET_NO_ERROR;
20214             default:
20215                 throw new IllegalArgumentException(
20216                         String.format("Provided mode, %d, is not a valid mode.", mode));
20217         }
20218     }
20219 
20220     @Override
20221     public int getGlobalPrivateDnsMode(@NonNull ComponentName who) {
20222         if (!mHasFeature) {
20223             return PRIVATE_DNS_MODE_UNKNOWN;
20224         }
20225         Objects.requireNonNull(who, "ComponentName is null");
20226         final CallerIdentity caller = getCallerIdentity(who);
20227         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20228 
20229         final int currentMode = ConnectivitySettingsManager.getPrivateDnsMode(mContext);
20230         switch (currentMode) {
20231             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OFF:
20232                 return PRIVATE_DNS_MODE_OFF;
20233             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC:
20234                 return PRIVATE_DNS_MODE_OPPORTUNISTIC;
20235             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
20236                 return PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
20237         }
20238 
20239         return PRIVATE_DNS_MODE_UNKNOWN;
20240     }
20241 
20242     @Override
20243     public String getGlobalPrivateDnsHost(@NonNull ComponentName who) {
20244         if (!mHasFeature) {
20245             return null;
20246         }
20247         Objects.requireNonNull(who, "ComponentName is null");
20248         final CallerIdentity caller = getCallerIdentity(who);
20249         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20250         return mInjector.settingsGlobalGetString(PRIVATE_DNS_SPECIFIER);
20251     }
20252 
20253     @Override
20254     public void installUpdateFromFile(ComponentName admin, String callerPackageName,
20255             ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback) {
20256         if (!isPermissionCheckFlagEnabled()) {
20257             Objects.requireNonNull(admin, "ComponentName is null");
20258         }
20259 
20260         CallerIdentity caller;
20261         if (isPermissionCheckFlagEnabled()) {
20262             caller = getCallerIdentity(admin, callerPackageName);
20263             enforcePermission(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, caller.getPackageName(),
20264                     UserHandle.USER_ALL);
20265         } else {
20266             caller = getCallerIdentity(admin);
20267             Preconditions.checkCallAuthorization(
20268                     isDefaultDeviceOwner(caller)
20269                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
20270         }
20271         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_SYSTEM_UPDATE);
20272 
20273         DevicePolicyEventLogger
20274                 .createEvent(DevicePolicyEnums.INSTALL_SYSTEM_UPDATE)
20275                 .setAdmin(caller.getPackageName())
20276                 .setBoolean(isDeviceAB())
20277                 .write();
20278 
20279         mInjector.binderWithCleanCallingIdentity(() -> {
20280             UpdateInstaller updateInstaller;
20281             if (isDeviceAB()) {
20282                 updateInstaller = new AbUpdateInstaller(
20283                         mContext, updateFileDescriptor, callback, mInjector, mConstants);
20284             } else {
20285                 updateInstaller = new NonAbUpdateInstaller(
20286                         mContext, updateFileDescriptor, callback, mInjector, mConstants);
20287             }
20288             updateInstaller.startInstallUpdate();
20289         });
20290     }
20291 
20292     private boolean isDeviceAB() {
20293         return "true".equalsIgnoreCase(android.os.SystemProperties
20294                 .get(AB_DEVICE_KEY, ""));
20295     }
20296 
20297     @Override
20298     public void setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames) {
20299         if (!mHasFeature) {
20300             return;
20301         }
20302         Objects.requireNonNull(who, "ComponentName is null");
20303         final CallerIdentity caller = getCallerIdentity(who);
20304         Preconditions.checkCallAuthorization(isProfileOwner(caller));
20305 
20306         synchronized (getLockObject()) {
20307             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20308             admin.mCrossProfileCalendarPackages = packageNames;
20309             saveSettingsLocked(caller.getUserId());
20310         }
20311         DevicePolicyEventLogger
20312                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALENDAR_PACKAGES)
20313                 .setAdmin(who)
20314                 .setStrings(packageNames == null ? null
20315                         : packageNames.toArray(new String[packageNames.size()]))
20316                 .write();
20317     }
20318 
20319     @Override
20320     public List<String> getCrossProfileCalendarPackages(ComponentName who) {
20321         if (!mHasFeature) {
20322             return Collections.emptyList();
20323         }
20324         Objects.requireNonNull(who, "ComponentName is null");
20325         final CallerIdentity caller = getCallerIdentity(who);
20326         Preconditions.checkCallAuthorization(isProfileOwner(caller));
20327 
20328         synchronized (getLockObject()) {
20329             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20330             return admin.mCrossProfileCalendarPackages;
20331         }
20332     }
20333 
20334     @Override
20335     public boolean isPackageAllowedToAccessCalendarForUser(String packageName,
20336             @UserIdInt int userId) {
20337         if (!mHasFeature) {
20338             return false;
20339         }
20340         Preconditions.checkStringNotEmpty(packageName, "Package name is null or empty");
20341         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
20342 
20343         final int packageUid;
20344         try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
20345             var packageState = snapshot.getPackageStates().get(packageName);
20346             if (packageState == null) {
20347                 Slogf.w(LOG_TAG, "Couldn't find package %s in user %d", packageName,
20348                         userId);
20349                 return false;
20350             } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
20351                 Slogf.w(LOG_TAG, "Couldn't find installed package %s in user %d", packageName,
20352                         userId);
20353                 return false;
20354             } else {
20355                 packageUid = UserHandle.getUid(userId, packageState.getAppId());
20356             }
20357         }
20358         final CallerIdentity caller = getCallerIdentity();
20359         if (caller.getUid() != packageUid) {
20360             Preconditions.checkCallAuthorization(
20361                     hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)
20362                             || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL));
20363         }
20364 
20365         synchronized (getLockObject()) {
20366             if (mInjector.settingsSecureGetIntForUser(
20367                     Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userId) == 0) {
20368                 return false;
20369             }
20370             final ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
20371             if (admin != null) {
20372                 if (admin.mCrossProfileCalendarPackages == null) {
20373                     return true;
20374                 }
20375                 return admin.mCrossProfileCalendarPackages.contains(packageName);
20376             }
20377         }
20378         return false;
20379     }
20380 
20381     @Override
20382     public List<String> getCrossProfileCalendarPackagesForUser(int userHandle) {
20383         if (!mHasFeature) {
20384             return Collections.emptyList();
20385         }
20386         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
20387         Preconditions.checkCallAuthorization(
20388                 hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)
20389                         || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL));
20390 
20391         synchronized (getLockObject()) {
20392             final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
20393             if (admin != null) {
20394                 return admin.mCrossProfileCalendarPackages;
20395             }
20396         }
20397         return Collections.emptyList();
20398     }
20399 
20400     @Override
20401     public void setCrossProfilePackages(ComponentName who, List<String> packageNames) {
20402         if (!mHasFeature) {
20403             return;
20404         }
20405 
20406         Objects.requireNonNull(who, "ComponentName is null");
20407         Objects.requireNonNull(packageNames, "Package names is null");
20408         final CallerIdentity caller = getCallerIdentity(who);
20409         Preconditions.checkCallAuthorization(isProfileOwner(caller));
20410 
20411         final List<String> previousCrossProfilePackages;
20412         synchronized (getLockObject()) {
20413             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20414             previousCrossProfilePackages = admin.mCrossProfilePackages;
20415             if (packageNames.equals(previousCrossProfilePackages)) {
20416                 return;
20417             }
20418             admin.mCrossProfilePackages = packageNames;
20419             saveSettingsLocked(caller.getUserId());
20420         }
20421         logSetCrossProfilePackages(who, packageNames);
20422         final CrossProfileApps crossProfileApps =
20423                 mContext.createContextAsUser(
20424                         caller.getUserHandle(), /* flags= */ 0)
20425                         .getSystemService(CrossProfileApps.class);
20426         mInjector.binderWithCleanCallingIdentity(
20427         () -> crossProfileApps.resetInteractAcrossProfilesAppOps(
20428                         previousCrossProfilePackages, new HashSet<>(packageNames)));
20429     }
20430 
20431     private void logSetCrossProfilePackages(ComponentName who, List<String> packageNames) {
20432         DevicePolicyEventLogger
20433                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_PACKAGES)
20434                 .setAdmin(who)
20435                 .setStrings(packageNames.toArray(new String[packageNames.size()]))
20436                 .write();
20437     }
20438 
20439     @Override
20440     public List<String> getCrossProfilePackages(ComponentName who) {
20441         if (!mHasFeature) {
20442             return Collections.emptyList();
20443         }
20444         Objects.requireNonNull(who, "ComponentName is null");
20445         final CallerIdentity caller = getCallerIdentity(who);
20446         Preconditions.checkCallAuthorization(isProfileOwner(caller));
20447 
20448         synchronized (getLockObject()) {
20449             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20450             return admin.mCrossProfilePackages;
20451         }
20452     }
20453 
20454     @Override
20455     public List<String> getAllCrossProfilePackages(int userId) {
20456         if (!mHasFeature) {
20457             return Collections.emptyList();
20458         }
20459         final CallerIdentity caller = getCallerIdentity();
20460         Preconditions.checkCallAuthorization(
20461                 isSystemUid(caller) || isRootUid(caller) || hasCallingPermission(
20462                         permission.INTERACT_ACROSS_USERS) || hasCallingPermission(
20463                         permission.INTERACT_ACROSS_USERS_FULL) || hasPermissionForPreflight(
20464                                                 caller, permission.INTERACT_ACROSS_PROFILES));
20465 
20466         synchronized (getLockObject()) {
20467             final List<ActiveAdmin> admins = getProfileOwnerAdminsForProfileGroup(userId);
20468             final List<String> packages = getCrossProfilePackagesForAdmins(admins);
20469 
20470             packages.addAll(getDefaultCrossProfilePackages());
20471 
20472             return packages;
20473         }
20474     }
20475 
20476     private List<String> getCrossProfilePackagesForAdmins(List<ActiveAdmin> admins) {
20477         final List<String> packages = new ArrayList<>();
20478         for (int i = 0; i < admins.size(); i++) {
20479             packages.addAll(admins.get(i).mCrossProfilePackages);
20480         }
20481         return packages;
20482     }
20483 
20484     @Override
20485     public List<String> getDefaultCrossProfilePackages() {
20486         Set<String> crossProfilePackages = new HashSet<>();
20487 
20488         Collections.addAll(crossProfilePackages, mContext.getResources()
20489                 .getStringArray(R.array.cross_profile_apps));
20490         Collections.addAll(crossProfilePackages, mContext.getResources()
20491                 .getStringArray(R.array.vendor_cross_profile_apps));
20492 
20493         return new ArrayList<>(crossProfilePackages);
20494     }
20495 
20496     private List<ActiveAdmin> getProfileOwnerAdminsForProfileGroup(int userId) {
20497         synchronized (getLockObject()) {
20498             final List<ActiveAdmin> admins = new ArrayList<>();
20499             int[] users = mUserManager.getProfileIdsWithDisabled(userId);
20500             for (int i = 0; i < users.length; i++) {
20501                 final ComponentName componentName = getProfileOwnerAsUser(users[i]);
20502                 if (componentName != null) {
20503                     ActiveAdmin admin = getActiveAdminUncheckedLocked(componentName, users[i]);
20504                     if (admin != null) {
20505                         admins.add(admin);
20506                     }
20507                 }
20508             }
20509             return admins;
20510         }
20511     }
20512 
20513     @Override
20514     public boolean isManagedKiosk() {
20515         if (!mHasFeature) {
20516             return false;
20517         }
20518         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
20519                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
20520 
20521         long id = mInjector.binderClearCallingIdentity();
20522         try {
20523             return isManagedKioskInternal();
20524         } catch (RemoteException e) {
20525             throw new IllegalStateException(e);
20526         } finally {
20527             mInjector.binderRestoreCallingIdentity(id);
20528         }
20529     }
20530 
20531     private boolean isUnattendedManagedKioskUnchecked() {
20532         try {
20533             return isManagedKioskInternal()
20534                     && getPowerManagerInternal().wasDeviceIdleFor(UNATTENDED_MANAGED_KIOSK_MS);
20535         } catch (RemoteException e) {
20536             throw new IllegalStateException(e);
20537         }
20538     }
20539 
20540     @Override
20541     public boolean isUnattendedManagedKiosk() {
20542         if (!mHasFeature) {
20543             return false;
20544         }
20545         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
20546                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
20547 
20548         return mInjector.binderWithCleanCallingIdentity(() -> isUnattendedManagedKioskUnchecked());
20549     }
20550 
20551     /**
20552      * Returns whether the device is currently being used as a publicly-accessible dedicated device.
20553      * Assumes that feature checks and permission checks have already been performed, and that the
20554      * calling identity has been cleared.
20555      */
20556     private boolean isManagedKioskInternal() throws RemoteException {
20557         return mOwners.hasDeviceOwner()
20558                 && mInjector.getIActivityManager().getLockTaskModeState()
20559                         == ActivityManager.LOCK_TASK_MODE_LOCKED
20560                 && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO)
20561                 && !deviceHasKeyguard()
20562                 && !inEphemeralUserSession();
20563     }
20564 
20565     private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException {
20566         int lockTaskFeatures = 0;
20567         if (isPolicyEngineForFinanceFlagEnabled()) {
20568             LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
20569                     PolicyDefinition.LOCK_TASK, getCurrentForegroundUserId());
20570             lockTaskFeatures = policy == null
20571                     // We default on the power button menu, in order to be consistent with pre-P
20572                     // behaviour.
20573                     ? DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS
20574                     : policy.getFlags();
20575         } else {
20576             //TODO(b/175285301): Explicitly get the user's identity to check.
20577             lockTaskFeatures =
20578                     getUserData(getCurrentForegroundUserId()).mLockTaskFeatures;
20579         }
20580         return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature;
20581     }
20582 
20583     private boolean deviceHasKeyguard() {
20584         for (UserInfo userInfo : mUserManager.getUsers()) {
20585             if (mLockPatternUtils.isSecure(userInfo.id)) {
20586                 return true;
20587             }
20588         }
20589         return false;
20590     }
20591 
20592     private boolean inEphemeralUserSession() {
20593         for (UserInfo userInfo : mUserManager.getUsers()) {
20594             if (mInjector.getUserManager().isUserEphemeral(userInfo.id)) {
20595                 return true;
20596             }
20597         }
20598         return false;
20599     }
20600 
20601     private PowerManagerInternal getPowerManagerInternal() {
20602         return mInjector.getPowerManagerInternal();
20603     }
20604 
20605     @Override
20606     public boolean startViewCalendarEventInManagedProfile(String packageName, long eventId,
20607             long start, long end, boolean allDay, int flags) {
20608         if (!mHasFeature) {
20609             return false;
20610         }
20611         Preconditions.checkStringNotEmpty(packageName, "Package name is empty");
20612 
20613         final CallerIdentity caller = getCallerIdentity();
20614         if (!isCallingFromPackage(packageName, caller.getUid())) {
20615             throw new SecurityException("Input package name doesn't align with actual "
20616                     + "calling package.");
20617         }
20618         return mInjector.binderWithCleanCallingIdentity(() -> {
20619             final int workProfileUserId = getManagedUserId(caller.getUserId());
20620             if (workProfileUserId < 0) {
20621                 return false;
20622             }
20623             if (!isPackageAllowedToAccessCalendarForUser(packageName, workProfileUserId)) {
20624                 Slogf.d(LOG_TAG, "Package %s is not allowed to access cross-profile calendar APIs",
20625                         packageName);
20626                 return false;
20627             }
20628             final Intent intent = new Intent(
20629                     CalendarContract.ACTION_VIEW_MANAGED_PROFILE_CALENDAR_EVENT);
20630             intent.setPackage(packageName);
20631             intent.putExtra(CalendarContract.EXTRA_EVENT_ID, eventId);
20632             intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start);
20633             intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
20634             intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay);
20635             intent.setFlags(flags);
20636             try {
20637                 mContext.startActivityAsUser(intent, UserHandle.of(workProfileUserId));
20638             } catch (ActivityNotFoundException e) {
20639                 Slogf.e(LOG_TAG, "View event activity not found", e);
20640                 return false;
20641             }
20642             return true;
20643         });
20644     }
20645 
20646     @Override
20647     public void setApplicationExemptions(String callerPackage, String packageName,
20648             int[] exemptions) {
20649         if (!mHasFeature) {
20650             return;
20651         }
20652         Preconditions.checkStringNotEmpty(packageName, "Package name cannot be empty.");
20653         Objects.requireNonNull(exemptions, "Application exemptions must not be null.");
20654         Preconditions.checkArgument(areApplicationExemptionsValid(exemptions),
20655                 "Invalid application exemption constant found in application exemptions set.");
20656         Preconditions.checkCallAuthorization(
20657                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS));
20658 
20659         final CallerIdentity caller = getCallerIdentity(callerPackage);
20660         final ApplicationInfo packageInfo;
20661         packageInfo = getPackageInfoWithNullCheck(packageName, caller);
20662 
20663         for (Map.Entry<Integer, String> entry :
20664                 APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.entrySet()) {
20665             int currentMode = mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
20666                     entry.getValue(), packageInfo.uid, packageInfo.packageName);
20667             int newMode = ArrayUtils.contains(exemptions, entry.getKey())
20668                     ? MODE_ALLOWED : MODE_DEFAULT;
20669             mInjector.binderWithCleanCallingIdentity(() -> {
20670                 if (currentMode != newMode) {
20671                     mInjector.getAppOpsManager()
20672                             .setMode(entry.getValue(),
20673                                     packageInfo.uid,
20674                                     packageName,
20675                                     newMode);
20676                 }
20677             });
20678         }
20679         String[] appOpExemptions = new String[exemptions.length];
20680         for (int i = 0; i < exemptions.length; i++) {
20681             appOpExemptions[i] = APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.get(exemptions[i]);
20682         }
20683         DevicePolicyEventLogger
20684             .createEvent(DevicePolicyEnums.SET_APPLICATION_EXEMPTIONS)
20685             .setAdmin(caller.getPackageName())
20686             .setStrings(packageName, appOpExemptions)
20687             .write();
20688     }
20689 
20690     @Override
20691     public int[] getApplicationExemptions(String packageName) {
20692         if (!mHasFeature) {
20693             return new int[0];
20694         }
20695         Preconditions.checkStringNotEmpty(packageName, "Package name cannot be empty.");
20696         Preconditions.checkCallAuthorization(
20697                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS));
20698 
20699         final CallerIdentity caller = getCallerIdentity();
20700         final ApplicationInfo packageInfo;
20701         packageInfo = getPackageInfoWithNullCheck(packageName, caller);
20702 
20703         IntArray appliedExemptions = new IntArray(0);
20704         for (Map.Entry<Integer, String> entry :
20705                 APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.entrySet()) {
20706             if (mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
20707                     entry.getValue(), packageInfo.uid, packageInfo.packageName) == MODE_ALLOWED) {
20708                 appliedExemptions.add(entry.getKey());
20709             }
20710         }
20711         return appliedExemptions.toArray();
20712     }
20713 
20714     private ApplicationInfo getPackageInfoWithNullCheck(String packageName, CallerIdentity caller) {
20715         final ApplicationInfo packageInfo =
20716                 mInjector.getPackageManagerInternal().getApplicationInfo(
20717                         packageName,
20718                         /* flags= */ 0,
20719                         caller.getUid(),
20720                         caller.getUserId());
20721         if (packageInfo == null) {
20722             throw new ServiceSpecificException(
20723                     DevicePolicyManager.ERROR_PACKAGE_NAME_NOT_FOUND,
20724                     "Package name not found.");
20725         }
20726         return packageInfo;
20727     }
20728 
20729     private boolean areApplicationExemptionsValid(int[] exemptions) {
20730         for (int exemption : exemptions) {
20731             if (!APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.containsKey(exemption)) {
20732                 return false;
20733             }
20734         }
20735         return true;
20736     }
20737 
20738     private boolean isCallingFromPackage(String packageName, int callingUid) {
20739         try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
20740             var packageState = snapshot.getPackageStates().get(packageName);
20741             var userId = UserHandle.getUserId(callingUid);
20742             if (packageState == null) {
20743                 Slogf.d(LOG_TAG, "Calling UID " + callingUid + " not found");
20744                 return false;
20745             } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
20746                 Slogf.d(LOG_TAG, "Calling UID " + callingUid + " not installed");
20747                 return false;
20748             } else {
20749                 return callingUid == UserHandle.getUid(userId, packageState.getAppId());
20750             }
20751         }
20752     }
20753 
20754     private DevicePolicyConstants loadConstants() {
20755         return DevicePolicyConstants.loadFromString(
20756                 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
20757     }
20758 
20759     @Override
20760     public void setUserControlDisabledPackages(ComponentName who, String callerPackageName,
20761             List<String> packages) {
20762         Objects.requireNonNull(packages, "packages is null");
20763         CallerIdentity caller;
20764         if (isPolicyEngineForFinanceFlagEnabled()) {
20765             caller = getCallerIdentity(who, callerPackageName);
20766         } else {
20767             caller = getCallerIdentity(who);
20768         }
20769         checkCanExecuteOrThrowUnsafe(
20770                 DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES);
20771 
20772         if (isPolicyEngineForFinanceFlagEnabled()) {
20773             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
20774                     who,
20775                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
20776                     caller.getPackageName(),
20777                     caller.getUserId());
20778             Binder.withCleanCallingIdentity(() -> {
20779                 if (packages.isEmpty()) {
20780                     removeUserControlDisabledPackages(caller, enforcingAdmin);
20781                 } else {
20782                     addUserControlDisabledPackages(caller, enforcingAdmin, new HashSet<>(packages));
20783                 }
20784             });
20785         } else {
20786             Objects.requireNonNull(who, "ComponentName is null");
20787             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
20788                     || isProfileOwner(caller) || isFinancedDeviceOwner(caller));
20789             synchronized (getLockObject()) {
20790                 ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
20791                 if (!Objects.equals(admin.protectedPackages, packages)) {
20792                     admin.protectedPackages = packages.isEmpty() ? null : packages;
20793                     saveSettingsLocked(caller.getUserId());
20794                     pushUserControlDisabledPackagesLocked(caller.getUserId());
20795                 }
20796             }
20797         }
20798 
20799         DevicePolicyEventLogger
20800                 .createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES)
20801                 .setAdmin(caller.getPackageName())
20802                 .setStrings(packages.toArray(new String[packages.size()]))
20803                 .write();
20804     }
20805 
20806     private void addUserControlDisabledPackages(CallerIdentity caller,
20807             EnforcingAdmin enforcingAdmin, Set<String> packages) {
20808         if (isDeviceOwner(caller)) {
20809             mDevicePolicyEngine.setGlobalPolicy(
20810                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20811                     enforcingAdmin,
20812                     new StringSetPolicyValue(packages));
20813         } else {
20814             mDevicePolicyEngine.setLocalPolicy(
20815                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20816                     enforcingAdmin,
20817                     new StringSetPolicyValue(packages),
20818                     caller.getUserId());
20819         }
20820     }
20821 
20822     private void removeUserControlDisabledPackages(CallerIdentity caller,
20823             EnforcingAdmin enforcingAdmin) {
20824         if (isDeviceOwner(caller)) {
20825             mDevicePolicyEngine.removeGlobalPolicy(
20826                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20827                     enforcingAdmin);
20828         } else {
20829             mDevicePolicyEngine.removeLocalPolicy(
20830                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20831                     enforcingAdmin,
20832                     caller.getUserId());
20833         }
20834     }
20835 
20836     @Override
20837     public List<String> getUserControlDisabledPackages(ComponentName who,
20838             String callerPackageName) {
20839         CallerIdentity caller;
20840         if (isPolicyEngineForFinanceFlagEnabled()) {
20841             caller = getCallerIdentity(who, callerPackageName);
20842         } else {
20843             caller = getCallerIdentity(who);
20844         }
20845 
20846         if (isPolicyEngineForFinanceFlagEnabled()) {
20847             enforceCanQuery(
20848                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
20849                     caller.getPackageName(),
20850                     caller.getUserId());
20851             // This retrieves the policy for the calling user only, DOs for example can't know
20852             // what's enforced globally or on another user.
20853             Set<String> packages = mDevicePolicyEngine.getResolvedPolicy(
20854                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20855                     caller.getUserId());
20856             return packages == null ? Collections.emptyList() : packages.stream().toList();
20857         } else {
20858             Objects.requireNonNull(who, "ComponentName is null");
20859             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
20860                     || isProfileOwner(caller) || isFinancedDeviceOwner(caller));
20861             synchronized (getLockObject()) {
20862                 ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
20863                 return admin.protectedPackages != null
20864                         ? admin.protectedPackages : Collections.emptyList();
20865             }
20866         }
20867     }
20868 
20869     @Override
20870     public void setCommonCriteriaModeEnabled(ComponentName who, String callerPackageName,
20871             boolean enabled) {
20872         CallerIdentity caller;
20873         if (isPermissionCheckFlagEnabled()) {
20874             caller = getCallerIdentity(who, callerPackageName);
20875         } else {
20876             caller = getCallerIdentity(who);
20877         }
20878         final ActiveAdmin admin;
20879 
20880         if (isPermissionCheckFlagEnabled()) {
20881             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
20882                     who,
20883                     MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
20884                     caller.getPackageName(),
20885                     caller.getUserId());
20886             admin = enforcingAdmin.getActiveAdmin();
20887         } else {
20888             Objects.requireNonNull(who, "ComponentName is null");
20889             Preconditions.checkCallAuthorization(
20890                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
20891                     "Common Criteria mode can only be controlled by a device owner or "
20892                             + "a profile owner on an organization-owned device.");
20893             synchronized (getLockObject()) {
20894                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
20895             }
20896         }
20897         synchronized (getLockObject()) {
20898             admin.mCommonCriteriaMode = enabled;
20899             saveSettingsLocked(caller.getUserId());
20900         }
20901         DevicePolicyEventLogger
20902                 .createEvent(DevicePolicyEnums.SET_COMMON_CRITERIA_MODE)
20903                 .setAdmin(caller.getPackageName())
20904                 .setBoolean(enabled)
20905                 .write();
20906     }
20907 
20908     @Override
20909     public boolean isCommonCriteriaModeEnabled(ComponentName who) {
20910         if (who != null) {
20911             final CallerIdentity caller = getCallerIdentity(who);
20912             Preconditions.checkCallAuthorization(
20913                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
20914                     "Common Criteria mode can only be controlled by a device owner or "
20915                             + "a profile owner on an organization-owned device.");
20916 
20917             synchronized (getLockObject()) {
20918                 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
20919                 return admin.mCommonCriteriaMode;
20920             }
20921         }
20922 
20923         // Return aggregated state if caller is not admin (who == null).
20924         synchronized (getLockObject()) {
20925             // Only DO or COPE PO can turn on CC mode, so take a shortcut here and only look at
20926             // their ActiveAdmin, instead of iterating through all admins.
20927             ActiveAdmin admin;
20928             // TODO(b/261999445): remove
20929             if (isHeadlessFlagEnabled()) {
20930                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
20931             } else {
20932                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
20933                         UserHandle.USER_SYSTEM);
20934             }
20935             return admin != null ? admin.mCommonCriteriaMode : false;
20936         }
20937     }
20938 
20939     @Override
20940     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(ComponentName who) {
20941         Objects.requireNonNull(who, "ComponentName is null");
20942 
20943         final CallerIdentity caller = getCallerIdentity(who);
20944         // DO shouldn't be able to use this method.
20945         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
20946 
20947         synchronized (getLockObject()) {
20948             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20949             final long deadline = admin.mProfileOffDeadline;
20950             final int result = makeSuspensionReasons(admin.mSuspendPersonalApps,
20951                     deadline != 0 && mInjector.systemCurrentTimeMillis() > deadline);
20952             Slogf.d(LOG_TAG, "getPersonalAppsSuspendedReasons user: %d; result: %d",
20953                     mInjector.userHandleGetCallingUserId(), result);
20954             return result;
20955         }
20956     }
20957 
20958     private @PersonalAppsSuspensionReason int makeSuspensionReasons(
20959             boolean explicit, boolean timeout) {
20960         int result = PERSONAL_APPS_NOT_SUSPENDED;
20961         if (explicit) {
20962             result |= PERSONAL_APPS_SUSPENDED_EXPLICITLY;
20963         }
20964         if (timeout) {
20965             result |= PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT;
20966         }
20967         return result;
20968     }
20969 
20970     @Override
20971     public void setPersonalAppsSuspended(ComponentName who, boolean suspended) {
20972         Objects.requireNonNull(who, "ComponentName is null");
20973 
20974         final CallerIdentity caller = getCallerIdentity(who);
20975         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
20976         Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller));
20977 
20978         final int callingUserId = caller.getUserId();
20979         synchronized (getLockObject()) {
20980             final ActiveAdmin admin = getProfileOwnerLocked(callingUserId);
20981             boolean shouldSaveSettings = false;
20982             if (admin.mSuspendPersonalApps != suspended) {
20983                 admin.mSuspendPersonalApps = suspended;
20984                 shouldSaveSettings = true;
20985             }
20986             if (admin.mProfileOffDeadline != 0) {
20987                 admin.mProfileOffDeadline = 0;
20988                 shouldSaveSettings = true;
20989             }
20990             if (shouldSaveSettings) {
20991                 saveSettingsLocked(callingUserId);
20992             }
20993         }
20994 
20995         mInjector.binderWithCleanCallingIdentity(() -> updatePersonalAppsSuspension(
20996                 callingUserId));
20997 
20998         DevicePolicyEventLogger
20999                 .createEvent(DevicePolicyEnums.SET_PERSONAL_APPS_SUSPENDED)
21000                 .setAdmin(caller.getComponentName())
21001                 .setBoolean(suspended)
21002                 .write();
21003     }
21004 
21005     /** Starts an activity to check policy compliance or request compliance acknowledgement. */
21006     private void triggerPolicyComplianceCheckIfNeeded(int profileUserId, boolean suspended) {
21007         synchronized (getLockObject()) {
21008             final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
21009             if (profileOwner == null) {
21010                 Slogf.wtf(LOG_TAG, "Profile owner not found for compliance check");
21011                 return;
21012             }
21013             if (suspended) {
21014                 // If suspended, DPC will need to show an activity.
21015                 final Intent intent = new Intent(ACTION_CHECK_POLICY_COMPLIANCE);
21016                 intent.setPackage(profileOwner.info.getPackageName());
21017                 mContext.startActivityAsUser(intent, UserHandle.of(profileUserId));
21018             } else if (profileOwner.mProfileOffDeadline > 0) {
21019                 // If not suspended, but deadline set, DPC needs to acknowledge compliance so that
21020                 // the deadline can be reset.
21021                 sendAdminCommandLocked(profileOwner, ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED,
21022                         /* adminExtras= */ null, /* receiver= */ null, /* inForeground = */ true);
21023             }
21024         }
21025     }
21026 
21027     /**
21028      * Checks whether personal apps should be suspended according to the policy and applies the
21029      * change if needed.
21030      */
21031     private boolean updatePersonalAppsSuspension(int profileUserId) {
21032         final boolean shouldSuspend;
21033         synchronized (getLockObject()) {
21034             final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
21035             if (profileOwner != null) {
21036                 // Profile is considered "off" when it is either not running or is running locked
21037                 // or is in quiet mode, i.e. when the admin cannot sync policies or show UI.
21038                 boolean profileUserOff =
21039                         !mUserManagerInternal.isUserUnlockingOrUnlocked(profileUserId)
21040                         || mUserManager.isQuietModeEnabled(UserHandle.of(profileUserId));
21041                 final int notificationState = updateProfileOffDeadlineLocked(
21042                         profileUserId, profileOwner, profileUserOff);
21043                 final boolean suspendedExplicitly = profileOwner.mSuspendPersonalApps;
21044                 final boolean suspendedByTimeout = profileOwner.mProfileOffDeadline == -1;
21045                 Slogf.d(LOG_TAG,
21046                         "Personal apps suspended explicitly: %b, by timeout: %b, notification: %d",
21047                         suspendedExplicitly, suspendedByTimeout, notificationState);
21048                 updateProfileOffDeadlineNotificationLocked(
21049                         profileUserId, profileOwner, notificationState);
21050                 shouldSuspend = suspendedExplicitly || suspendedByTimeout;
21051             } else {
21052                 shouldSuspend = false;
21053             }
21054         }
21055 
21056         final int parentUserId = getProfileParentId(profileUserId);
21057         suspendPersonalAppsInternal(parentUserId, profileUserId, shouldSuspend);
21058         return shouldSuspend;
21059     }
21060 
21061     /**
21062      * Checks work profile time off policy, scheduling personal apps suspension via alarm if
21063      * necessary.
21064      * @return notification state
21065      */
21066     private int updateProfileOffDeadlineLocked(
21067             int profileUserId, ActiveAdmin profileOwner, boolean off) {
21068         final long now = mInjector.systemCurrentTimeMillis();
21069         if (profileOwner.mProfileOffDeadline != 0 && now > profileOwner.mProfileOffDeadline) {
21070             Slogf.i(LOG_TAG, "Profile off deadline has been reached, off: " + off);
21071             if (profileOwner.mProfileOffDeadline != -1) {
21072                 // Move the deadline far to the past so that it cannot be rolled back by TZ change.
21073                 profileOwner.mProfileOffDeadline = -1;
21074                 saveSettingsLocked(profileUserId);
21075             }
21076             return off ? PROFILE_OFF_NOTIFICATION_SUSPENDED : PROFILE_OFF_NOTIFICATION_NONE;
21077         }
21078         boolean shouldSaveSettings = false;
21079         if (profileOwner.mSuspendPersonalApps) {
21080             // When explicit suspension is active, deadline shouldn't be set.
21081             if (profileOwner.mProfileOffDeadline != 0) {
21082                 profileOwner.mProfileOffDeadline = 0;
21083                 shouldSaveSettings = true;
21084             }
21085         } else if (profileOwner.mProfileOffDeadline != 0
21086                 && (profileOwner.mProfileMaximumTimeOffMillis == 0)) {
21087             // There is a deadline but either there is no policy -> clear
21088             // the deadline.
21089             Slogf.i(LOG_TAG, "Profile off deadline is reset to zero");
21090             profileOwner.mProfileOffDeadline = 0;
21091             shouldSaveSettings = true;
21092         } else if (profileOwner.mProfileOffDeadline == 0
21093                 && (profileOwner.mProfileMaximumTimeOffMillis != 0 && off)) {
21094             // There profile is locked and there is a policy, but the deadline is not set -> set the
21095             // deadline.
21096             Slogf.i(LOG_TAG, "Profile off deadline is set.");
21097             profileOwner.mProfileOffDeadline = now + profileOwner.mProfileMaximumTimeOffMillis;
21098             shouldSaveSettings = true;
21099         }
21100 
21101         if (shouldSaveSettings) {
21102             saveSettingsLocked(profileUserId);
21103         }
21104 
21105         final long alarmTime;
21106         final int notificationState;
21107         if (!off || profileOwner.mProfileOffDeadline == 0) {
21108             alarmTime = 0;
21109             notificationState = PROFILE_OFF_NOTIFICATION_NONE;
21110         } else if (profileOwner.mProfileOffDeadline - now < MANAGED_PROFILE_OFF_WARNING_PERIOD) {
21111             // The deadline is close, upon the alarm personal apps should be suspended.
21112             alarmTime = profileOwner.mProfileOffDeadline;
21113             notificationState = PROFILE_OFF_NOTIFICATION_WARNING;
21114         } else {
21115             // The deadline is quite far, upon the alarm we should warn the user first, so the
21116             // alarm is scheduled earlier than the actual deadline.
21117             alarmTime = profileOwner.mProfileOffDeadline - MANAGED_PROFILE_OFF_WARNING_PERIOD;
21118             notificationState = PROFILE_OFF_NOTIFICATION_NONE;
21119         }
21120 
21121         final AlarmManager am = mInjector.getAlarmManager();
21122         final Intent intent = new Intent(ACTION_PROFILE_OFF_DEADLINE);
21123         intent.setPackage(mContext.getPackageName());
21124         // Broadcast alarms sent by system are immutable
21125         final PendingIntent pi = mInjector.pendingIntentGetBroadcast(
21126                 mContext, REQUEST_PROFILE_OFF_DEADLINE, intent,
21127                 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
21128                         | PendingIntent.FLAG_IMMUTABLE);
21129 
21130         if (alarmTime == 0) {
21131             Slogf.i(LOG_TAG, "Profile off deadline alarm is removed.");
21132             am.cancel(pi);
21133         } else {
21134             Slogf.i(LOG_TAG, "Profile off deadline alarm is set.");
21135             am.set(AlarmManager.RTC, alarmTime, pi);
21136         }
21137 
21138         return notificationState;
21139     }
21140 
21141     private void suspendPersonalAppsInternal(
21142             int parentUserId, int profileUserId, boolean suspended) {
21143         if (getUserData(parentUserId).mAppsSuspended == suspended) {
21144             return;
21145         }
21146         Slogf.i(LOG_TAG, "%s personal apps for user %d", suspended ? "Suspending" : "Unsuspending",
21147                 parentUserId);
21148 
21149         if (isPolicyEngineForFinanceFlagEnabled()) {
21150             // TODO(b/280602237): migrate properly
21151             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
21152             if (profileOwner != null) {
21153                 EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
21154                         profileOwner.info.getComponent(),
21155                         profileUserId,
21156                         profileOwner);
21157                 mDevicePolicyEngine.setLocalPolicy(
21158                         PolicyDefinition.PERSONAL_APPS_SUSPENDED,
21159                         admin,
21160                         new BooleanPolicyValue(suspended),
21161                         parentUserId);
21162             }
21163         } else {
21164             if (suspended) {
21165                 suspendPersonalAppsInPackageManager(parentUserId);
21166             } else {
21167                 mInjector.getPackageManagerInternal().unsuspendForSuspendingPackage(
21168                         PLATFORM_PACKAGE_NAME, parentUserId);
21169             }
21170         }
21171 
21172         synchronized (getLockObject()) {
21173             getUserData(parentUserId).mAppsSuspended = suspended;
21174             saveSettingsLocked(parentUserId);
21175         }
21176     }
21177 
21178     private void suspendPersonalAppsInPackageManager(int userId) {
21179         mInjector.binderWithCleanCallingIdentity(() -> {
21180             final String[] appsToSuspend = mInjector.getPersonalAppsForSuspension(userId);
21181             final String[] failedApps = mInjector.getPackageManagerInternal()
21182                     .setPackagesSuspendedByAdmin(userId, appsToSuspend, true);
21183             if (!ArrayUtils.isEmpty(failedApps)) {
21184                 Slogf.wtf(LOG_TAG, "Failed to suspend apps: " + String.join(",", failedApps));
21185             }
21186         });
21187     }
21188 
21189     private void notifyIfManagedSubscriptionsAreUnavailable(
21190             UserHandle managedProfile, boolean managedProfileAvailable) {
21191         if (!isManagedProfile(managedProfile.getIdentifier())) {
21192             Slog.wtf(
21193                     LOG_TAG,
21194                     "Expected managed profile when notified of profile availability change.");
21195         }
21196         if (getManagedSubscriptionsPolicy().getPolicyType()
21197                 != ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
21198             // There may be a subscription in the personal profile, in which case calls and
21199             // texts may still be available. No need to notify the user.
21200             return;
21201         }
21202         if (managedProfileAvailable) {
21203             // When quiet mode is switched off calls and texts then become available to the user,
21204             // so no need to keep showing the notification.
21205             mInjector
21206                     .getNotificationManager()
21207                     .cancel(SystemMessage.NOTE_ALL_MANAGED_SUBSCRIPTIONS_AND_MANAGED_PROFILE_OFF);
21208             return;
21209         }
21210         final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION);
21211         intent.putExtra(Intent.EXTRA_USER_HANDLE, managedProfile.getIdentifier());
21212         final PendingIntent pendingIntent =
21213                 mInjector.pendingIntentGetBroadcast(
21214                         mContext,
21215                         /* requestCode= */ 0,
21216                         intent,
21217                         PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
21218         final Notification.Action turnProfileOnButton =
21219                 new Notification.Action.Builder(
21220                         /* icon= */ null, getUnpauseWorkAppsButtonText(), pendingIntent)
21221                         .build();
21222 
21223         final Bundle extras = new Bundle();
21224         extras.putString(
21225                 Notification.EXTRA_SUBSTITUTE_APP_NAME, getWorkProfileContentDescription());
21226         final Notification notification =
21227                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
21228                         .setSmallIcon(R.drawable.ic_phone_disabled)
21229                         .setContentTitle(getUnpauseWorkAppsForTelephonyTitle())
21230                         .setContentText(getUnpauseWorkAppsForTelephonyText())
21231                         .setStyle(new Notification.BigTextStyle().bigText(
21232                                 getUnpauseWorkAppsForTelephonyText()))
21233                         .addAction(turnProfileOnButton)
21234                         .addExtras(extras)
21235                         .setOngoing(false)
21236                         .setShowWhen(true)
21237                         .setAutoCancel(true)
21238                         .build();
21239 
21240         mInjector
21241                 .getNotificationManager()
21242                 .notifyAsUser(
21243                         /* tag= */ null,
21244                         SystemMessage.NOTE_ALL_MANAGED_SUBSCRIPTIONS_AND_MANAGED_PROFILE_OFF,
21245                         notification,
21246                         UserHandle.of(getProfileParentId(managedProfile.getIdentifier())));
21247     }
21248 
21249     private String getUnpauseWorkAppsButtonText() {
21250         return getUpdatableString(
21251                 WORK_PROFILE_TELEPHONY_PAUSED_TURN_ON_BUTTON,
21252                 R.string.work_profile_telephony_paused_turn_on_button);
21253     }
21254 
21255     private String getUnpauseWorkAppsForTelephonyTitle() {
21256         return getUpdatableString(
21257                 WORK_PROFILE_TELEPHONY_PAUSED_TITLE, R.string.work_profile_telephony_paused_title);
21258     }
21259 
21260     private String getUnpauseWorkAppsForTelephonyText() {
21261         return getUpdatableString(
21262                 WORK_PROFILE_TELEPHONY_PAUSED_BODY,
21263                 R.string.work_profile_telephony_paused_text);
21264     }
21265 
21266     @GuardedBy("getLockObject()")
21267     private void updateProfileOffDeadlineNotificationLocked(
21268             int profileUserId, ActiveAdmin profileOwner, int notificationState) {
21269         if (notificationState == PROFILE_OFF_NOTIFICATION_NONE) {
21270             mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED);
21271             return;
21272         }
21273 
21274         final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION);
21275         intent.setPackage(mContext.getPackageName());
21276         intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
21277 
21278         // Simple notification action button clicks are immutable
21279         final PendingIntent pendingIntent = mInjector.pendingIntentGetBroadcast(mContext,
21280                 0 /* requestCode */, intent,
21281                 PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
21282 
21283         final Notification.Action turnProfileOnButton = new Notification.Action.Builder(
21284                 /* icon= */ null, getPersonalAppSuspensionButtonText(), pendingIntent).build();
21285 
21286         final String text;
21287         final boolean ongoing;
21288         if (notificationState == PROFILE_OFF_NOTIFICATION_WARNING) {
21289             // Round to the closest integer number of days.
21290             final int maxDays = (int)
21291                     ((profileOwner.mProfileMaximumTimeOffMillis + MS_PER_DAY / 2) / MS_PER_DAY);
21292             final String date = DateUtils.formatDateTime(
21293                     mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_DATE);
21294             final String time = DateUtils.formatDateTime(
21295                     mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_TIME);
21296             text = getPersonalAppSuspensionSoonText(date, time, maxDays);
21297             ongoing = false;
21298         } else {
21299             text = getPersonalAppSuspensionText();
21300             ongoing = true;
21301         }
21302         final int color = mContext.getColor(R.color.personal_apps_suspension_notification_color);
21303         final Bundle extras = new Bundle();
21304         // TODO: Create a separate string for this.
21305         extras.putString(
21306                 Notification.EXTRA_SUBSTITUTE_APP_NAME, getWorkProfileContentDescription());
21307 
21308         final Notification notification =
21309                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
21310                         .setSmallIcon(R.drawable.ic_corp_badge_no_background)
21311                         .setOngoing(ongoing)
21312                         .setAutoCancel(false)
21313                         .setContentTitle(getPersonalAppSuspensionTitle())
21314                         .setContentText(text)
21315                         .setStyle(new Notification.BigTextStyle().bigText(text))
21316                         .setColor(color)
21317                         .addAction(turnProfileOnButton)
21318                         .addExtras(extras)
21319                         .build();
21320 
21321         mHandler.post(() -> mInjector.getNotificationManager().notifyAsUser(
21322                 null, SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED, notification,
21323                 UserHandle.of(getProfileParentId(profileUserId))));
21324     }
21325 
21326     private String getPersonalAppSuspensionButtonText() {
21327         return getUpdatableString(
21328                 PERSONAL_APP_SUSPENSION_TURN_ON_PROFILE,
21329                 R.string.personal_apps_suspended_turn_profile_on);
21330     }
21331 
21332     private String getPersonalAppSuspensionTitle() {
21333         return getUpdatableString(
21334                 PERSONAL_APP_SUSPENSION_TITLE, R.string.personal_apps_suspension_title);
21335     }
21336 
21337     private String getPersonalAppSuspensionText() {
21338         return getUpdatableString(
21339                 PERSONAL_APP_SUSPENSION_MESSAGE, R.string.personal_apps_suspension_text);
21340     }
21341 
21342     private String getPersonalAppSuspensionSoonText(String date, String time, int maxDays) {
21343         return getUpdatableString(
21344                 PERSONAL_APP_SUSPENSION_SOON_MESSAGE, R.string.personal_apps_suspension_soon_text,
21345                 date, time, maxDays);
21346     }
21347 
21348     private String getWorkProfileContentDescription() {
21349         return getUpdatableString(
21350                 NOTIFICATION_WORK_PROFILE_CONTENT_DESCRIPTION,
21351                 R.string.notification_work_profile_content_description);
21352     }
21353 
21354     @Override
21355     public void setManagedProfileMaximumTimeOff(ComponentName who, long timeoutMillis) {
21356         Objects.requireNonNull(who, "ComponentName is null");
21357         Preconditions.checkArgumentNonnegative(timeoutMillis, "Timeout must be non-negative.");
21358 
21359         final CallerIdentity caller = getCallerIdentity(who);
21360         // DO shouldn't be able to use this method.
21361         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
21362         Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller));
21363 
21364         final int userId = caller.getUserId();
21365         synchronized (getLockObject()) {
21366             final ActiveAdmin admin = getProfileOwnerLocked(userId);
21367 
21368             // Ensure the timeout is long enough to avoid having bad user experience.
21369             if (timeoutMillis > 0 && timeoutMillis < MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD
21370                     && !isAdminTestOnlyLocked(who, userId)) {
21371                 timeoutMillis = MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD;
21372             }
21373             if (admin.mProfileMaximumTimeOffMillis == timeoutMillis) {
21374                 return;
21375             }
21376             admin.mProfileMaximumTimeOffMillis = timeoutMillis;
21377             saveSettingsLocked(userId);
21378         }
21379 
21380         mInjector.binderWithCleanCallingIdentity(
21381                 () -> updatePersonalAppsSuspension(userId));
21382 
21383         DevicePolicyEventLogger
21384                 .createEvent(DevicePolicyEnums.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF)
21385                 .setAdmin(caller.getComponentName())
21386                 .setTimePeriod(timeoutMillis)
21387                 .write();
21388     }
21389 
21390     private boolean canHandleCheckPolicyComplianceIntent(CallerIdentity caller) {
21391         mInjector.binderWithCleanCallingIdentity(() -> {
21392             final Intent intent = new Intent(DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE);
21393             intent.setPackage(caller.getPackageName());
21394             final List<ResolveInfo> handlers =
21395                     mInjector.getPackageManager().queryIntentActivitiesAsUser(intent, /* flags= */
21396                             0, caller.getUserId());
21397             return !handlers.isEmpty();
21398         });
21399         return true;
21400     }
21401 
21402     @Override
21403     public long getManagedProfileMaximumTimeOff(ComponentName who) {
21404         Objects.requireNonNull(who, "ComponentName is null");
21405 
21406         final CallerIdentity caller = getCallerIdentity(who);
21407         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
21408 
21409         synchronized (getLockObject()) {
21410             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
21411             return admin.mProfileMaximumTimeOffMillis;
21412         }
21413     }
21414 
21415     @Override
21416     public void acknowledgeDeviceCompliant() {
21417         final CallerIdentity caller = getCallerIdentity();
21418         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
21419         enforceUserUnlocked(caller.getUserId());
21420 
21421         synchronized (getLockObject()) {
21422             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
21423             if (admin.mProfileOffDeadline > 0) {
21424                 admin.mProfileOffDeadline = 0;
21425                 saveSettingsLocked(caller.getUserId());
21426             }
21427         }
21428     }
21429 
21430     @Override
21431     public boolean isComplianceAcknowledgementRequired() {
21432         final CallerIdentity caller = getCallerIdentity();
21433         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
21434         enforceUserUnlocked(caller.getUserId());
21435 
21436         synchronized (getLockObject()) {
21437             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
21438             return admin.mProfileOffDeadline != 0;
21439         }
21440     }
21441 
21442     @Override
21443     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
21444         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
21445                 String.format(NOT_SYSTEM_CALLER_MSG,
21446                         "call canProfileOwnerResetPasswordWhenLocked"));
21447         synchronized (getLockObject()) {
21448             final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(userId);
21449             DevicePolicyData policy = getUserData(userId);
21450             if (poAdmin == null
21451                     || getEncryptionStatus() != ENCRYPTION_STATUS_ACTIVE_PER_USER
21452                     || !isResetPasswordTokenActiveForUserLocked(
21453                             policy.mPasswordTokenHandle, userId)) {
21454                 return false;
21455             }
21456             final ApplicationInfo poAppInfo;
21457             try {
21458                 poAppInfo = mIPackageManager.getApplicationInfo(
21459                         poAdmin.info.getPackageName(), 0 /* flags */, userId);
21460             } catch (RemoteException e) {
21461                 Slogf.e(LOG_TAG, "Failed to query PO app info", e);
21462                 return false;
21463             }
21464             if (poAppInfo == null) {
21465                 Slogf.wtf(LOG_TAG, "Cannot find AppInfo for profile owner");
21466                 return false;
21467             }
21468             if (!poAppInfo.isEncryptionAware()) {
21469                 return false;
21470             }
21471             Slogf.d(LOG_TAG, "PO should be able to reset password from direct boot");
21472             return true;
21473         }
21474     }
21475 
21476     @Override
21477     public String getEnrollmentSpecificId(String callerPackage) {
21478         if (!mHasFeature) {
21479             return "";
21480         }
21481 
21482         final CallerIdentity caller = getCallerIdentity(callerPackage);
21483         Preconditions.checkCallAuthorization(
21484                 isDefaultDeviceOwner(caller) || isProfileOwner(caller)
21485                         || isCallerDelegate(caller, DELEGATION_CERT_INSTALL));
21486 
21487         synchronized (getLockObject()) {
21488             final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
21489                     caller.getUserId());
21490             final String esid = requiredAdmin.mEnrollmentSpecificId;
21491             return esid != null ? esid : "";
21492         }
21493     }
21494 
21495     @Override
21496     public void setOrganizationIdForUser(
21497             @NonNull String callerPackage, @NonNull String organizationId, int userId) {
21498         if (!mHasFeature) {
21499             return;
21500         }
21501         Objects.requireNonNull(callerPackage);
21502 
21503         final CallerIdentity caller = getCallerIdentity(callerPackage);
21504         // Only the DPC can set this ID.
21505         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) || isProfileOwner(caller),
21506                 "Only a Device Owner or Profile Owner may set the Enterprise ID.");
21507         // Empty enterprise ID must not be provided in calls to this method.
21508         Preconditions.checkArgument(!TextUtils.isEmpty(organizationId),
21509                 "Enterprise ID may not be empty.");
21510 
21511         Slogf.i(LOG_TAG, "Setting Enterprise ID to %s for user %d", organizationId, userId);
21512 
21513         synchronized (mESIDInitilizationLock) {
21514             if (mEsidCalculator == null) {
21515                 mInjector.binderWithCleanCallingIdentity(() -> {
21516                     mEsidCalculator = mInjector.newEnterpriseSpecificIdCalculator();
21517                 });
21518             }
21519         }
21520 
21521         final String ownerPackage;
21522         synchronized (getLockObject()) {
21523             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
21524             // As the caller is the system, it must specify the component name of the profile owner
21525             // as a safety check.
21526             Preconditions.checkCallAuthorization(
21527                     owner != null && owner.getUserHandle().getIdentifier() == userId,
21528                     String.format("The Profile Owner or Device Owner may only set the Enterprise ID"
21529                             + " on its own user, called on user %d but owner user is %d", userId,
21530                             owner.getUserHandle().getIdentifier()));
21531             ownerPackage = owner.info.getPackageName();
21532             Preconditions.checkState(
21533                     TextUtils.isEmpty(owner.mOrganizationId) || owner.mOrganizationId.equals(
21534                             organizationId),
21535                     "The organization ID has been previously set to a different value and cannot "
21536                             + "be changed");
21537             final String dpcPackage = owner.info.getPackageName();
21538             final String esid = mEsidCalculator.calculateEnterpriseId(dpcPackage,
21539                     organizationId);
21540             owner.mOrganizationId = organizationId;
21541             owner.mEnrollmentSpecificId = esid;
21542             saveSettingsLocked(userId);
21543         }
21544 
21545         DevicePolicyEventLogger
21546                 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_ID)
21547                 .setAdmin(ownerPackage)
21548                 .setBoolean(isManagedProfile(userId))
21549                 .write();
21550     }
21551 
21552     @Override
21553     public void clearOrganizationIdForUser(int userHandle) {
21554         Preconditions.checkCallAuthorization(
21555                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
21556 
21557         synchronized (getLockObject()) {
21558             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userHandle);
21559             owner.mOrganizationId = null;
21560             owner.mEnrollmentSpecificId = null;
21561             saveSettingsLocked(userHandle);
21562         }
21563     }
21564 
21565     @Override
21566     public UserHandle createAndProvisionManagedProfile(
21567             @NonNull ManagedProfileProvisioningParams provisioningParams,
21568             @NonNull String callerPackage) {
21569         Objects.requireNonNull(provisioningParams, "provisioningParams is null");
21570         Objects.requireNonNull(callerPackage, "callerPackage is null");
21571 
21572         final ComponentName admin = provisioningParams.getProfileAdminComponentName();
21573         Objects.requireNonNull(admin, "admin is null");
21574 
21575         final CallerIdentity caller = getCallerIdentity(callerPackage);
21576         Preconditions.checkCallAuthorization(
21577                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
21578 
21579         provisioningParams.logParams(callerPackage);
21580 
21581         UserInfo userInfo = null;
21582         final long identity = Binder.clearCallingIdentity();
21583         try {
21584             final int result = checkProvisioningPreconditionSkipPermission(
21585                     ACTION_PROVISION_MANAGED_PROFILE, admin.getPackageName(), caller.getUserId());
21586             if (result != STATUS_OK) {
21587                 throw new ServiceSpecificException(
21588                         ERROR_PRE_CONDITION_FAILED,
21589                         "Provisioning preconditions failed with result: " + result);
21590             }
21591 
21592             final long startTime = SystemClock.elapsedRealtime();
21593 
21594             onCreateAndProvisionManagedProfileStarted(provisioningParams);
21595 
21596             final Set<String> nonRequiredApps = provisioningParams.isLeaveAllSystemAppsEnabled()
21597                     ? Collections.emptySet()
21598                     : mOverlayPackagesProvider.getNonRequiredApps(
21599                             admin, caller.getUserId(), ACTION_PROVISION_MANAGED_PROFILE);
21600             if (nonRequiredApps.isEmpty()) {
21601                 Slogf.i(LOG_TAG, "No disallowed packages for the managed profile.");
21602             } else {
21603                 for (String packageName : nonRequiredApps) {
21604                     Slogf.i(LOG_TAG, "Disallowed package [" + packageName + "]");
21605                 }
21606             }
21607 
21608             userInfo = mUserManager.createProfileForUserEvenWhenDisallowed(
21609                     provisioningParams.getProfileName(),
21610                     UserManager.USER_TYPE_PROFILE_MANAGED,
21611                     UserInfo.FLAG_DISABLED,
21612                     caller.getUserId(),
21613                     nonRequiredApps.toArray(new String[nonRequiredApps.size()]));
21614             if (userInfo == null) {
21615                 throw new ServiceSpecificException(
21616                         ERROR_PROFILE_CREATION_FAILED,
21617                         "Error creating profile, createProfileForUserEvenWhenDisallowed "
21618                                 + "returned null.");
21619             }
21620             resetInteractAcrossProfilesAppOps(caller.getUserId());
21621             logEventDuration(
21622                     DevicePolicyEnums.PLATFORM_PROVISIONING_CREATE_PROFILE_MS,
21623                     startTime,
21624                     callerPackage);
21625 
21626             maybeInstallDevicePolicyManagementRoleHolderInUser(userInfo.id);
21627 
21628             installExistingAdminPackage(userInfo.id, admin.getPackageName());
21629             if (!enableAdminAndSetProfileOwner(userInfo.id, caller.getUserId(), admin)) {
21630                 throw new ServiceSpecificException(
21631                         ERROR_SETTING_PROFILE_OWNER_FAILED,
21632                         "Error setting profile owner.");
21633             }
21634             setUserSetupComplete(userInfo.id);
21635 
21636             startProfileForSetup(userInfo.id, callerPackage);
21637             maybeMigrateAccount(
21638                     userInfo.id, caller.getUserId(), provisioningParams.getAccountToMigrate(),
21639                     provisioningParams.isKeepingAccountOnMigration(), callerPackage);
21640 
21641             if (provisioningParams.isOrganizationOwnedProvisioning()) {
21642                 synchronized (getLockObject()) {
21643                     setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(admin, userInfo.id,
21644                             true);
21645                 }
21646             }
21647 
21648             onCreateAndProvisionManagedProfileCompleted(provisioningParams);
21649 
21650             sendProvisioningCompletedBroadcast(
21651                     userInfo.id,
21652                     ACTION_PROVISION_MANAGED_PROFILE,
21653                     provisioningParams.isLeaveAllSystemAppsEnabled());
21654 
21655             return userInfo.getUserHandle();
21656         } catch (Exception e) {
21657             DevicePolicyEventLogger
21658                     .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
21659                     .setStrings(callerPackage)
21660                     .write();
21661             // In case of any errors during provisioning, remove the newly created profile.
21662             if (userInfo != null) {
21663                 mUserManager.removeUserEvenWhenDisallowed(userInfo.id);
21664             }
21665             throw e;
21666         } finally {
21667             Binder.restoreCallingIdentity(identity);
21668         }
21669     }
21670 
21671     @Override
21672     public void finalizeWorkProfileProvisioning(UserHandle managedProfileUser,
21673             Account migratedAccount) {
21674         Preconditions.checkCallAuthorization(
21675                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
21676 
21677         if (!isManagedProfile(managedProfileUser.getIdentifier())) {
21678             throw new IllegalStateException("Given user is not a managed profile");
21679         }
21680         ComponentName profileOwnerComponent =
21681                 mOwners.getProfileOwnerComponent(managedProfileUser.getIdentifier());
21682         if (profileOwnerComponent == null) {
21683             throw new IllegalStateException("There is no profile owner on the given profile");
21684         }
21685         Intent primaryProfileSuccessIntent = new Intent(ACTION_MANAGED_PROFILE_PROVISIONED);
21686         primaryProfileSuccessIntent.setPackage(profileOwnerComponent.getPackageName());
21687         primaryProfileSuccessIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES
21688                 | Intent.FLAG_RECEIVER_FOREGROUND);
21689         primaryProfileSuccessIntent.putExtra(Intent.EXTRA_USER, managedProfileUser);
21690 
21691         if (migratedAccount != null) {
21692             primaryProfileSuccessIntent.putExtra(EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE,
21693                     migratedAccount);
21694         }
21695 
21696         mContext.sendBroadcastAsUser(primaryProfileSuccessIntent,
21697                 UserHandle.of(getProfileParentId(managedProfileUser.getIdentifier())));
21698     }
21699 
21700     /**
21701      * Callback called at the beginning of {@link #createAndProvisionManagedProfile(
21702      * ManagedProfileProvisioningParams, String)} after the relevant prechecks have passed.
21703      *
21704      * <p>The logic in this method blocks provisioning.
21705      *
21706      * <p>This method is meant to be overridden by OEMs.
21707      */
21708     private void onCreateAndProvisionManagedProfileStarted(
21709             ManagedProfileProvisioningParams provisioningParams) {}
21710 
21711     /**
21712      * Callback called at the end of {@link #createAndProvisionManagedProfile(
21713      * ManagedProfileProvisioningParams, String)} after all the other provisioning tasks
21714      * have completed successfully.
21715      *
21716      * <p>The logic in this method blocks provisioning.
21717      *
21718      * <p>This method is meant to be overridden by OEMs.
21719      */
21720     private void onCreateAndProvisionManagedProfileCompleted(
21721             ManagedProfileProvisioningParams provisioningParams) {}
21722 
21723     private void maybeInstallDevicePolicyManagementRoleHolderInUser(int targetUserId) {
21724         String devicePolicyManagerRoleHolderPackageName =
21725                 getRoleHolderPackageName(mContext, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT);
21726         if (devicePolicyManagerRoleHolderPackageName == null) {
21727             Slogf.d(LOG_TAG, "No device policy management role holder specified.");
21728             return;
21729         }
21730         try {
21731             if (mIPackageManager.isPackageAvailable(
21732                     devicePolicyManagerRoleHolderPackageName, targetUserId)) {
21733                 Slogf.d(LOG_TAG, "The device policy management role holder "
21734                         + devicePolicyManagerRoleHolderPackageName + " is already installed in "
21735                         + "user " + targetUserId);
21736                 return;
21737             }
21738             Slogf.d(LOG_TAG, "Installing the device policy management role holder "
21739                     + devicePolicyManagerRoleHolderPackageName + " in user " + targetUserId);
21740             mIPackageManager.installExistingPackageAsUser(
21741                     devicePolicyManagerRoleHolderPackageName,
21742                     targetUserId,
21743                     PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
21744                     PackageManager.INSTALL_REASON_POLICY,
21745                     /* whiteListedPermissions= */ null);
21746         } catch (RemoteException e) {
21747             // Does not happen, same process
21748         }
21749     }
21750 
21751     /**
21752      * If multiple packages hold the role, returns the first package in the list.
21753      */
21754     @Nullable
21755     private String getRoleHolderPackageName(Context context, String role) {
21756         return getRoleHolderPackageNameOnUser(context, role, Process.myUserHandle());
21757     }
21758 
21759     /**
21760      * If multiple packages hold the role, returns the first package in the list.
21761      */
21762     @Nullable
21763     private String getRoleHolderPackageNameOnUser(Context context, String role, UserHandle user) {
21764         RoleManager roleManager = context.getSystemService(RoleManager.class);
21765 
21766         // Calling identity needs to be cleared as this method is used in the permissions checks.
21767         return mInjector.binderWithCleanCallingIdentity(() -> {
21768             List<String> roleHolders = roleManager.getRoleHoldersAsUser(role, user);
21769             if (roleHolders.isEmpty()) {
21770                 return null;
21771             }
21772             return roleHolders.get(0);
21773         });
21774     }
21775 
21776     private boolean isCallerDevicePolicyManagementRoleHolder(CallerIdentity caller) {
21777         return doesCallerHoldRole(caller, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT);
21778     }
21779 
21780     private boolean isCallerSystemSupervisionRoleHolder(CallerIdentity caller) {
21781         return doesCallerHoldRole(caller, RoleManager.ROLE_SYSTEM_SUPERVISION);
21782     }
21783 
21784     /**
21785      * Check if the caller is holding the given role on the calling user.
21786      *
21787      * @param caller the caller you wish to check
21788      * @param role the name of the role to check for.
21789      * @return {@code true} if the caller holds the role, {@code false} otherwise.
21790      */
21791     private boolean doesCallerHoldRole(CallerIdentity caller, String role) {
21792         int callerUid = caller.getUid();
21793         String roleHolderPackageName =
21794                 getRoleHolderPackageNameOnUser(role, caller.getUserId());
21795         int roleHolderUid = mInjector.getPackageManagerInternal().getPackageUid(
21796                 roleHolderPackageName, 0, caller.getUserId());
21797 
21798         return callerUid == roleHolderUid;
21799     }
21800 
21801     /**
21802      * Return the package name of the role holder on the given user.
21803      *
21804      * <p>If the userId passed in is {@link UserHandle.USER_ALL} then every user will be checked and
21805      * the package name of the role holder on the first user where there is a role holder is
21806      * returned.
21807      *
21808      * @param role the name of the role to check for.
21809      * @param userId the userId to check for the role holder on.
21810      * @return the package name of the role holder
21811      */
21812     @Nullable
21813     private String getRoleHolderPackageNameOnUser(String role, int userId) {
21814         RoleManager roleManager = mContext.getSystemService(RoleManager.class);
21815 
21816         // Clear calling identity as the RoleManager APIs require privileged permissions.
21817         return mInjector.binderWithCleanCallingIdentity(() -> {
21818             List<UserInfo> users;
21819             // Interpret USER_ALL as meaning "any" user.
21820             if (userId == UserHandle.USER_ALL) {
21821                 users = mInjector.getUserManagerInternal().getUsers(/*excludeDying=*/ true);
21822             } else {
21823                 users = List.of(new UserInfo(userId, /*name=*/ null, /*flags=*/ 0));
21824             }
21825             for (UserInfo user : users) {
21826                 List<String> roleHolders =
21827                         roleManager.getRoleHoldersAsUser(role, user.getUserHandle());
21828                 if (!roleHolders.isEmpty()) {
21829                     return roleHolders.get(0);
21830                 }
21831             }
21832             return null;
21833         });
21834     }
21835 
21836     private void resetInteractAcrossProfilesAppOps(@UserIdInt int userId) {
21837         mInjector.getCrossProfileApps(userId).clearInteractAcrossProfilesAppOps();
21838         pregrantDefaultInteractAcrossProfilesAppOps(userId);
21839     }
21840 
21841     private void pregrantDefaultInteractAcrossProfilesAppOps(@UserIdInt int userId) {
21842         final String op =
21843                 AppOpsManager.permissionToOp(Manifest.permission.INTERACT_ACROSS_PROFILES);
21844         for (String packageName : getConfigurableDefaultCrossProfilePackages(userId)) {
21845             if (!appOpIsDefaultOrAllowed(userId, op, packageName)) {
21846                 continue;
21847             }
21848             mInjector.getCrossProfileApps(userId).setInteractAcrossProfilesAppOp(
21849                     packageName, MODE_ALLOWED);
21850         }
21851     }
21852 
21853     private Set<String> getConfigurableDefaultCrossProfilePackages(@UserIdInt int userId) {
21854         List<String> defaultPackages = getDefaultCrossProfilePackages();
21855         return defaultPackages.stream().filter(
21856                 mInjector.getCrossProfileApps(userId)::canConfigureInteractAcrossProfiles).collect(
21857                 Collectors.toSet());
21858     }
21859 
21860     private boolean appOpIsDefaultOrAllowed(@UserIdInt int userId, String op, String packageName) {
21861         try {
21862             final int uid = mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0).
21863                     getPackageManager().getPackageUid(packageName, /* flags= */ 0);
21864             int mode = mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
21865                     op, uid, packageName);
21866             return mode == MODE_ALLOWED || mode == MODE_DEFAULT;
21867         } catch (NameNotFoundException e) {
21868             return false;
21869         }
21870     }
21871 
21872     private void installExistingAdminPackage(int userId, String packageName) {
21873         try {
21874             final int status = mContext.getPackageManager().installExistingPackageAsUser(
21875                     packageName,
21876                     userId);
21877             if (status != PackageManager.INSTALL_SUCCEEDED) {
21878                 throw new ServiceSpecificException(
21879                         ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED,
21880                         String.format("Failed to install existing package %s for user %d with "
21881                                         + "result code %d",
21882                                 packageName, userId, status));
21883             }
21884         } catch (NameNotFoundException e) {
21885             throw new ServiceSpecificException(
21886                     ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED,
21887                     String.format("Failed to install existing package %s for user %d: %s",
21888                             packageName, userId, e.getMessage()));
21889         }
21890     }
21891 
21892     private boolean enableAdminAndSetProfileOwner(
21893             @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) {
21894         enableAndSetActiveAdmin(userId, callingUserId, adminComponent);
21895         return setProfileOwner(adminComponent, userId);
21896     }
21897 
21898     private void enableAndSetActiveAdmin(
21899             @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) {
21900         final String adminPackage = adminComponent.getPackageName();
21901         enablePackage(adminPackage, callingUserId);
21902         setActiveAdmin(adminComponent, /* refreshing= */ true, userId);
21903     }
21904 
21905     private void enablePackage(String packageName, @UserIdInt int userId) {
21906         try {
21907             final int enabledSetting = mIPackageManager.getApplicationEnabledSetting(
21908                     packageName, userId);
21909             if (enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21910                     && enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21911                 mIPackageManager.setApplicationEnabledSetting(
21912                         packageName,
21913                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
21914                         // Device policy app may have launched ManagedProvisioning, play nice and
21915                         // don't kill it as a side-effect of this call.
21916                         PackageManager.DONT_KILL_APP,
21917                         userId,
21918                         mContext.getOpPackageName());
21919             }
21920         } catch (RemoteException e) {
21921             // Shouldn't happen.
21922             Slogf.wtf(LOG_TAG, "Error setting application enabled", e);
21923         }
21924     }
21925 
21926     private void setUserSetupComplete(@UserIdInt int userId) {
21927         Settings.Secure.putIntForUser(
21928                 mContext.getContentResolver(), USER_SETUP_COMPLETE, 1, userId);
21929     }
21930 
21931     private void startProfileForSetup(@UserIdInt int userId, String callerPackage)
21932             throws IllegalStateException {
21933         Slogf.i(LOG_TAG, "Starting profile %d as requested by package %s", userId, callerPackage);
21934         final long startTime = SystemClock.elapsedRealtime();
21935         final UserUnlockedBlockingReceiver unlockedReceiver = new UserUnlockedBlockingReceiver(
21936                 userId);
21937         mContext.registerReceiverAsUser(
21938                 unlockedReceiver,
21939                 new UserHandle(userId),
21940                 new IntentFilter(Intent.ACTION_USER_UNLOCKED),
21941                 /* broadcastPermission = */ null,
21942                 /* scheduler= */ null);
21943         try {
21944             // Must call startProfileEvenWhenDisabled(), as profile is not enabled yet
21945             if (!mInjector.getActivityManagerInternal().startProfileEvenWhenDisabled(userId)) {
21946                 throw new ServiceSpecificException(ERROR_STARTING_PROFILE_FAILED,
21947                         String.format("Unable to start user %d in background", userId));
21948             }
21949 
21950             if (!unlockedReceiver.waitForUserUnlocked()) {
21951                 throw new ServiceSpecificException(ERROR_STARTING_PROFILE_FAILED,
21952                         String.format("Timeout whilst waiting for unlock of user %d.", userId));
21953             }
21954             logEventDuration(
21955                     DevicePolicyEnums.PLATFORM_PROVISIONING_START_PROFILE_MS,
21956                     startTime,
21957                     callerPackage);
21958         } finally {
21959             mContext.unregisterReceiver(unlockedReceiver);
21960         }
21961     }
21962 
21963     private void maybeMigrateAccount(
21964             @UserIdInt int targetUserId, @UserIdInt int sourceUserId, Account accountToMigrate,
21965             boolean keepAccountMigrated, String callerPackage) {
21966         final UserHandle sourceUser = UserHandle.of(sourceUserId);
21967         final UserHandle targetUser = UserHandle.of(targetUserId);
21968         if (accountToMigrate == null) {
21969             Slogf.d(LOG_TAG, "No account to migrate.");
21970             return;
21971         }
21972         if (sourceUser.equals(targetUser)) {
21973             Slogf.w(LOG_TAG, "sourceUser and targetUser are the same, won't migrate account.");
21974             return;
21975         }
21976         copyAccount(targetUser, sourceUser, accountToMigrate, callerPackage);
21977         if (!keepAccountMigrated) {
21978             removeAccount(accountToMigrate, sourceUserId);
21979         }
21980     }
21981 
21982     private void copyAccount(
21983             UserHandle targetUser, UserHandle sourceUser, Account accountToMigrate,
21984             String callerPackage) {
21985         final long startTime = SystemClock.elapsedRealtime();
21986         try {
21987             final AccountManager accountManager = mContext.getSystemService(AccountManager.class);
21988             final boolean copySucceeded = accountManager.copyAccountToUser(
21989                     accountToMigrate,
21990                     sourceUser,
21991                     targetUser,
21992                     /* callback= */ null, /* handler= */ null)
21993                     .getResult(60 * 3, TimeUnit.SECONDS);
21994             if (copySucceeded) {
21995                 logCopyAccountStatus(COPY_ACCOUNT_SUCCEEDED, callerPackage);
21996                 logEventDuration(
21997                         DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_MS,
21998                         startTime,
21999                         callerPackage);
22000             } else {
22001                 logCopyAccountStatus(COPY_ACCOUNT_FAILED, callerPackage);
22002                 Slogf.e(LOG_TAG, "Failed to copy account to " + targetUser);
22003             }
22004         } catch (OperationCanceledException e) {
22005             // Account migration is not considered a critical operation.
22006             logCopyAccountStatus(COPY_ACCOUNT_TIMED_OUT, callerPackage);
22007             Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e);
22008         } catch (AuthenticatorException | IOException e) {
22009             logCopyAccountStatus(COPY_ACCOUNT_EXCEPTION, callerPackage);
22010             Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e);
22011         }
22012     }
22013 
22014     private static void logCopyAccountStatus(@CopyAccountStatus int status, String callerPackage) {
22015         DevicePolicyEventLogger
22016                 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_STATUS)
22017                 .setInt(status)
22018                 .setStrings(callerPackage)
22019                 .write();
22020     }
22021 
22022     private void removeAccount(Account account, @UserIdInt int sourceUserId) {
22023         final AccountManager accountManager = mContext.createContextAsUser(
22024                         UserHandle.of(sourceUserId), /* flags= */ 0)
22025                 .getSystemService(AccountManager.class);
22026         try {
22027             final Bundle result = accountManager.removeAccount(account,
22028                     null, null /* callback */, null /* handler */).getResult(60, TimeUnit.SECONDS);
22029             if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, /* default */ false)) {
22030                 Slogf.i(LOG_TAG, "Account removed from the primary user.");
22031             } else {
22032                 // TODO(174768447): Revisit start activity logic.
22033                 final Intent removeIntent = result.getParcelable(AccountManager.KEY_INTENT, android.content.Intent.class);
22034                 removeIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
22035                 if (removeIntent != null) {
22036                     Slogf.i(LOG_TAG, "Starting activity to remove account");
22037                     new Handler(Looper.getMainLooper()).post(() -> {
22038                         mContext.startActivity(removeIntent);
22039                     });
22040                 } else {
22041                     Slogf.e(LOG_TAG, "Could not remove account from the primary user.");
22042                 }
22043             }
22044         } catch (OperationCanceledException | AuthenticatorException | IOException e) {
22045             Slogf.e(LOG_TAG, "Exception removing account from the primary user.", e);
22046         }
22047     }
22048 
22049     @Override
22050     public void provisionFullyManagedDevice(
22051             @NonNull FullyManagedDeviceProvisioningParams provisioningParams,
22052             @NonNull String callerPackage) {
22053         Objects.requireNonNull(provisioningParams, "provisioningParams is null.");
22054         Objects.requireNonNull(callerPackage, "callerPackage is null.");
22055 
22056         ComponentName deviceAdmin = provisioningParams.getDeviceAdminComponentName();
22057         Objects.requireNonNull(deviceAdmin, "admin is null.");
22058         Objects.requireNonNull(provisioningParams.getOwnerName(), "owner name is null.");
22059 
22060         final CallerIdentity caller = getCallerIdentity();
22061         Preconditions.checkCallAuthorization(
22062                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS)
22063                         || (hasCallingOrSelfPermission(permission.PROVISION_DEMO_DEVICE)
22064                         && provisioningParams.isDemoDevice()));
22065 
22066         provisioningParams.logParams(callerPackage);
22067 
22068         final long identity = Binder.clearCallingIdentity();
22069         try {
22070             int result = checkProvisioningPreconditionSkipPermission(
22071                     ACTION_PROVISION_MANAGED_DEVICE, deviceAdmin.getPackageName(),
22072                     caller.getUserId());
22073             if (result != STATUS_OK) {
22074                 throw new ServiceSpecificException(
22075                         ERROR_PRE_CONDITION_FAILED,
22076                         "Provisioning preconditions failed with result: " + result);
22077             }
22078             onProvisionFullyManagedDeviceStarted(provisioningParams);
22079 
22080             // These properties are global so will apply on all users
22081             setTimeAndTimezone(provisioningParams.getTimeZone(), provisioningParams.getLocalTime());
22082             setLocale(provisioningParams.getLocale());
22083 
22084             int deviceOwnerUserId = UserHandle.USER_SYSTEM;
22085             if (!removeNonRequiredAppsForManagedDevice(
22086                     deviceOwnerUserId,
22087                     provisioningParams.isLeaveAllSystemAppsEnabled(),
22088                     deviceAdmin)) {
22089                 throw new ServiceSpecificException(
22090                         ERROR_REMOVE_NON_REQUIRED_APPS_FAILED,
22091                         "PackageManager failed to remove non required apps.");
22092             }
22093 
22094 
22095             if (!setActiveAdminAndDeviceOwner(deviceOwnerUserId, deviceAdmin)) {
22096                 throw new ServiceSpecificException(
22097                         ERROR_SET_DEVICE_OWNER_FAILED, "Failed to set device owner.");
22098             }
22099 
22100             disallowAddUser();
22101             setAdminCanGrantSensorsPermissionForUserUnchecked(
22102                     deviceOwnerUserId, provisioningParams.canDeviceOwnerGrantSensorsPermissions());
22103             setDemoDeviceStateUnchecked(deviceOwnerUserId, provisioningParams.isDemoDevice());
22104             onProvisionFullyManagedDeviceCompleted(provisioningParams);
22105             sendProvisioningCompletedBroadcast(
22106                     deviceOwnerUserId,
22107                     ACTION_PROVISION_MANAGED_DEVICE,
22108                     provisioningParams.isLeaveAllSystemAppsEnabled());
22109         } catch (Exception e) {
22110             DevicePolicyEventLogger
22111                     .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
22112                     .setStrings(callerPackage)
22113                     .write();
22114             throw e;
22115         } finally {
22116             Binder.restoreCallingIdentity(identity);
22117         }
22118     }
22119 
22120     /**
22121      * Callback called at the beginning of {@link #provisionFullyManagedDevice(
22122      * FullyManagedDeviceProvisioningParams, String)} after the relevant prechecks have passed.
22123      *
22124      * <p>The logic in this method blocks provisioning.
22125      *
22126      * <p>This method is meant to be overridden by OEMs.
22127      */
22128     private void onProvisionFullyManagedDeviceStarted(
22129             FullyManagedDeviceProvisioningParams provisioningParams) {}
22130 
22131     /**
22132      * Callback called at the end of {@link #provisionFullyManagedDevice(
22133      * FullyManagedDeviceProvisioningParams, String)} after all the other provisioning tasks
22134      * have completed successfully.
22135      *
22136      * <p>The logic in this method blocks provisioning.
22137      *
22138      * <p>This method is meant to be overridden by OEMs.
22139      */
22140     private void onProvisionFullyManagedDeviceCompleted(
22141             FullyManagedDeviceProvisioningParams provisioningParams) {}
22142 
22143     private void setTimeAndTimezone(String timeZone, long localTime) {
22144         try {
22145             final AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class);
22146             if (timeZone != null) {
22147                 alarmManager.setTimeZone(timeZone);
22148             }
22149             if (localTime > 0) {
22150                 alarmManager.setTime(localTime);
22151             }
22152         } catch (Exception e) {
22153             // Do not stop provisioning and ignore this error.
22154             Slogf.e(LOG_TAG, "Alarm manager failed to set the system time/timezone.", e);
22155         }
22156     }
22157 
22158     private void setLocale(Locale locale) {
22159         if (locale == null || locale.equals(Locale.getDefault())) {
22160             return;
22161         }
22162         try {
22163             // If locale is different from current locale this results in a configuration change,
22164             // which will trigger the restarting of the activity.
22165             LocalePicker.updateLocale(locale);
22166         } catch (Exception e) {
22167             // Do not stop provisioning and ignore this error.
22168             Slogf.e(LOG_TAG, "Failed to set the system locale.", e);
22169         }
22170     }
22171 
22172     private boolean removeNonRequiredAppsForManagedDevice(
22173             @UserIdInt int userId, boolean leaveAllSystemAppsEnabled, ComponentName admin) {
22174         Set<String> packagesToDelete = leaveAllSystemAppsEnabled
22175                 ? Collections.emptySet()
22176                 : mOverlayPackagesProvider.getNonRequiredApps(
22177                         admin, userId, ACTION_PROVISION_MANAGED_DEVICE);
22178 
22179         removeNonInstalledPackages(packagesToDelete, userId);
22180         if (packagesToDelete.isEmpty()) {
22181             Slogf.i(LOG_TAG, "No packages to delete on user " + userId);
22182             return true;
22183         }
22184 
22185         NonRequiredPackageDeleteObserver packageDeleteObserver =
22186                 new NonRequiredPackageDeleteObserver(packagesToDelete.size());
22187         for (String packageName : packagesToDelete) {
22188             Slogf.i(LOG_TAG, "Deleting package [" + packageName + "] as user " + userId);
22189             mContext.getPackageManager().deletePackageAsUser(
22190                     packageName,
22191                     packageDeleteObserver,
22192                     PackageManager.DELETE_SYSTEM_APP,
22193                     userId);
22194         }
22195         Slogf.i(LOG_TAG, "Waiting for non required apps to be deleted");
22196         return packageDeleteObserver.awaitPackagesDeletion();
22197     }
22198 
22199     private void removeNonInstalledPackages(Set<String> packages, @UserIdInt int userId) {
22200         final Set<String> toBeRemoved = new HashSet<>();
22201         for (String packageName : packages) {
22202             if (!isPackageInstalledForUser(packageName, userId)) {
22203                 toBeRemoved.add(packageName);
22204             }
22205         }
22206         packages.removeAll(toBeRemoved);
22207     }
22208 
22209     private void disallowAddUser() {
22210         if (!isHeadlessFlagEnabled() || mIsAutomotive) {
22211             // Auto still enables adding users due to the communal nature of those devices
22212             if (mInjector.userManagerIsHeadlessSystemUserMode()) {
22213                 Slogf.i(LOG_TAG, "Not setting DISALLOW_ADD_USER on headless system user mode.");
22214                 return;
22215             }
22216         }
22217         for (UserInfo userInfo : mUserManager.getUsers()) {
22218             UserHandle userHandle = userInfo.getUserHandle();
22219             if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
22220                 mUserManager.setUserRestriction(
22221                         UserManager.DISALLOW_ADD_USER, /* value= */ true, userHandle);
22222             }
22223         }
22224     }
22225 
22226     private boolean setActiveAdminAndDeviceOwner(
22227             @UserIdInt int userId, ComponentName adminComponent) {
22228         enableAndSetActiveAdmin(userId, userId, adminComponent);
22229         // TODO(b/178187130): Directly set DO and remove the check once silent provisioning is no
22230         //  longer used.
22231         if (getDeviceOwnerComponent(/* callingUserOnly= */ true) == null) {
22232             return setDeviceOwner(adminComponent, userId,
22233                     /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
22234         }
22235         return true;
22236     }
22237 
22238     private static void logEventDuration(int eventId, long startTime, String callerPackage) {
22239         final long duration = SystemClock.elapsedRealtime() - startTime;
22240         DevicePolicyEventLogger
22241                 .createEvent(eventId)
22242                 .setTimePeriod(duration)
22243                 .setStrings(callerPackage)
22244                 .write();
22245     }
22246 
22247     @Override
22248     public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
22249         Preconditions.checkCallAuthorization(
22250                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
22251 
22252         mInjector.binderWithCleanCallingIdentity(() -> {
22253             try {
22254                 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
22255                 final int numOfProfiles = profiles.size();
22256                 if (numOfProfiles <= 1) {
22257                     return;
22258                 }
22259 
22260                 final String managedProvisioningPackageName = getManagedProvisioningPackage(
22261                         mContext);
22262                 // Removes cross profile intent filters from the parent to all the profiles.
22263                 mIPackageManager.clearCrossProfileIntentFilters(
22264                         userId, mContext.getOpPackageName());
22265                 // Setting and resetting default cross profile intent filters was previously handled
22266                 // by Managed Provisioning. For backwards compatibility, clear any intent filters
22267                 // that were set by ManagedProvisioning.
22268                 mIPackageManager.clearCrossProfileIntentFilters(
22269                         userId, managedProvisioningPackageName);
22270 
22271                 // For each profile reset cross profile intent filters
22272                 for (int i = 0; i < numOfProfiles; i++) {
22273                     UserInfo profile = profiles.get(i);
22274                     mIPackageManager.clearCrossProfileIntentFilters(
22275                             profile.id, mContext.getOpPackageName());
22276                     // Clear any intent filters that were set by ManagedProvisioning.
22277                     mIPackageManager.clearCrossProfileIntentFilters(
22278                             profile.id, managedProvisioningPackageName);
22279 
22280                     mUserManagerInternal.setDefaultCrossProfileIntentFilters(userId, profile.id);
22281                 }
22282             } catch (RemoteException e) {
22283                 // Shouldn't happen.
22284                 Slogf.wtf(LOG_TAG, "Error resetting default cross profile intent filters", e);
22285             }
22286         });
22287     }
22288 
22289     private void setAdminCanGrantSensorsPermissionForUserUnchecked(@UserIdInt int userId,
22290             boolean canGrant) {
22291         Slogf.d(LOG_TAG, "setAdminCanGrantSensorsPermissionForUserUnchecked(%d, %b)",
22292                 userId, canGrant);
22293         synchronized (getLockObject()) {
22294             ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
22295 
22296             Preconditions.checkState(
22297                     isDeviceOwner(owner) && owner.getUserHandle().getIdentifier() == userId,
22298                     "May only be set on a the user of a device owner.");
22299 
22300             owner.mAdminCanGrantSensorsPermissions = canGrant;
22301             mPolicyCache.setAdminCanGrantSensorsPermissions(canGrant);
22302             saveSettingsLocked(userId);
22303         }
22304     }
22305 
22306     private void setDemoDeviceStateUnchecked(@UserIdInt int userId, boolean isDemoDevice) {
22307         Slogf.d(LOG_TAG, "setDemoDeviceStateUnchecked(%d, %b)",
22308                 userId, isDemoDevice);
22309         if (!isDemoDevice) {
22310             return;
22311         }
22312         synchronized (getLockObject()) {
22313             mInjector.settingsGlobalPutStringForUser(
22314                     Settings.Global.DEVICE_DEMO_MODE, Integer.toString(/* value= */ 1), userId);
22315         }
22316 
22317         setUserProvisioningState(STATE_USER_SETUP_FINALIZED, userId);
22318     }
22319 
22320     private void updateAdminCanGrantSensorsPermissionCache(@UserIdInt int userId) {
22321         synchronized (getLockObject()) {
22322 
22323             ActiveAdmin owner;
22324             // If the user is affiliated the device (either a DO itself, or an affiliated PO),
22325             // use mAdminCanGrantSensorsPermissions from the DO
22326             if (isUserAffiliatedWithDeviceLocked(userId)) {
22327                 owner = getDeviceOwnerAdminLocked();
22328             } else {
22329                 owner = getDeviceOrProfileOwnerAdminLocked(userId);
22330             }
22331             boolean canGrant = owner != null ? owner.mAdminCanGrantSensorsPermissions : false;
22332             mPolicyCache.setAdminCanGrantSensorsPermissions(canGrant);
22333         }
22334     }
22335 
22336     private void updateNetworkPreferenceForUser(int userId,
22337             List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
22338         if (!isManagedProfile(userId) && !isDeviceOwnerUserId(userId)) {
22339             return;
22340         }
22341         List<ProfileNetworkPreference> preferences = new ArrayList<>();
22342         for (PreferentialNetworkServiceConfig preferentialNetworkServiceConfig :
22343                 preferentialNetworkServiceConfigs) {
22344             ProfileNetworkPreference.Builder preferenceBuilder =
22345                     new ProfileNetworkPreference.Builder();
22346             if (preferentialNetworkServiceConfig.isEnabled()) {
22347                 if (preferentialNetworkServiceConfig.isFallbackToDefaultConnectionAllowed()) {
22348                     preferenceBuilder.setPreference(PROFILE_NETWORK_PREFERENCE_ENTERPRISE);
22349                 } else if (preferentialNetworkServiceConfig.shouldBlockNonMatchingNetworks()) {
22350                     preferenceBuilder.setPreference(
22351                             PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING);
22352                 } else {
22353                     preferenceBuilder.setPreference(
22354                             PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK);
22355                 }
22356                 preferenceBuilder.setIncludedUids(
22357                         preferentialNetworkServiceConfig.getIncludedUids());
22358                 preferenceBuilder.setExcludedUids(
22359                         preferentialNetworkServiceConfig.getExcludedUids());
22360                 preferenceBuilder.setPreferenceEnterpriseId(
22361                         preferentialNetworkServiceConfig.getNetworkId());
22362             } else {
22363                 preferenceBuilder.setPreference(PROFILE_NETWORK_PREFERENCE_DEFAULT);
22364             }
22365 
22366 
22367             preferences.add(preferenceBuilder.build());
22368         }
22369         Slogf.d(LOG_TAG, "updateNetworkPreferenceForUser to " + preferences);
22370         mInjector.binderWithCleanCallingIdentity(() ->
22371                 mInjector.getConnectivityManager().setProfileNetworkPreferences(
22372                         UserHandle.of(userId), preferences,
22373                         null /* executor */, null /* listener */));
22374     }
22375 
22376     @Override
22377     public boolean canAdminGrantSensorsPermissions() {
22378         if (!mHasFeature) {
22379             return false;
22380         }
22381 
22382         return mPolicyCache.canAdminGrantSensorsPermissions();
22383     }
22384 
22385     @Override
22386     public void setDeviceOwnerType(@NonNull ComponentName admin,
22387             @DeviceOwnerType int deviceOwnerType) {
22388         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22389                 MANAGE_PROFILE_AND_DEVICE_OWNERS));
22390 
22391         synchronized (getLockObject()) {
22392             setDeviceOwnerTypeLocked(admin, deviceOwnerType);
22393         }
22394     }
22395 
22396     private void setDeviceOwnerTypeLocked(ComponentName admin,
22397             @DeviceOwnerType int deviceOwnerType) {
22398         String packageName = admin.getPackageName();
22399         boolean isAdminTestOnly;
22400 
22401         verifyDeviceOwnerTypePreconditionsLocked(admin);
22402 
22403         isAdminTestOnly = isAdminTestOnlyLocked(admin, mOwners.getDeviceOwnerUserId());
22404         Preconditions.checkState(isAdminTestOnly
22405                         || !mOwners.isDeviceOwnerTypeSetForDeviceOwner(packageName),
22406                 "Test only admins can only set the device owner type more than once");
22407 
22408         mOwners.setDeviceOwnerType(packageName, deviceOwnerType, isAdminTestOnly);
22409         setGlobalSettingDeviceOwnerType(deviceOwnerType);
22410     }
22411 
22412     // TODO(b/237065504): Allow mainline modules to get the device owner type. This is a workaround
22413     // to get the device owner type in PermissionController. See HibernationPolicy.kt.
22414     private void setGlobalSettingDeviceOwnerType(int deviceOwnerType) {
22415         mInjector.binderWithCleanCallingIdentity(
22416                 () -> mInjector.settingsGlobalPutInt("device_owner_type", deviceOwnerType));
22417     }
22418 
22419     @Override
22420     @DeviceOwnerType
22421     public int getDeviceOwnerType(@NonNull ComponentName admin) {
22422         synchronized (getLockObject()) {
22423             verifyDeviceOwnerTypePreconditionsLocked(admin);
22424             return getDeviceOwnerTypeLocked(admin.getPackageName());
22425         }
22426     }
22427 
22428     @DeviceOwnerType
22429     private int getDeviceOwnerTypeLocked(String packageName) {
22430         return mOwners.getDeviceOwnerType(packageName);
22431     }
22432 
22433     /**
22434      * {@code true} is returned <b>only if</b> the caller is the device owner and the device owner
22435      * type is {@link DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}. {@code false} is returned for
22436      * the case where the caller is not the device owner, there is no device owner, or the device
22437      * owner type is not {@link DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}.
22438      */
22439     private boolean isFinancedDeviceOwner(CallerIdentity caller) {
22440         synchronized (getLockObject()) {
22441             return isDeviceOwnerLocked(caller) && getDeviceOwnerTypeLocked(
22442                     mOwners.getDeviceOwnerPackageName()) == DEVICE_OWNER_TYPE_FINANCED;
22443         }
22444     }
22445 
22446     private void verifyDeviceOwnerTypePreconditionsLocked(@NonNull ComponentName admin) {
22447         Preconditions.checkState(mOwners.hasDeviceOwner(), "there is no device owner");
22448         Preconditions.checkState(mOwners.getDeviceOwnerComponent().equals(admin),
22449                 "admin is not the device owner");
22450     }
22451 
22452     @Override
22453     public void setUsbDataSignalingEnabled(String packageName, boolean enabled) {
22454         Objects.requireNonNull(packageName, "Admin package name must be provided");
22455         final CallerIdentity caller = getCallerIdentity(packageName);
22456         if (!isPermissionCheckFlagEnabled()) {
22457             Preconditions.checkCallAuthorization(
22458                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
22459                     "USB data signaling can only be controlled by a device owner or "
22460                             + "a profile owner on an organization-owned device.");
22461             Preconditions.checkState(canUsbDataSignalingBeDisabled(),
22462                     "USB data signaling cannot be disabled.");
22463         }
22464 
22465 
22466         synchronized (getLockObject()) {
22467             ActiveAdmin admin;
22468             if (isPermissionCheckFlagEnabled()) {
22469                 admin = enforcePermissionAndGetEnforcingAdmin(
22470                         /* admin= */ null, MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
22471                         caller.getPackageName(),
22472                         caller.getUserId()).getActiveAdmin();
22473             } else {
22474                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
22475             }
22476 
22477             if (admin.mUsbDataSignalingEnabled != enabled) {
22478                 admin.mUsbDataSignalingEnabled = enabled;
22479                 saveSettingsLocked(caller.getUserId());
22480                 updateUsbDataSignal();
22481             }
22482         }
22483         DevicePolicyEventLogger
22484                 .createEvent(DevicePolicyEnums.SET_USB_DATA_SIGNALING)
22485                 .setAdmin(packageName)
22486                 .setBoolean(enabled)
22487                 .write();
22488     }
22489 
22490     private void updateUsbDataSignal() {
22491         if (!canUsbDataSignalingBeDisabled()) {
22492             return;
22493         }
22494         final boolean usbEnabled;
22495         synchronized (getLockObject()) {
22496             usbEnabled = isUsbDataSignalingEnabledInternalLocked();
22497         }
22498         if (!mInjector.binderWithCleanCallingIdentity(
22499                 () -> mInjector.getUsbManager().enableUsbDataSignal(usbEnabled))) {
22500             Slogf.w(LOG_TAG, "Failed to set usb data signaling state");
22501         }
22502     }
22503 
22504     @Override
22505     public boolean isUsbDataSignalingEnabled(String packageName) {
22506         final CallerIdentity caller = getCallerIdentity(packageName);
22507         synchronized (getLockObject()) {
22508             // If the caller is an admin, return the policy set by itself. Otherwise
22509             // return the device-wide policy.
22510             if (isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)) {
22511                 return getProfileOwnerOrDeviceOwnerLocked(
22512                         caller.getUserId()).mUsbDataSignalingEnabled;
22513             } else {
22514                 return isUsbDataSignalingEnabledInternalLocked();
22515             }
22516         }
22517     }
22518 
22519     @Override
22520     public boolean isUsbDataSignalingEnabledForUser(int userId) {
22521         final CallerIdentity caller = getCallerIdentity();
22522         Preconditions.checkCallAuthorization(isSystemUid(caller));
22523 
22524         synchronized (getLockObject()) {
22525             return isUsbDataSignalingEnabledInternalLocked();
22526         }
22527     }
22528 
22529     private boolean isUsbDataSignalingEnabledInternalLocked() {
22530         // TODO(b/261999445): remove
22531         ActiveAdmin admin;
22532         if (isHeadlessFlagEnabled()) {
22533             admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
22534         } else {
22535             admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
22536                     UserHandle.USER_SYSTEM);
22537         }
22538         return admin == null || admin.mUsbDataSignalingEnabled;
22539     }
22540 
22541     @Override
22542     public boolean canUsbDataSignalingBeDisabled() {
22543         return mInjector.binderWithCleanCallingIdentity(() ->
22544                 mInjector.getUsbManager() != null
22545                         && mInjector.getUsbManager().getUsbHalVersion() >= UsbManager.USB_HAL_V1_3
22546         );
22547     }
22548 
22549     private void notifyMinimumRequiredWifiSecurityLevelChanged(int level) {
22550         mInjector.binderWithCleanCallingIdentity(
22551                 () -> mInjector.getWifiManager()
22552                         .notifyMinimumRequiredWifiSecurityLevelChanged(level));
22553     }
22554 
22555     private void notifyWifiSsidPolicyChanged(WifiSsidPolicy policy) {
22556         if (policy == null) {
22557             // If policy doesn't limit SSIDs, no need to disconnect anything.
22558             return;
22559         }
22560         mInjector.binderWithCleanCallingIdentity(
22561                 () -> mInjector.getWifiManager().notifyWifiSsidPolicyChanged(policy));
22562     }
22563 
22564     @Override
22565     public void setMinimumRequiredWifiSecurityLevel(String callerPackageName, int level) {
22566         CallerIdentity caller;
22567         if (isPermissionCheckFlagEnabled()) {
22568             caller = getCallerIdentity(callerPackageName);
22569         } else {
22570             caller = getCallerIdentity();
22571             Preconditions.checkCallAuthorization(
22572                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
22573                     "Wi-Fi minimum security level can only be controlled by a device owner or "
22574                             + "a profile owner on an organization-owned device.");
22575         }
22576 
22577         boolean valueChanged = false;
22578         synchronized (getLockObject()) {
22579             ActiveAdmin admin;
22580             if (isPermissionCheckFlagEnabled()) {
22581                 admin = enforcePermissionAndGetEnforcingAdmin(/* admin= */ null,
22582                         MANAGE_DEVICE_POLICY_WIFI, caller.getPackageName(), caller.getUserId())
22583                         .getActiveAdmin();
22584             } else {
22585                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
22586             }
22587             if (admin.mWifiMinimumSecurityLevel != level) {
22588                 admin.mWifiMinimumSecurityLevel = level;
22589                 saveSettingsLocked(caller.getUserId());
22590                 valueChanged = true;
22591             }
22592         }
22593         if (valueChanged) notifyMinimumRequiredWifiSecurityLevelChanged(level);
22594     }
22595 
22596     @Override
22597     public int getMinimumRequiredWifiSecurityLevel() {
22598         synchronized (getLockObject()) {
22599             ActiveAdmin admin;
22600             // TODO(b/261999445): remove
22601             if (isHeadlessFlagEnabled()) {
22602                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
22603             } else {
22604                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
22605                         UserHandle.USER_SYSTEM);
22606             }
22607             return (admin == null) ? DevicePolicyManager.WIFI_SECURITY_OPEN
22608                     : admin.mWifiMinimumSecurityLevel;
22609         }
22610     }
22611 
22612     @Override
22613     public WifiSsidPolicy getWifiSsidPolicy(String callerPackageName) {
22614         final CallerIdentity caller = getCallerIdentity();
22615         if (isPermissionCheckFlagEnabled()) {
22616             enforcePermission(MANAGE_DEVICE_POLICY_WIFI, callerPackageName,
22617                     caller.getUserId());
22618         } else {
22619             Preconditions.checkCallAuthorization(
22620                     isDefaultDeviceOwner(caller)
22621                             || isProfileOwnerOfOrganizationOwnedDevice(caller)
22622                             || canQueryAdminPolicy(caller),
22623                     "SSID policy can only be retrieved by a device owner or "
22624                             + "a profile owner on an organization-owned device or "
22625                             + "an app with the QUERY_ADMIN_POLICY permission.");
22626         }
22627         synchronized (getLockObject()) {
22628             ActiveAdmin admin;
22629             admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked();
22630             return admin != null ? admin.mWifiSsidPolicy : null;
22631         }
22632     }
22633 
22634     @Override
22635     public void setWifiSsidPolicy(String callerPackageName, WifiSsidPolicy policy) {
22636         CallerIdentity caller;
22637 
22638         if (isPermissionCheckFlagEnabled()) {
22639             caller = getCallerIdentity(callerPackageName);
22640         } else {
22641             caller = getCallerIdentity();
22642             Preconditions.checkCallAuthorization(
22643                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
22644                     "SSID denylist can only be controlled by a device owner or "
22645                             + "a profile owner on an organization-owned device.");
22646         }
22647 
22648         boolean changed = false;
22649         synchronized (getLockObject()) {
22650             ActiveAdmin admin;
22651             if (isPermissionCheckFlagEnabled()) {
22652                 admin = enforcePermissionAndGetEnforcingAdmin(
22653                         /* admin= */ null, MANAGE_DEVICE_POLICY_WIFI,
22654                         caller.getPackageName(),
22655                         caller.getUserId()).getActiveAdmin();
22656             } else {
22657                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
22658             }
22659             if (!Objects.equals(policy, admin.mWifiSsidPolicy)) {
22660                 admin.mWifiSsidPolicy = policy;
22661                 changed = true;
22662             }
22663             if (changed) saveSettingsLocked(caller.getUserId());
22664         }
22665         if (changed) {
22666             notifyWifiSsidPolicyChanged(policy);
22667         }
22668     }
22669 
22670     @Override
22671     public void setDrawables(@NonNull List<DevicePolicyDrawableResource> drawables) {
22672         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22673                 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
22674 
22675         Objects.requireNonNull(drawables, "drawables must be provided.");
22676 
22677         mInjector.binderWithCleanCallingIdentity(() -> {
22678             if (mDeviceManagementResourcesProvider.updateDrawables(drawables)) {
22679                 sendDrawableUpdatedBroadcast(
22680                         drawables.stream().map(s -> s.getDrawableId()).collect(
22681                                 Collectors.toList()));
22682             }
22683         });
22684     }
22685 
22686     @Override
22687     public void resetDrawables(@NonNull List<String> drawableIds) {
22688         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22689                 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
22690 
22691         Objects.requireNonNull(drawableIds, "drawableIds must be provided.");
22692 
22693         mInjector.binderWithCleanCallingIdentity(() -> {
22694             if (mDeviceManagementResourcesProvider.removeDrawables(drawableIds)) {
22695                 sendDrawableUpdatedBroadcast(drawableIds);
22696             }
22697         });
22698     }
22699 
22700     @Override
22701     public ParcelableResource getDrawable(
22702             String drawableId, String drawableStyle, String drawableSource) {
22703         return mInjector.binderWithCleanCallingIdentity(() ->
22704                 mDeviceManagementResourcesProvider.getDrawable(
22705                         drawableId, drawableStyle, drawableSource));
22706     }
22707 
22708     private void sendDrawableUpdatedBroadcast(List<String> drawableIds) {
22709         sendResourceUpdatedBroadcast(EXTRA_RESOURCE_TYPE_DRAWABLE, drawableIds);
22710     }
22711 
22712     @Override
22713     public void setStrings(@NonNull List<DevicePolicyStringResource> strings) {
22714         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22715                 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
22716 
22717         Objects.requireNonNull(strings, "strings must be provided.");
22718 
22719         mInjector.binderWithCleanCallingIdentity(() -> {
22720             if (mDeviceManagementResourcesProvider.updateStrings(strings)) {
22721                 sendStringsUpdatedBroadcast(
22722                         strings.stream().map(s -> s.getStringId()).collect(Collectors.toList()));
22723             }
22724         });
22725     }
22726 
22727     @Override
22728     public void resetStrings(@NonNull List<String> stringIds) {
22729         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22730                 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
22731 
22732         mInjector.binderWithCleanCallingIdentity(() -> {
22733             if (mDeviceManagementResourcesProvider.removeStrings(stringIds)) {
22734                 sendStringsUpdatedBroadcast(stringIds);
22735             }
22736         });
22737     }
22738 
22739     @Override
22740     public ParcelableResource getString(String stringId) {
22741         return mInjector.binderWithCleanCallingIdentity(() ->
22742                 mDeviceManagementResourcesProvider.getString(stringId));
22743     }
22744 
22745     private void sendStringsUpdatedBroadcast(List<String> stringIds) {
22746         sendResourceUpdatedBroadcast(EXTRA_RESOURCE_TYPE_STRING, stringIds);
22747     }
22748 
22749     private void sendResourceUpdatedBroadcast(int resourceType, List<String> resourceIds) {
22750         final Intent intent = new Intent(ACTION_DEVICE_POLICY_RESOURCE_UPDATED);
22751         intent.putExtra(EXTRA_RESOURCE_IDS, resourceIds.toArray(String[]::new));
22752         intent.putExtra(EXTRA_RESOURCE_TYPE, resourceType);
22753         intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
22754         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
22755 
22756         List<UserInfo> users = mUserManager.getAliveUsers();
22757         for (int i = 0; i < users.size(); i++) {
22758             UserHandle user = users.get(i).getUserHandle();
22759             mContext.sendBroadcastAsUser(intent, user);
22760         }
22761     }
22762 
22763     private String getUpdatableString(
22764             String updatableStringId, int defaultStringId, Object... formatArgs) {
22765         ParcelableResource resource = mDeviceManagementResourcesProvider.getString(
22766                 updatableStringId);
22767         if (resource == null) {
22768             return ParcelableResource.loadDefaultString(() ->
22769                     mContext.getString(defaultStringId, formatArgs));
22770         }
22771         return resource.getString(
22772                 mContext, () -> mContext.getString(defaultStringId, formatArgs), formatArgs);
22773     }
22774 
22775     public boolean isDpcDownloaded() {
22776         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22777                 MANAGE_PROFILE_AND_DEVICE_OWNERS));
22778 
22779         ContentResolver cr = mContext.getContentResolver();
22780 
22781         return mInjector.binderWithCleanCallingIdentity(() -> Settings.Secure.getIntForUser(
22782                 cr, MANAGED_PROVISIONING_DPC_DOWNLOADED,
22783                 /* def= */ 0, /* userHandle= */ cr.getUserId())
22784                 == 1);
22785     }
22786 
22787     public void setDpcDownloaded(boolean downloaded) {
22788         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22789                 MANAGE_PROFILE_AND_DEVICE_OWNERS));
22790 
22791         int setTo = downloaded ? 1 : 0;
22792 
22793         mInjector.binderWithCleanCallingIdentity(() -> Settings.Secure.putInt(
22794                 mContext.getContentResolver(), MANAGED_PROVISIONING_DPC_DOWNLOADED, setTo));
22795     }
22796 
22797     @Override
22798     public void resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState() {
22799         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22800                 android.Manifest.permission.MANAGE_ROLE_HOLDERS));
22801         setBypassDevicePolicyManagementRoleQualificationStateInternal(
22802                 /* currentRoleHolder= */ null, /* allowBypass= */ false);
22803     }
22804 
22805     @Override
22806     public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() {
22807         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22808                 android.Manifest.permission.MANAGE_ROLE_HOLDERS));
22809         return mInjector.binderWithCleanCallingIdentity(() -> {
22810             if (getUserData(
22811                     UserHandle.USER_SYSTEM).mBypassDevicePolicyManagementRoleQualifications) {
22812                 return true;
22813             }
22814             return shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal();
22815         });
22816     }
22817 
22818     private boolean shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal() {
22819         if (nonTestNonPrecreatedUsersExist()) {
22820             return false;
22821         }
22822 
22823 
22824         return !hasIncompatibleAccountsOnAnyUser();
22825     }
22826 
22827     private boolean hasAccountsOnAnyUser() {
22828         long callingIdentity = Binder.clearCallingIdentity();
22829         try {
22830             for (UserInfo user : mUserManagerInternal.getUsers(/* excludeDying= */ true)) {
22831                 AccountManager am = mContext.createContextAsUser(
22832                                 UserHandle.of(user.id), /* flags= */ 0)
22833                         .getSystemService(AccountManager.class);
22834                 Account[] accounts = am.getAccounts();
22835                 if (accounts.length != 0) {
22836                     return true;
22837                 }
22838             }
22839 
22840             return false;
22841         } finally {
22842             Binder.restoreCallingIdentity(callingIdentity);
22843         }
22844     }
22845 
22846     private void setBypassDevicePolicyManagementRoleQualificationStateInternal(
22847             String currentRoleHolder, boolean allowBypass) {
22848         boolean stateChanged = false;
22849         DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
22850         if (policy.mBypassDevicePolicyManagementRoleQualifications != allowBypass) {
22851             policy.mBypassDevicePolicyManagementRoleQualifications = allowBypass;
22852             stateChanged = true;
22853         }
22854         if (!Objects.equals(currentRoleHolder, policy.mCurrentRoleHolder)) {
22855             policy.mCurrentRoleHolder = currentRoleHolder;
22856             stateChanged = true;
22857         }
22858         if (stateChanged) {
22859             synchronized (getLockObject()) {
22860                 saveSettingsLocked(UserHandle.USER_SYSTEM);
22861             }
22862         }
22863     }
22864 
22865     private final class DevicePolicyManagementRoleObserver implements OnRoleHoldersChangedListener {
22866         private RoleManager mRm;
22867         private final Executor mExecutor;
22868         private final Context mContext;
22869 
22870         DevicePolicyManagementRoleObserver(@NonNull Context context) {
22871             mContext = context;
22872             mExecutor = mContext.getMainExecutor();
22873             mRm = mContext.getSystemService(RoleManager.class);
22874         }
22875 
22876         public void register() {
22877             mRm.addOnRoleHoldersChangedListenerAsUser(mExecutor, this, UserHandle.ALL);
22878         }
22879 
22880         @Override
22881         public void onRoleHoldersChanged(@NonNull String roleName, @NonNull UserHandle user) {
22882             mDevicePolicyEngine.handleRoleChanged(roleName, user.getIdentifier());
22883             if (RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT.equals(roleName)) {
22884                 handleDevicePolicyManagementRoleChange(user);
22885                 return;
22886             }
22887             if (RoleManager.ROLE_FINANCED_DEVICE_KIOSK.equals(roleName)) {
22888                 handleFinancedDeviceKioskRoleChange();
22889                 return;
22890             }
22891         }
22892 
22893         private void handleDevicePolicyManagementRoleChange(UserHandle user) {
22894             String newRoleHolder = getDeviceManagementRoleHolder(user);
22895             if (isDefaultRoleHolder(newRoleHolder)) {
22896                 Slogf.i(LOG_TAG,
22897                         "onRoleHoldersChanged: Default role holder is set, returning early");
22898                 return;
22899             }
22900             if (newRoleHolder == null) {
22901                 Slogf.i(LOG_TAG,
22902                         "onRoleHoldersChanged: New role holder is null, returning early");
22903                 return;
22904             }
22905             if (shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal()) {
22906                 Slogf.w(LOG_TAG,
22907                         "onRoleHoldersChanged: Updating current role holder to " + newRoleHolder);
22908                 setBypassDevicePolicyManagementRoleQualificationStateInternal(
22909                         newRoleHolder, /* allowBypass= */ true);
22910                 return;
22911             }
22912             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
22913             if (!newRoleHolder.equals(policy.mCurrentRoleHolder)) {
22914                 Slogf.w(LOG_TAG,
22915                         "onRoleHoldersChanged: You can't set a different role holder, role "
22916                                 + "is getting revoked from " + newRoleHolder);
22917                 setBypassDevicePolicyManagementRoleQualificationStateInternal(
22918                         /* currentRoleHolder= */ null, /* allowBypass= */ false);
22919                 mRm.removeRoleHolderAsUser(
22920                         RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT,
22921                         newRoleHolder,
22922                         /* flags= */ 0,
22923                         user,
22924                         mExecutor,
22925                         successful -> {});
22926             }
22927         }
22928 
22929         private void handleFinancedDeviceKioskRoleChange() {
22930             if (!isPolicyEngineForFinanceFlagEnabled()) {
22931                 return;
22932             }
22933             Slog.i(LOG_TAG, "Handling action " + ACTION_DEVICE_FINANCING_STATE_CHANGED);
22934             Intent intent = new Intent(ACTION_DEVICE_FINANCING_STATE_CHANGED);
22935             mInjector.binderWithCleanCallingIdentity(() -> {
22936                 for (UserInfo userInfo : mUserManager.getUsers()) {
22937                     UserHandle user = userInfo.getUserHandle();
22938                     broadcastExplicitIntentToRoleHolder(
22939                             intent, RoleManager.ROLE_SYSTEM_SUPERVISION, user);
22940                     broadcastExplicitIntentToRoleHolder(
22941                             intent, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, user);
22942                     ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(user.getIdentifier());
22943                     if (admin == null) {
22944                         continue;
22945                     }
22946                     if (!isProfileOwnerOfOrganizationOwnedDevice(
22947                             admin.info.getComponent(), user.getIdentifier())
22948                             && !isDeviceOwner(admin)
22949                             && !(isProfileOwner(admin.info.getComponent(), user.getIdentifier())
22950                             && admin.getUserHandle().isSystem())) {
22951                         continue;
22952                     }
22953                     // Don't send the broadcast twice if the DPC is the same package as the
22954                     // DMRH
22955                     if (admin.info.getPackageName().equals(getDeviceManagementRoleHolder(user))) {
22956                         continue;
22957                     }
22958                     broadcastExplicitIntentToPackage(
22959                             intent, admin.info.getPackageName(), admin.getUserHandle());
22960                 }
22961             });
22962         }
22963 
22964         private String getDeviceManagementRoleHolder(UserHandle user) {
22965             return DevicePolicyManagerService.this.getRoleHolderPackageNameOnUser(
22966                     mContext, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, user);
22967         }
22968 
22969         private boolean isDefaultRoleHolder(String packageName) {
22970             String defaultRoleHolder = getDefaultRoleHolderPackageName();
22971             if (packageName == null || defaultRoleHolder == null) {
22972                 return false;
22973             }
22974             if (!defaultRoleHolder.equals(packageName)) {
22975                 return false;
22976             }
22977             return hasSigningCertificate(
22978                     packageName, getDefaultRoleHolderPackageSignature());
22979         }
22980 
22981         private boolean hasSigningCertificate(String packageName, String  certificateString) {
22982             if (packageName == null || certificateString == null) {
22983                 return false;
22984             }
22985             byte[] certificate;
22986             try {
22987                 certificate = new Signature(certificateString).toByteArray();
22988             } catch (IllegalArgumentException e) {
22989                 Slogf.w(LOG_TAG, "Cannot parse signing certificate: " + certificateString, e);
22990                 return false;
22991             }
22992             PackageManager pm = mInjector.getPackageManager();
22993             return pm.hasSigningCertificate(
22994                     packageName, certificate, PackageManager.CERT_INPUT_SHA256);
22995         }
22996 
22997         private String getDefaultRoleHolderPackageName() {
22998             String[] info = getDefaultRoleHolderPackageNameAndSignature();
22999             if (info == null) {
23000                 return null;
23001             }
23002             return info[0];
23003         }
23004 
23005         private String getDefaultRoleHolderPackageSignature() {
23006             String[] info = getDefaultRoleHolderPackageNameAndSignature();
23007             if (info == null || info.length < 2) {
23008                 return null;
23009             }
23010             return info[1];
23011         }
23012 
23013         private String[] getDefaultRoleHolderPackageNameAndSignature() {
23014             String packageNameAndSignature = mContext.getString(
23015                     com.android.internal.R.string.config_devicePolicyManagement);
23016             if (TextUtils.isEmpty(packageNameAndSignature)) {
23017                 return null;
23018             }
23019             if (packageNameAndSignature.contains(":")) {
23020                 return packageNameAndSignature.split(":");
23021             }
23022             return new String[]{packageNameAndSignature};
23023         }
23024     }
23025 
23026     private void broadcastExplicitIntentToRoleHolder(
23027             Intent intent, String role, UserHandle userHandle) {
23028         String packageName = getRoleHolderPackageNameOnUser(mContext, role, userHandle);
23029         if (packageName == null) {
23030             return;
23031         }
23032         broadcastExplicitIntentToPackage(intent, packageName, userHandle);
23033     }
23034 
23035     private void broadcastExplicitIntentToPackage(
23036             Intent intent, String packageName, UserHandle userHandle) {
23037         int userId = userHandle.getIdentifier();
23038         if (packageName == null) {
23039             return;
23040         }
23041         Intent packageIntent = new Intent(intent)
23042                 .setPackage(packageName);
23043         List<ResolveInfo> receivers = mContext.getPackageManager().queryBroadcastReceiversAsUser(
23044                 packageIntent,
23045                 PackageManager.ResolveInfoFlags.of(PackageManager.GET_RECEIVERS),
23046                 userId);
23047         if (receivers.isEmpty()) {
23048             Slog.i(LOG_TAG, "Found no receivers to handle intent " + intent
23049                     + " in package " + packageName);
23050             return;
23051         }
23052         for (ResolveInfo receiver : receivers) {
23053             Intent componentIntent = new Intent(packageIntent)
23054                     .setComponent(receiver.getComponentInfo().getComponentName())
23055                     .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
23056             mContext.sendBroadcastAsUser(componentIntent, userHandle);
23057         }
23058     }
23059 
23060     @Override
23061     public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) {
23062         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
23063                 MANAGE_PROFILE_AND_DEVICE_OWNERS));
23064         int userId = user.getIdentifier();
23065         return mInjector.binderWithCleanCallingIdentity(() -> {
23066             List<UserInfo> userProfiles = mUserManager.getProfiles(userId);
23067             List<UserHandle> result = new ArrayList<>();
23068             for (int i = 0; i < userProfiles.size(); i++) {
23069                 UserInfo userInfo = userProfiles.get(i);
23070                 if (userInfo.isManagedProfile() && hasProfileOwner(userInfo.id)) {
23071                     result.add(new UserHandle(userInfo.id));
23072                 }
23073             }
23074             return result;
23075         });
23076     }
23077 
23078     // Permission that will need to be created in V.
23079     private static final String MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL =
23080             "manage_device_policy_block_uninstall";
23081     private static final String MANAGE_DEVICE_POLICY_CAMERA_TOGGLE =
23082             "manage_device_policy_camera_toggle";
23083     private static final String MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE =
23084             "manage_device_policy_microphone_toggle";
23085 
23086     // DPC types
23087     private static final int NOT_A_DPC = -1;
23088     private static final int DEFAULT_DEVICE_OWNER = 0;
23089     private static final int FINANCED_DEVICE_OWNER = 1;
23090     private static final int PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE = 2;
23091     private static final int PROFILE_OWNER_ON_USER_0 = 3;
23092     private static final int PROFILE_OWNER = 4;
23093     private static final int PROFILE_OWNER_ON_USER = 5;
23094     private static final int AFFILIATED_PROFILE_OWNER_ON_USER = 6;
23095     // DPC types
23096     @IntDef(value = {
23097             NOT_A_DPC,
23098             DEFAULT_DEVICE_OWNER,
23099             FINANCED_DEVICE_OWNER,
23100             PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE,
23101             PROFILE_OWNER_ON_USER_0,
23102             PROFILE_OWNER,
23103             PROFILE_OWNER_ON_USER,
23104             AFFILIATED_PROFILE_OWNER_ON_USER
23105     })
23106     private @interface DpcType {}
23107 
23108     // Permissions of existing DPC types.
23109     private static final List<String> DEFAULT_DEVICE_OWNER_PERMISSIONS = List.of(
23110             MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
23111             MANAGE_DEVICE_POLICY_ACROSS_USERS,
23112             MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL,
23113             MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
23114             MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
23115             MANAGE_DEVICE_POLICY_APPS_CONTROL,
23116             MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
23117             MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
23118             MANAGE_DEVICE_POLICY_AUTOFILL,
23119             MANAGE_DEVICE_POLICY_BLUETOOTH,
23120             MANAGE_DEVICE_POLICY_CALLS,
23121             MANAGE_DEVICE_POLICY_CAMERA,
23122             MANAGE_DEVICE_POLICY_CERTIFICATES,
23123             MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
23124             MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
23125             MANAGE_DEVICE_POLICY_DEFAULT_SMS,
23126             MANAGE_DEVICE_POLICY_DISPLAY,
23127             MANAGE_DEVICE_POLICY_FACTORY_RESET,
23128             MANAGE_DEVICE_POLICY_FUN,
23129             MANAGE_DEVICE_POLICY_INPUT_METHODS,
23130             MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
23131             MANAGE_DEVICE_POLICY_KEYGUARD,
23132             MANAGE_DEVICE_POLICY_LOCALE,
23133             MANAGE_DEVICE_POLICY_LOCATION,
23134             MANAGE_DEVICE_POLICY_LOCK,
23135             MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
23136             MANAGE_DEVICE_POLICY_LOCK_TASK,
23137             MANAGE_DEVICE_POLICY_MICROPHONE,
23138             MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
23139             MANAGE_DEVICE_POLICY_MODIFY_USERS,
23140             MANAGE_DEVICE_POLICY_MTE,
23141             MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
23142             MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
23143             MANAGE_DEVICE_POLICY_PACKAGE_STATE,
23144             MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
23145             MANAGE_DEVICE_POLICY_PRINTING,
23146             MANAGE_DEVICE_POLICY_PROFILES,
23147             MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
23148             MANAGE_DEVICE_POLICY_RESET_PASSWORD,
23149             MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
23150             MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
23151             MANAGE_DEVICE_POLICY_SAFE_BOOT,
23152             MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
23153             MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
23154             MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
23155             MANAGE_DEVICE_POLICY_SMS,
23156             MANAGE_DEVICE_POLICY_STATUS_BAR,
23157             MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
23158             MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
23159             MANAGE_DEVICE_POLICY_SYSTEM_UPDATES,
23160             MANAGE_DEVICE_POLICY_TIME,
23161             MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
23162             MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
23163             MANAGE_DEVICE_POLICY_VPN,
23164             MANAGE_DEVICE_POLICY_WALLPAPER,
23165             MANAGE_DEVICE_POLICY_WIFI,
23166             MANAGE_DEVICE_POLICY_WINDOWS,
23167             MANAGE_DEVICE_POLICY_WIPE_DATA,
23168             SET_TIME,
23169             SET_TIME_ZONE
23170     );
23171     private static final List<String> FINANCED_DEVICE_OWNER_PERMISSIONS = List.of(
23172             MANAGE_DEVICE_POLICY_ACROSS_USERS,
23173             MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL,
23174             MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
23175             MANAGE_DEVICE_POLICY_APPS_CONTROL,
23176             MANAGE_DEVICE_POLICY_CALLS,
23177             MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
23178             MANAGE_DEVICE_POLICY_FACTORY_RESET,
23179             MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
23180             MANAGE_DEVICE_POLICY_KEYGUARD,
23181             MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
23182             MANAGE_DEVICE_POLICY_LOCK_TASK,
23183             MANAGE_DEVICE_POLICY_MODIFY_USERS,
23184             MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
23185             MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
23186             MANAGE_DEVICE_POLICY_SAFE_BOOT,
23187             MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
23188             MANAGE_DEVICE_POLICY_TIME,
23189             MANAGE_DEVICE_POLICY_WIPE_DATA
23190     );
23191 
23192     /**
23193      * All the permissions granted to a profile owner.
23194      */
23195     private static final List<String> PROFILE_OWNER_PERMISSIONS  =
23196             List.of(
23197                     MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
23198                     MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
23199                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
23200                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
23201                     MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
23202                     MANAGE_DEVICE_POLICY_AUTOFILL,
23203                     MANAGE_DEVICE_POLICY_BLUETOOTH,
23204                     MANAGE_DEVICE_POLICY_CALLS,
23205                     MANAGE_DEVICE_POLICY_CAMERA,
23206                     MANAGE_DEVICE_POLICY_CERTIFICATES,
23207                     MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
23208                     MANAGE_DEVICE_POLICY_DISPLAY,
23209                     MANAGE_DEVICE_POLICY_FACTORY_RESET,
23210                     MANAGE_DEVICE_POLICY_INPUT_METHODS,
23211                     MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
23212                     MANAGE_DEVICE_POLICY_KEYGUARD,
23213                     MANAGE_DEVICE_POLICY_LOCALE,
23214                     MANAGE_DEVICE_POLICY_LOCATION,
23215                     MANAGE_DEVICE_POLICY_LOCK,
23216                     MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
23217                     MANAGE_DEVICE_POLICY_CERTIFICATES,
23218                     MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
23219                     MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
23220                     MANAGE_DEVICE_POLICY_PACKAGE_STATE,
23221                     MANAGE_DEVICE_POLICY_PRINTING,
23222                     MANAGE_DEVICE_POLICY_PROFILES,
23223                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
23224                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
23225                     MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
23226                     MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
23227                     MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
23228                     MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
23229                     MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
23230                     MANAGE_DEVICE_POLICY_TIME,
23231                     MANAGE_DEVICE_POLICY_VPN,
23232                     MANAGE_DEVICE_POLICY_WIPE_DATA
23233             );
23234 
23235     /**
23236      * All the additional permissions granted to an organisation owned profile owner.
23237      */
23238     private static final List<String>
23239             ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS =
23240             List.of(
23241                     MANAGE_DEVICE_POLICY_ACROSS_USERS,
23242                     MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
23243                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
23244                     MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
23245                     MANAGE_DEVICE_POLICY_DEFAULT_SMS,
23246                     MANAGE_DEVICE_POLICY_LOCALE,
23247                     MANAGE_DEVICE_POLICY_MICROPHONE,
23248                     MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
23249                     MANAGE_DEVICE_POLICY_MTE,
23250                     MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
23251                     MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
23252                     MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
23253                     MANAGE_DEVICE_POLICY_SAFE_BOOT,
23254                     MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
23255                     MANAGE_DEVICE_POLICY_SMS,
23256                     MANAGE_DEVICE_POLICY_SYSTEM_UPDATES,
23257                     MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
23258                     MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
23259                     MANAGE_DEVICE_POLICY_WIFI,
23260                     SET_TIME,
23261                     SET_TIME_ZONE
23262             );
23263 
23264     /**
23265      * All the additional permissions granted to a Profile Owner on user 0.
23266      */
23267     private static final List<String> ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS =
23268             List.of(
23269                     MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
23270                     MANAGE_DEVICE_POLICY_DISPLAY,
23271                     MANAGE_DEVICE_POLICY_FUN,
23272                     MANAGE_DEVICE_POLICY_LOCK_TASK,
23273                     MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
23274                     MANAGE_DEVICE_POLICY_MODIFY_USERS,
23275                     MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
23276                     MANAGE_DEVICE_POLICY_PRINTING,
23277                     MANAGE_DEVICE_POLICY_PROFILES,
23278                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
23279                     MANAGE_DEVICE_POLICY_SAFE_BOOT,
23280                     MANAGE_DEVICE_POLICY_SMS,
23281                     MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
23282                     MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
23283                     MANAGE_DEVICE_POLICY_WINDOWS,
23284                     SET_TIME,
23285                     SET_TIME_ZONE
23286             );
23287 
23288     /**
23289      * All the additional permissions granted to a Profile Owner on an unaffiliated user.
23290      */
23291     private static final List<String> ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS =
23292             List.of(
23293                     MANAGE_DEVICE_POLICY_LOCK_TASK
23294             );
23295 
23296     /**
23297      * All the additional permissions granted to a Profile Owner on an affiliated user.
23298      */
23299     private static final List<String> ADDITIONAL_AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS =
23300             List.of(
23301                     MANAGE_DEVICE_POLICY_STATUS_BAR
23302             );
23303 
23304     /**
23305      * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
23306      * {@link ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS}.
23307      */
23308     private static final List<String> PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS =
23309             new ArrayList();
23310 
23311     /**
23312      * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
23313      * {@link ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS}.
23314      */
23315     private static final List<String> PROFILE_OWNER_ON_USER_0_PERMISSIONS  =
23316             new ArrayList();
23317 
23318     /**
23319      * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
23320      * {@link ADDITIONAL_AFFILIATED_PROFIL_OWNER_ON_USER_PERMISSIONS}.
23321      */
23322     private static final List<String> AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS =
23323             new ArrayList();
23324 
23325     /**
23326      * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
23327      * {@link ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS}.
23328      */
23329     private static final List<String> PROFILE_OWNER_ON_USER_PERMISSIONS =
23330             new ArrayList();
23331 
23332 
23333     private static final HashMap<Integer, List<String>> DPC_PERMISSIONS = new HashMap<>();
23334     {
23335         // Organisation owned profile owners have all the permission of a profile owner plus
23336         // some extra permissions.
23337         PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
23338         PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS.addAll(
23339                 ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS);
23340         // Profile owners on user 0 have all the permission of a profile owner plus
23341         // some extra permissions.
23342         PROFILE_OWNER_ON_USER_0_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
23343         PROFILE_OWNER_ON_USER_0_PERMISSIONS.addAll(ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS);
23344         // Profile owners on users have all the permission of a profile owner plus
23345         // some extra permissions.
23346         PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
23347         PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(
23348                 ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS);
23349         // Profile owners on affiliated users have all the permission of a profile owner on a user
23350         // plus some extra permissions.
23351         AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(PROFILE_OWNER_ON_USER_PERMISSIONS);
23352         AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(
23353                 ADDITIONAL_AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS);
23354 
23355         DPC_PERMISSIONS.put(DEFAULT_DEVICE_OWNER, DEFAULT_DEVICE_OWNER_PERMISSIONS);
23356         DPC_PERMISSIONS.put(FINANCED_DEVICE_OWNER, FINANCED_DEVICE_OWNER_PERMISSIONS);
23357         DPC_PERMISSIONS.put(PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE,
23358                 PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS);
23359         DPC_PERMISSIONS.put(PROFILE_OWNER_ON_USER_0, PROFILE_OWNER_ON_USER_0_PERMISSIONS);
23360         DPC_PERMISSIONS.put(PROFILE_OWNER, PROFILE_OWNER_PERMISSIONS);
23361         DPC_PERMISSIONS.put(PROFILE_OWNER_ON_USER, PROFILE_OWNER_ON_USER_PERMISSIONS);
23362         DPC_PERMISSIONS.put(AFFILIATED_PROFILE_OWNER_ON_USER,
23363                 AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS);
23364     }
23365     //Map of Permission to Delegate Scope.
23366     private static final HashMap<String, String> DELEGATE_SCOPES = new HashMap<>();
23367     {
23368         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_APP_RESTRICTIONS, DELEGATION_APP_RESTRICTIONS);
23369         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL, DELEGATION_BLOCK_UNINSTALL);
23370         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_CERTIFICATES, DELEGATION_CERT_INSTALL);
23371         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_PACKAGE_STATE, DELEGATION_PACKAGE_ACCESS);
23372         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, DELEGATION_PERMISSION_GRANT);
23373         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, DELEGATION_SECURITY_LOGGING);
23374     }
23375 
23376     private static final HashMap<String, String> CROSS_USER_PERMISSIONS =
23377             new HashMap<>();
23378     {
23379         // The permissions are all intrinsically global and therefore have no cross-user permission.
23380         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_FACTORY_RESET, null);
23381         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MTE, null);
23382         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, null);
23383         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_STATUS_BAR, null);
23384         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, null);
23385         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING, null);
23386         CROSS_USER_PERMISSIONS.put(SET_TIME, null);
23387         CROSS_USER_PERMISSIONS.put(SET_TIME_ZONE, null);
23388 
23389         // The permissions are all critical for securing data within the current user and
23390         // therefore are protected with MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL for
23391         // cross-user calls.
23392         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
23393                 MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);
23394         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_KEYGUARD,
23395                 MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);
23396         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
23397                 MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);
23398 
23399         // These permissions are required for securing device ownership without accessing user data
23400         // and therefore are protected with MANAGE_DEVICE_POLICY_ACROSS_USERS for cross-user calls.
23401         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
23402                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23403         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
23404                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23405         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_BLUETOOTH,
23406                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23407         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CALLS,
23408                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23409         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CAMERA,
23410                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23411         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DEFAULT_SMS,
23412                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23413         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_INPUT_METHODS,
23414                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23415         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MICROPHONE,
23416                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23417         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
23418                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23419         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
23420                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23421         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
23422                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23423         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PACKAGE_STATE,
23424                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23425         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
23426                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23427         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
23428                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23429         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SMS,
23430                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23431         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SAFE_BOOT,
23432                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23433         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_TIME,
23434                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23435         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
23436                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23437         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WIFI,
23438                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23439         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WIPE_DATA,
23440                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23441 
23442         // These permissions may grant access to user data and therefore must be protected with
23443         // MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL for cross-user calls.
23444         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_APPS_CONTROL,
23445                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23446         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
23447                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23448         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
23449                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23450         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AUTOFILL,
23451                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23452         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL,
23453                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23454         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CAMERA_TOGGLE,
23455                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23456         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
23457                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23458         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
23459                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23460         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DISPLAY,
23461                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23462         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_FUN,
23463                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23464         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCALE,
23465                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23466         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCATION,
23467                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23468         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK,
23469                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23470         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK_TASK,
23471                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23472         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MODIFY_USERS,
23473                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23474         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE,
23475                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23476         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
23477                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23478         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PROFILES,
23479                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23480         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
23481                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23482         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PRINTING,
23483                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23484         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RESET_PASSWORD,
23485                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23486         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
23487                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23488         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
23489                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23490         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
23491                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23492         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
23493                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23494         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_VPN,
23495                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23496         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WALLPAPER,
23497                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23498         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WINDOWS,
23499                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23500     }
23501 
23502     /**
23503      * Checks if the calling process has been granted permission to apply a device policy on a
23504      * specific user. Only one permission provided in the list needs to be granted to pass this
23505      * check.
23506      * The given permissions will be checked along with their associated cross-user permissions if
23507      * they exists and the target user is different to the calling user.
23508      * Returns an {@link EnforcingAdmin} for the caller.
23509      *
23510      * @param admin the component name of the admin.
23511      * @param callerPackageName The package name of the calling application.
23512      * @param permissions an array of permission names to be checked.
23513      * @param targetUserId The userId of the user which the caller needs permission to act on.
23514      * @throws SecurityException if the caller has not been granted the given permission,
23515      * the associated cross-user permission if the caller's user is different to the target user.
23516      */
23517     private EnforcingAdmin enforcePermissionsAndGetEnforcingAdmin(@Nullable ComponentName admin,
23518             String[] permissions, String callerPackageName, int targetUserId) {
23519         enforcePermissions(permissions, callerPackageName, targetUserId);
23520         return getEnforcingAdminForCaller(admin, callerPackageName);
23521     }
23522 
23523     /**
23524      * Checks if the calling process has been granted permission to apply a device policy on a
23525      * specific user.
23526      * The given permission will be checked along with its associated cross-user permission if it
23527      * exists and the target user is different to the calling user.
23528      * Returns an {@link EnforcingAdmin} for the caller.
23529      *
23530      * @param admin the component name of the admin.
23531      * @param callerPackageName The package name of the calling application.
23532      * @param permission The name of the permission being checked.
23533      * @param targetUserId The userId of the user which the caller needs permission to act on.
23534      * @throws SecurityException if the caller has not been granted the given permission,
23535      * the associated cross-user permission if the caller's user is different to the target user.
23536      */
23537     private EnforcingAdmin enforcePermissionAndGetEnforcingAdmin(@Nullable ComponentName admin,
23538             String permission, String callerPackageName, int targetUserId) {
23539         enforcePermission(permission, callerPackageName, targetUserId);
23540         return getEnforcingAdminForCaller(admin, callerPackageName);
23541     }
23542 
23543     /**
23544      * Checks if the calling process has been granted permission to apply a device policy on a
23545      * specific user.
23546      * The given permission will be checked along with its associated cross-user permission if it
23547      * exists and the target user is different to the calling user.
23548      * Returns an {@link EnforcingAdmin} for the caller.
23549      *
23550      * @param admin the component name of the admin.
23551      * @param callerPackageName The package name  of the calling application.
23552      * @param permission The name of the permission being checked.
23553      * @param deviceAdminPolicy The userId of the user which the caller needs permission to act on.
23554      * @throws SecurityException if the caller has not been granted the given permission,
23555      * the associated cross-user permission if the caller's user is different to the target user.
23556      */
23557     private EnforcingAdmin enforcePermissionAndGetEnforcingAdmin(@Nullable ComponentName admin,
23558             String permission, int deviceAdminPolicy, String callerPackageName, int targetUserId) {
23559         enforcePermission(permission, deviceAdminPolicy, callerPackageName, targetUserId);
23560         return getEnforcingAdminForCaller(admin, callerPackageName);
23561     }
23562 
23563     /**
23564      * Checks if the calling process has been granted permission to apply a device policy on a
23565      * specific user.  Only one permission provided in the list needs to be granted to pass this
23566      * check.
23567      * The given permissions will be checked along with their associated cross-user permissions if
23568      * they exist and the target user is different to the calling user.
23569      * Returns an {@link EnforcingAdmin} for the caller.
23570      *
23571      * @param admin the component name of the admin.
23572      * @param callerPackageName The package name of the calling application.
23573      * @param permissions The names of the permissions being checked.
23574      * @param deviceAdminPolicy The userId of the user which the caller needs permission to act on.
23575      * @throws SecurityException if the caller has not been granted the given permission,
23576      * the associated cross-user permission if the caller's user is different to the target user.
23577      */
23578     private EnforcingAdmin enforcePermissionsAndGetEnforcingAdmin(@Nullable ComponentName admin,
23579             String[] permissions, int deviceAdminPolicy, String callerPackageName,
23580             int targetUserId) {
23581         enforcePermissions(permissions, deviceAdminPolicy, callerPackageName, targetUserId);
23582         return getEnforcingAdminForCaller(admin, callerPackageName);
23583     }
23584 
23585     /**
23586      * Checks whether the calling process has been granted permission to query a device policy on
23587      * a specific user.
23588      * The given permission will be checked along with its associated cross-user permission if it
23589      * exists and the target user is different to the calling user.
23590      *
23591      * @param permission The name of the permission being checked.
23592      * @param targetUserId The userId of the user which the caller needs permission to act on.
23593      * @throws SecurityException if the caller has not been granted the given permission,
23594      * the associated cross-user permission if the caller's user is different to the target user.
23595      */
23596     private EnforcingAdmin enforceCanQueryAndGetEnforcingAdmin(@Nullable ComponentName admin,
23597             String permission, String callerPackageName, int targetUserId) {
23598         enforceCanQuery(permission, callerPackageName, targetUserId);
23599         return getEnforcingAdminForCaller(admin, callerPackageName);
23600     }
23601 
23602     private static final HashMap<String, String> POLICY_IDENTIFIER_TO_PERMISSION = new HashMap<>();
23603     {
23604         POLICY_IDENTIFIER_TO_PERMISSION.put(AUTO_TIMEZONE_POLICY, SET_TIME_ZONE);
23605     }
23606 
23607     private static final HashMap<String, Integer> POLICY_IDENTIFIER_TO_ACTIVE_ADMIN_POLICY =
23608             new HashMap<>();
23609 
23610     /**
23611      * Checks if the calling process has been granted permission to apply a device policy.
23612      *
23613      * @param callerPackageName The package name  of the calling application.
23614      * @param permission The name of the permission being checked.
23615      * @throws SecurityException if the caller has not been granted the given permission,
23616      * the associated cross-user permission if the caller's user is different to the target user.
23617      */
23618     private void enforcePermission(String permission, String callerPackageName)
23619             throws SecurityException {
23620         if (!hasPermission(permission, callerPackageName)) {
23621             throw new SecurityException("Caller does not have the required permissions for "
23622                     + "this user. Permission required: "
23623                     + permission
23624                     + ".");
23625         }
23626     }
23627 
23628 
23629     /**
23630      * Checks if the calling process has been granted permission to apply a device policy on a
23631      * specific user. Only one permission provided in the list needs to be granted to pass this
23632      * check.
23633      * The given permissions will be checked along with their associated cross-user permissions if
23634      * they exists and the target user is different to the calling user.
23635      *
23636      * @param callerPackageName The package name  of the calling application.
23637      * @param permissions The names of the permissions being checked.
23638      * @param targetUserId The userId of the user which the caller needs permission to act on.
23639      * @throws SecurityException if the caller has not been granted the given permission,
23640      * the associated cross-user permission if the caller's user is different to the target user.
23641      */
23642     private void enforcePermission(String permission, String callerPackageName, int targetUserId)
23643             throws SecurityException {
23644         enforcePermission(permission, callerPackageName);
23645         if (targetUserId != getCallerIdentity(callerPackageName).getUserId()) {
23646             enforcePermission(CROSS_USER_PERMISSIONS.get(permission), callerPackageName);
23647         }
23648     }
23649 
23650     /**
23651      * Checks if the calling process has been granted permission to apply a device policy on a
23652      * specific user. Only one of the given permissions will be required to be held to pass this
23653      * check.
23654      * The given permissions will be checked along with their associated cross-user permissions if
23655      * they exist and the target user is different to the calling user.
23656      *
23657      * @param permissions An array of the names of the permissions being checked.
23658      * @param callerPackageName The package name  of the calling application.
23659      * @param targetUserId The userId of the user which the caller needs permission to act on.
23660      * @throws SecurityException if the caller has not been granted the given permission,
23661      * the associated cross-user permission if the caller's user is different to the target user.
23662      */
23663     private void enforcePermissions(String[] permissions, String callerPackageName,
23664             int targetUserId) throws SecurityException {
23665         String heldPermission = "";
23666         for (String permission : permissions) {
23667             if (hasPermission(permission, callerPackageName)) {
23668                 heldPermission = permission;
23669                 break;
23670             }
23671         }
23672         if (heldPermission.isEmpty()) {
23673             throw new SecurityException("Caller does not have the required permissions for "
23674                     + "this user. One of the following permission required: "
23675                     + Arrays.toString(permissions));
23676         }
23677         enforcePermission(heldPermission, callerPackageName, targetUserId);
23678     }
23679 
23680     /**
23681      * Checks if the calling process has been granted permission to apply a device policy on a
23682      * specific user.
23683      * The given permission will be checked along with its associated cross-user permission if it
23684      * exists and the target user is different to the calling user.
23685      *
23686      * @param callerPackageName The package name  of the calling application.
23687      * @param adminPolicy The admin policy that should grant holders permission.
23688      * @param permission The name of the permission being checked.
23689      * @param targetUserId The userId of the user which the caller needs permission to act on.
23690      * @throws SecurityException if the caller has not been granted the given permission,
23691      * the associated cross-user permission if the caller's user is different to the target user.
23692      */
23693     private void enforcePermission(String permission, int adminPolicy,
23694             String callerPackageName, int targetUserId) throws SecurityException {
23695         if (hasAdminPolicy(adminPolicy, callerPackageName)) {
23696             return;
23697         }
23698         enforcePermission(permission, callerPackageName, targetUserId);
23699     }
23700 
23701     /**
23702      * Checks if the calling process has been granted permission to apply a device policy on a
23703      * specific user.
23704      * The given permission will be checked along with its associated cross-user permission if it
23705      * exists and the target user is different to the calling user.
23706      *
23707      * @param callerPackageName The package name  of the calling application.
23708      * @param adminPolicy The admin policy that should grant holders permission.
23709      * @param permissions The names of the permissions being checked.
23710      * @param targetUserId The userId of the user which the caller needs permission to act on.
23711      * @throws SecurityException if the caller has not been granted the given permission,
23712      * the associated cross-user permission if the caller's user is different to the target user.
23713      */
23714     private void enforcePermissions(String[] permissions, int adminPolicy,
23715             String callerPackageName, int targetUserId) throws SecurityException {
23716         if (hasAdminPolicy(adminPolicy, callerPackageName)
23717                 && mInjector.userHandleGetCallingUserId() == targetUserId) {
23718             return;
23719         }
23720         enforcePermissions(permissions, callerPackageName, targetUserId);
23721     }
23722 
23723     /**
23724      * Checks whether the calling process has been granted permission to query a device policy on
23725      * a specific user.
23726      * The given permission will be checked along with its associated cross-user permission if it
23727      * exists and the target user is different to the calling user.
23728      *
23729      * @param callerPackageName The package name  of the calling application.
23730      * @param permission The name of the permission being checked.
23731      * @param targetUserId The userId of the user which the caller needs permission to act on.
23732      * @throws SecurityException if the caller has not been granted the given permission,
23733      * the associated cross-user permission if the caller's user is different to the target user
23734      * and if the user has not been granted {@link QUERY_ADMIN_POLICY}.
23735      */
23736     private void enforceCanQuery(String permission, String callerPackageName, int targetUserId)
23737             throws SecurityException {
23738         if (hasPermission(QUERY_ADMIN_POLICY, callerPackageName)) {
23739             return;
23740         }
23741         enforcePermission(permission, callerPackageName, targetUserId);
23742     }
23743 
23744     private boolean hasAdminPolicy(int adminPolicy, String callerPackageName) {
23745         CallerIdentity caller = getCallerIdentity(callerPackageName);
23746         ActiveAdmin deviceAdmin = getActiveAdminWithPolicyForUidLocked(
23747                 null, adminPolicy, caller.getUid());
23748         return deviceAdmin != null;
23749     }
23750 
23751     /**
23752      * Return whether the calling process has been granted permission to apply a device policy on
23753      * a specific user.
23754      *
23755      * @param callerPackageName The package name  of the calling application.
23756      * @param permission The name of the permission being checked.
23757      * @param targetUserId The userId of the user which the caller needs permission to act on.
23758      */
23759     private boolean hasPermission(String permission, String callerPackageName, int targetUserId) {
23760         CallerIdentity caller = getCallerIdentity(callerPackageName);
23761         boolean hasPermissionOnOwnUser = hasPermission(permission, caller.getPackageName());
23762         boolean hasPermissionOnTargetUser = true;
23763         if (hasPermissionOnOwnUser && caller.getUserId() != targetUserId) {
23764             hasPermissionOnTargetUser = hasPermissionOnTargetUser
23765                     && hasPermission(CROSS_USER_PERMISSIONS.get(permission),
23766                         caller.getPackageName());
23767         }
23768 
23769         return hasPermissionOnOwnUser && hasPermissionOnTargetUser;
23770     }
23771 
23772     /**
23773      * Return whether the calling process has been granted the given permission.
23774      *
23775      * @param callerPackageName The package name  of the calling application.
23776      * @param permission The name of the permission being checked.
23777      */
23778     private boolean hasPermission(String permission, @NonNull String callerPackageName) {
23779         Objects.requireNonNull(callerPackageName, "callerPackageName is null");
23780         if (permission == null) {
23781             return true;
23782         }
23783 
23784         CallerIdentity caller = getCallerIdentity(callerPackageName);
23785 
23786         // Check if the caller holds the permission
23787         if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
23788             return true;
23789         }
23790         int dpcType = getDpcType(caller);
23791         if (dpcType != NOT_A_DPC) {
23792             return DPC_PERMISSIONS.get(dpcType).contains(permission);
23793         }
23794         // Check the permission for the role-holder
23795         if (isCallerDevicePolicyManagementRoleHolder(caller)) {
23796             return anyDpcHasPermission(permission, caller.getUserId());
23797         }
23798         if (DELEGATE_SCOPES.containsKey(permission)) {
23799             return isCallerDelegate(caller, DELEGATE_SCOPES.get(permission));
23800         }
23801         return false;
23802     }
23803 
23804     /**
23805      * Returns whether there is a DPC on the given user that has been granted the given permission.
23806      *
23807      * @param permission The name of the permission being checked.
23808      * @param userId The id of the user to check.
23809      */
23810     private boolean anyDpcHasPermission(String permission, int userId) {
23811         if (mOwners.isDefaultDeviceOwnerUserId(userId)) {
23812             return DPC_PERMISSIONS.get(DEFAULT_DEVICE_OWNER).contains(permission);
23813         }
23814         if (mOwners.isFinancedDeviceOwnerUserId(userId)) {
23815             return DPC_PERMISSIONS.get(FINANCED_DEVICE_OWNER).contains(permission);
23816         }
23817         if (mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId)) {
23818             return DPC_PERMISSIONS.get(PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE).contains(
23819                     permission);
23820         }
23821         if (userId == 0 && mOwners.hasProfileOwner(0)) {
23822             return DPC_PERMISSIONS.get(PROFILE_OWNER_ON_USER_0).contains(permission);
23823         }
23824         if (mOwners.hasProfileOwner(userId)) {
23825             return DPC_PERMISSIONS.get(PROFILE_OWNER).contains(permission);
23826         }
23827         return false;
23828     }
23829 
23830     private EnforcingAdmin getEnforcingAdminForCaller(@Nullable ComponentName who,
23831             String callerPackageName) {
23832         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
23833         int userId = caller.getUserId();
23834         ActiveAdmin admin;
23835         if (isDeviceOwner(caller) || isProfileOwner(caller) || isCallerDelegate(caller)) {
23836             ComponentName component;
23837             synchronized (getLockObject()) {
23838                 if (who != null) {
23839                     admin = getActiveAdminUncheckedLocked(who, userId);
23840                     component = who;
23841                 } else {
23842                     admin = getDeviceOrProfileOwnerAdminLocked(userId);
23843                     component = admin.info.getComponent();
23844                 }
23845             }
23846             return EnforcingAdmin.createEnterpriseEnforcingAdmin(component, userId, admin);
23847         }
23848         // Check for non-DPC active admins.
23849         admin = getActiveAdminForCaller(who, caller);
23850         if (admin != null) {
23851             return EnforcingAdmin.createDeviceAdminEnforcingAdmin(admin.info.getComponent(), userId,
23852                     admin);
23853         }
23854         admin = getUserData(userId).createOrGetPermissionBasedAdmin(userId);
23855         return  EnforcingAdmin.createEnforcingAdmin(caller.getPackageName(), userId, admin);
23856     }
23857 
23858     private EnforcingAdmin getEnforcingAdminForPackage(@Nullable ComponentName who,
23859             String packageName, int userId) {
23860         ActiveAdmin admin;
23861         if (who != null) {
23862             if (isDeviceOwner(who, userId) || isProfileOwner(who, userId)) {
23863                 synchronized (getLockObject()) {
23864                     admin = getActiveAdminUncheckedLocked(who, userId);
23865                 }
23866                 if (admin != null) {
23867                     return EnforcingAdmin.createEnterpriseEnforcingAdmin(who, userId, admin);
23868                 }
23869             } else {
23870                 // Check for non-DPC active admins.
23871                 admin = getActiveAdminUncheckedLocked(who, userId);
23872                 if (admin != null) {
23873                     return EnforcingAdmin.createDeviceAdminEnforcingAdmin(who, userId, admin);
23874                 }
23875             }
23876         }
23877 
23878         admin = getUserData(userId).createOrGetPermissionBasedAdmin(userId);
23879         return  EnforcingAdmin.createEnforcingAdmin(packageName, userId, admin);
23880     }
23881 
23882     private int getAffectedUser(boolean calledOnParent) {
23883         int callingUserId = mInjector.userHandleGetCallingUserId();
23884         return calledOnParent ? getProfileParentId(callingUserId) : callingUserId;
23885     }
23886 
23887     /**
23888      * Return the DPC type of the given caller.
23889      */
23890     private @DpcType int getDpcType(CallerIdentity caller) {
23891         // Check the permissions of DPCs
23892         if (isDefaultDeviceOwner(caller)) {
23893             return DEFAULT_DEVICE_OWNER;
23894         }
23895         if (isFinancedDeviceOwner(caller)) {
23896             return FINANCED_DEVICE_OWNER;
23897         }
23898         if (isProfileOwner(caller)) {
23899             if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
23900                 return PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;
23901             }
23902             if (isManagedProfile(caller.getUserId())) {
23903                 return PROFILE_OWNER;
23904             }
23905             if (isProfileOwnerOnUser0(caller)) {
23906                 return PROFILE_OWNER_ON_USER_0;
23907             }
23908             if (isUserAffiliatedWithDevice(caller.getUserId())) {
23909                 return AFFILIATED_PROFILE_OWNER_ON_USER;
23910             }
23911             return PROFILE_OWNER_ON_USER;
23912         }
23913         return NOT_A_DPC;
23914     }
23915 
23916     private boolean isPermissionCheckFlagEnabled() {
23917         return DeviceConfig.getBoolean(
23918                 NAMESPACE_DEVICE_POLICY_MANAGER,
23919                 PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG,
23920                 DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG);
23921     }
23922 
23923     static boolean isPolicyEngineForFinanceFlagEnabled() {
23924         return DeviceConfig.getBoolean(
23925                 NAMESPACE_DEVICE_POLICY_MANAGER,
23926                 ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG,
23927                 DEFAULT_ENABLE_DEVICE_POLICY_ENGINE_FOR_FINANCE_FLAG);
23928     }
23929 
23930     private static boolean isKeepProfilesRunningFlagEnabled() {
23931         return DEFAULT_KEEP_PROFILES_RUNNING_FLAG;
23932     }
23933 
23934     private boolean isUnicornFlagEnabled() {
23935         return false;
23936     }
23937 
23938     private void setKeepProfileRunningEnabledUnchecked(boolean keepProfileRunning) {
23939         synchronized (getLockObject()) {
23940             DevicePolicyData policyData = getUserDataUnchecked(UserHandle.USER_SYSTEM);
23941             if (policyData.mEffectiveKeepProfilesRunning == keepProfileRunning) {
23942                 return;
23943             }
23944             policyData.mEffectiveKeepProfilesRunning = keepProfileRunning;
23945             saveSettingsLocked(UserHandle.USER_SYSTEM);
23946         }
23947         suspendAppsForQuietProfiles(keepProfileRunning);
23948     }
23949 
23950     @Override
23951     public void setOverrideKeepProfilesRunning(boolean enabled) {
23952         Preconditions.checkCallAuthorization(
23953                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
23954         setKeepProfileRunningEnabledUnchecked(enabled);
23955         Slog.i(LOG_TAG, "Keep profiles running overridden to: " + enabled);
23956     }
23957 
23958     public void setMtePolicy(int flags, String callerPackageName) {
23959         final Set<Integer> allowedModes =
23960                 Set.of(
23961                         DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY,
23962                         DevicePolicyManager.MTE_DISABLED,
23963                         DevicePolicyManager.MTE_ENABLED);
23964         Preconditions.checkArgument(
23965                 allowedModes.contains(flags), "Provided mode is not one of the allowed values.");
23966         // In general, this API should be available when "bootctl_settings_toggle" is set, which
23967         // signals that there is a control for MTE in the user settings and this API fundamentally
23968         // is a way for the device admin to override that setting.
23969         // Allow bootctl_device_policy_manager as an override, e.g. to offer the
23970         // DevicePolicyManager only without a visible user setting.
23971         if (!mInjector.systemPropertiesGetBoolean(
23972                 "ro.arm64.memtag.bootctl_device_policy_manager",
23973                 mInjector.systemPropertiesGetBoolean(
23974                         "ro.arm64.memtag.bootctl_settings_toggle", false))) {
23975             throw new UnsupportedOperationException("device does not support MTE");
23976         }
23977         final CallerIdentity caller = getCallerIdentity(callerPackageName);
23978         // For now we continue to restrict the DISABLED setting to device owner - we might need
23979         // another permission for this in future.
23980         if (flags == DevicePolicyManager.MTE_DISABLED) {
23981             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
23982         }
23983 
23984         if (isPermissionCheckFlagEnabled()) {
23985             enforcePermission(MANAGE_DEVICE_POLICY_MTE, caller.getPackageName(),
23986                     UserHandle.USER_ALL);
23987         } else {
23988             Preconditions.checkCallAuthorization(
23989                     isDefaultDeviceOwner(caller)
23990                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
23991         }
23992         synchronized (getLockObject()) {
23993             // TODO(b/261999445): Remove
23994             ActiveAdmin admin;
23995             if (isHeadlessFlagEnabled()) {
23996                 admin =
23997                         getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
23998             } else {
23999                 admin =
24000                         getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
24001                                 UserHandle.USER_SYSTEM);
24002             }
24003 
24004             if (admin != null) {
24005                 final String memtagProperty = "arm64.memtag.bootctl";
24006                 if (flags == DevicePolicyManager.MTE_ENABLED) {
24007                     mInjector.systemPropertiesSet(memtagProperty, "memtag");
24008                 } else if (flags == DevicePolicyManager.MTE_DISABLED) {
24009                     mInjector.systemPropertiesSet(memtagProperty, "memtag-off");
24010                 }
24011                 admin.mtePolicy = flags;
24012                 saveSettingsLocked(caller.getUserId());
24013 
24014                 DevicePolicyEventLogger.createEvent(DevicePolicyEnums.SET_MTE_POLICY)
24015                         .setInt(flags)
24016                         .setAdmin(caller.getPackageName())
24017                         .write();
24018             }
24019         }
24020     }
24021 
24022     @Override
24023     public int getMtePolicy(String callerPackageName) {
24024         final CallerIdentity caller = getCallerIdentity(callerPackageName);
24025         if (isPermissionCheckFlagEnabled()) {
24026             enforcePermission(MANAGE_DEVICE_POLICY_MTE, caller.getPackageName(),
24027                     UserHandle.USER_ALL);
24028         } else {
24029             Preconditions.checkCallAuthorization(
24030                     isDefaultDeviceOwner(caller)
24031                             || isProfileOwnerOfOrganizationOwnedDevice(caller)
24032                             || isSystemUid(caller));
24033         }
24034         synchronized (getLockObject()) {
24035             // TODO(b/261999445): Remove
24036             ActiveAdmin admin;
24037             if (isHeadlessFlagEnabled()) {
24038                 admin =
24039                         getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
24040             } else {
24041                 admin =
24042                         getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
24043                                 UserHandle.USER_SYSTEM);
24044             }
24045             return admin != null
24046                     ? admin.mtePolicy
24047                     : DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY;
24048         }
24049     }
24050 
24051     private boolean isHeadlessFlagEnabled() {
24052         return DeviceConfig.getBoolean(
24053                 NAMESPACE_DEVICE_POLICY_MANAGER,
24054                 HEADLESS_FLAG,
24055                 DEFAULT_HEADLESS_FLAG);
24056     }
24057 
24058     @Override
24059     public ManagedSubscriptionsPolicy getManagedSubscriptionsPolicy() {
24060         synchronized (getLockObject()) {
24061             ActiveAdmin admin = getProfileOwnerOfOrganizationOwnedDeviceLocked();
24062             if (admin != null && admin.mManagedSubscriptionsPolicy != null) {
24063                 return admin.mManagedSubscriptionsPolicy;
24064             }
24065         }
24066         return new ManagedSubscriptionsPolicy(
24067                 ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS);
24068     }
24069 
24070     @Override
24071     public void setManagedSubscriptionsPolicy(ManagedSubscriptionsPolicy policy) {
24072         CallerIdentity caller = getCallerIdentity();
24073 
24074         if (!isCallerDevicePolicyManagementRoleHolder(caller)
24075                 && !Objects.equals(mInjector.settingsGlobalGetString(
24076                         Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS), "1")) {
24077             throw new UnsupportedOperationException("This api is not enabled");
24078         }
24079 
24080         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller),
24081                 "This policy can only be set by a profile owner on an organization-owned "
24082                         + "device.");
24083 
24084         int parentUserId = getProfileParentId(caller.getUserId());
24085         synchronized (getLockObject()) {
24086             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
24087             if (hasUserSetupCompleted(parentUserId) && !isAdminTestOnlyLocked(
24088                     admin.info.getComponent(), caller.getUserId())) {
24089                 throw new IllegalStateException("Not allowed to apply this policy after setup");
24090             }
24091             boolean changed = false;
24092             if (!Objects.equals(policy, admin.mManagedSubscriptionsPolicy)) {
24093                 admin.mManagedSubscriptionsPolicy = policy;
24094                 changed = true;
24095             }
24096             if (changed) {
24097                 saveSettingsLocked(caller.getUserId());
24098             } else {
24099                 return;
24100             }
24101         }
24102 
24103         applyManagedSubscriptionsPolicyIfRequired();
24104 
24105         int policyType = getManagedSubscriptionsPolicy().getPolicyType();
24106         final long id = mInjector.binderClearCallingIdentity();
24107         try {
24108             if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
24109                 installOemDefaultDialerAndSmsApp(caller.getUserId());
24110                 updateTelephonyCrossProfileIntentFilters(parentUserId, caller.getUserId(), true);
24111             } else if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS) {
24112                 updateTelephonyCrossProfileIntentFilters(parentUserId, caller.getUserId(), false);
24113             }
24114         } finally {
24115             mInjector.binderRestoreCallingIdentity(id);
24116         }
24117     }
24118 
24119     private void installOemDefaultDialerAndSmsApp(int targetUserId) {
24120         try {
24121             String defaultDialerPackageName = getOemDefaultDialerPackage();
24122             String defaultSmsPackageName = getOemDefaultSmsPackage();
24123 
24124             if (defaultDialerPackageName != null) {
24125                 mIPackageManager.installExistingPackageAsUser(defaultDialerPackageName,
24126                         targetUserId, PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
24127                         PackageManager.INSTALL_REASON_POLICY, null);
24128             } else {
24129                 Slogf.w(LOG_TAG, "Couldn't install dialer app, dialer app package is null");
24130             }
24131 
24132             if (defaultSmsPackageName != null) {
24133                 mIPackageManager.installExistingPackageAsUser(defaultSmsPackageName, targetUserId,
24134                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
24135                         PackageManager.INSTALL_REASON_POLICY, null);
24136             } else {
24137                 Slogf.w(LOG_TAG, "Couldn't install sms app, sms app package is null");
24138             }
24139 
24140             updateDialerAndSmsManagedShortcutsOverrideCache();
24141         } catch (RemoteException re) {
24142             // shouldn't happen
24143             Slogf.wtf(LOG_TAG, "Failed to install dialer/sms app", re);
24144         }
24145     }
24146 
24147     private String getOemDefaultDialerPackage() {
24148         TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
24149         return telecomManager.getSystemDialerPackage();
24150     }
24151 
24152     private String getOemDefaultSmsPackage() {
24153         return mContext.getString(R.string.config_defaultSms);
24154     }
24155 
24156     private void updateDialerAndSmsManagedShortcutsOverrideCache() {
24157         ArrayMap<String, String> shortcutOverrides = new ArrayMap<>();
24158         int managedUserId = getManagedUserId();
24159         List<String> dialerRoleHolders = mRoleManager.getRoleHoldersAsUser(RoleManager.ROLE_DIALER,
24160                 UserHandle.of(managedUserId));
24161         List<String> smsRoleHolders = mRoleManager.getRoleHoldersAsUser(RoleManager.ROLE_SMS,
24162                 UserHandle.of(managedUserId));
24163 
24164         String dialerPackageToOverride = getOemDefaultDialerPackage();
24165         String smsPackageToOverride = getOemDefaultSmsPackage();
24166 
24167         // To get the default app, we can get all the role holders and get the first element.
24168         if (dialerPackageToOverride != null) {
24169             shortcutOverrides.put(dialerPackageToOverride,
24170                     dialerRoleHolders.isEmpty() ? dialerPackageToOverride
24171                             : dialerRoleHolders.get(0));
24172         }
24173         if (smsPackageToOverride != null) {
24174             shortcutOverrides.put(smsPackageToOverride,
24175                     smsRoleHolders.isEmpty() ? smsPackageToOverride : smsRoleHolders.get(0));
24176         }
24177 
24178         mPolicyCache.setLauncherShortcutOverrides(shortcutOverrides);
24179     }
24180 
24181     private void registerListenerToAssignSubscriptionsToUser(int userId) {
24182         synchronized (mSubscriptionsChangedListenerLock) {
24183             if (mSubscriptionsChangedListener != null) {
24184                 return;
24185             }
24186             SubscriptionManager subscriptionManager = mContext.getSystemService(
24187                     SubscriptionManager.class);
24188             // Listener to assign all current and future subs to managed profile.
24189             mSubscriptionsChangedListener = new SubscriptionManager.OnSubscriptionsChangedListener(
24190                     mHandler.getLooper()) {
24191                 @Override
24192                 public void onSubscriptionsChanged() {
24193                     final long id = mInjector.binderClearCallingIdentity();
24194                     try {
24195                         int[] subscriptionIds = subscriptionManager.getActiveSubscriptionIdList(
24196                                 false);
24197                         for (int subId : subscriptionIds) {
24198                             UserHandle associatedUserHandle =
24199                                     subscriptionManager.getSubscriptionUserHandle(subId);
24200                             if (associatedUserHandle == null
24201                                     || associatedUserHandle.getIdentifier() != userId) {
24202                                 subscriptionManager.setSubscriptionUserHandle(subId,
24203                                         UserHandle.of(userId));
24204                             }
24205                         }
24206                     } finally {
24207                         mInjector.binderRestoreCallingIdentity(id);
24208                     }
24209                 }
24210             };
24211 
24212             final long id = mInjector.binderClearCallingIdentity();
24213             try {
24214                 // When listener is added onSubscriptionsChanged gets called immediately for once
24215                 // (even if subscriptions are not changed) and later on when subscriptions changes.
24216                 subscriptionManager.addOnSubscriptionsChangedListener(
24217                         mSubscriptionsChangedListener.getHandlerExecutor(),
24218                         mSubscriptionsChangedListener);
24219             } finally {
24220                 mInjector.binderRestoreCallingIdentity(id);
24221             }
24222         }
24223     }
24224 
24225     private void unregisterOnSubscriptionsChangedListener() {
24226         synchronized (mSubscriptionsChangedListenerLock) {
24227             if (mSubscriptionsChangedListener != null) {
24228                 SubscriptionManager subscriptionManager = mContext.getSystemService(
24229                         SubscriptionManager.class);
24230                 subscriptionManager.removeOnSubscriptionsChangedListener(
24231                         mSubscriptionsChangedListener);
24232                 mSubscriptionsChangedListener = null;
24233             }
24234         }
24235     }
24236 
24237     @Override
24238     public DevicePolicyState getDevicePolicyState() {
24239         Preconditions.checkCallAuthorization(
24240                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
24241 
24242         return mInjector.binderWithCleanCallingIdentity(mDevicePolicyEngine::getDevicePolicyState);
24243     }
24244 
24245     @Override
24246     public boolean triggerDevicePolicyEngineMigration(boolean forceMigration) {
24247         Preconditions.checkCallAuthorization(
24248                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
24249         return mInjector.binderWithCleanCallingIdentity(() -> {
24250             boolean canForceMigration = forceMigration && !hasNonTestOnlyActiveAdmins();
24251             if (!canForceMigration && !shouldMigrateToDevicePolicyEngine()) {
24252                 return false;
24253             }
24254             return migratePoliciesToDevicePolicyEngine();
24255         });
24256     }
24257 
24258     private boolean hasNonTestOnlyActiveAdmins() {
24259         return mInjector.binderWithCleanCallingIdentity(() -> {
24260             for (UserInfo userInfo : mUserManager.getUsers()) {
24261                 synchronized (getLockObject()) {
24262                     List<ComponentName> activeAdmins = getActiveAdmins(userInfo.id);
24263                     if (activeAdmins == null) {
24264                         continue;
24265                     }
24266                     for (ComponentName admin : activeAdmins) {
24267                         if (!isAdminTestOnlyLocked(admin, userInfo.id)) {
24268                             return true;
24269                         }
24270                     }
24271                 }
24272             }
24273             return false;
24274         });
24275     }
24276 
24277     private boolean shouldMigrateToDevicePolicyEngine() {
24278         return mInjector.binderWithCleanCallingIdentity(() ->
24279                 (isPermissionCheckFlagEnabled() || isPolicyEngineForFinanceFlagEnabled())
24280                         && !mOwners.isMigratedToPolicyEngine());
24281     }
24282 
24283     /**
24284      * @return {@code true} if policies were migrated successfully, {@code false} otherwise.
24285      */
24286     private boolean migratePoliciesToDevicePolicyEngine() {
24287         return mInjector.binderWithCleanCallingIdentity(() -> {
24288             try {
24289                 synchronized (getLockObject()) {
24290                     Slogf.i(LOG_TAG,
24291                             "Started device policies migration to the device policy engine.");
24292                     if (isUnicornFlagEnabled()) {
24293                         migrateAutoTimezonePolicy();
24294                         migratePermissionGrantStatePolicies();
24295                     }
24296                     migrateScreenCapturePolicyLocked();
24297                     migratePermittedInputMethodsPolicyLocked();
24298                     migrateAccountManagementDisabledPolicyLocked();
24299                     migrateUserControlDisabledPackagesLocked();
24300 
24301                     mOwners.markMigrationToPolicyEngine();
24302                     return true;
24303                 }
24304             } catch (Exception e) {
24305                 mDevicePolicyEngine.clearAllPolicies();
24306                 Slogf.e(LOG_TAG, e, "Error occurred during device policy migration, will "
24307                         + "reattempt on the next system server restart.");
24308                 return false;
24309             }
24310         });
24311     }
24312 
24313     private void migrateAutoTimezonePolicy() {
24314         Slogf.i(LOG_TAG, "Skipping Migration of AUTO_TIMEZONE policy to device policy engine,"
24315                 + "as no way to identify if the value was set by the admin or the user.");
24316     }
24317 
24318     private void migratePermissionGrantStatePolicies() {
24319         Slogf.i(LOG_TAG, "Migrating PERMISSION_GRANT policy to device policy engine.");
24320         for (UserInfo userInfo : mUserManager.getUsers()) {
24321             ActiveAdmin admin = getMostProbableDPCAdminForLocalPolicy(userInfo.id);
24322             if (admin == null) {
24323                 Slogf.i(LOG_TAG, "No admin found that can set permission grant state on user "
24324                         + userInfo.id);
24325                 continue;
24326             }
24327             for (PackageInfo packageInfo : getInstalledPackagesOnUser(userInfo.id)) {
24328                 if (packageInfo.requestedPermissions == null) {
24329                     continue;
24330                 }
24331                 for (String permission : packageInfo.requestedPermissions) {
24332                     if (!isRuntimePermission(permission)) {
24333                         continue;
24334                     }
24335                     int grantState = DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
24336                     try {
24337                         grantState = getPermissionGrantStateForUser(
24338                                 packageInfo.packageName, permission,
24339                                 new CallerIdentity(
24340                                         mInjector.binderGetCallingUid(),
24341                                         admin.info.getComponent().getPackageName(),
24342                                         admin.info.getComponent()),
24343                                 userInfo.id);
24344                     } catch (RemoteException e) {
24345                         Slogf.e(LOG_TAG, e, "Error retrieving permission grant state for %s "
24346                                         + "and %s", packageInfo.packageName, permission);
24347                     }
24348                     if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
24349                         // Not Controlled by a policy
24350                         continue;
24351                     }
24352 
24353                     mDevicePolicyEngine.setLocalPolicy(
24354                             PolicyDefinition.PERMISSION_GRANT(packageInfo.packageName,
24355                                     permission),
24356                             EnforcingAdmin.createEnterpriseEnforcingAdmin(
24357                                     admin.info.getComponent(),
24358                                     admin.getUserHandle().getIdentifier()),
24359                             new IntegerPolicyValue(grantState),
24360                             userInfo.id,
24361                             /* skipEnforcePolicy= */ true);
24362                 }
24363             }
24364         }
24365     }
24366 
24367     private void migrateScreenCapturePolicyLocked() {
24368         Binder.withCleanCallingIdentity(() -> {
24369             if (mPolicyCache.getScreenCaptureDisallowedUser() == UserHandle.USER_NULL) {
24370                 return;
24371             }
24372             ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
24373             if (admin != null
24374                     && ((isDeviceOwner(admin) && admin.disableScreenCapture)
24375                     || (admin.getParentActiveAdmin() != null
24376                     && admin.getParentActiveAdmin().disableScreenCapture))) {
24377                 EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24378                         admin.info.getComponent(),
24379                         admin.getUserHandle().getIdentifier(),
24380                         admin);
24381                 mDevicePolicyEngine.setGlobalPolicy(
24382                         PolicyDefinition.SCREEN_CAPTURE_DISABLED,
24383                         enforcingAdmin,
24384                         new BooleanPolicyValue(true));
24385             }
24386 
24387             List<UserInfo> users = mUserManager.getUsers();
24388             for (UserInfo userInfo : users) {
24389                 ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
24390                 if (profileOwner != null && profileOwner.disableScreenCapture) {
24391                     EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24392                             profileOwner.info.getComponent(),
24393                             profileOwner.getUserHandle().getIdentifier(),
24394                             profileOwner);
24395                     mDevicePolicyEngine.setLocalPolicy(
24396                             PolicyDefinition.SCREEN_CAPTURE_DISABLED,
24397                             enforcingAdmin,
24398                             new BooleanPolicyValue(true),
24399                             profileOwner.getUserHandle().getIdentifier());
24400                 }
24401             }
24402         });
24403     }
24404 
24405     private void migratePermittedInputMethodsPolicyLocked() {
24406         Binder.withCleanCallingIdentity(() -> {
24407             List<UserInfo> users = mUserManager.getUsers();
24408             for (UserInfo userInfo : users) {
24409                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
24410                 if (admin != null) {
24411                     EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24412                             admin.info.getComponent(),
24413                             admin.getUserHandle().getIdentifier(),
24414                             admin);
24415                     if (admin.permittedInputMethods != null) {
24416                         mDevicePolicyEngine.setLocalPolicy(
24417                                 PolicyDefinition.PERMITTED_INPUT_METHODS,
24418                                 enforcingAdmin,
24419                                 new StringSetPolicyValue(
24420                                         new HashSet<>(admin.permittedInputMethods)),
24421                                 admin.getUserHandle().getIdentifier());
24422                     }
24423                     if (admin.getParentActiveAdmin() != null
24424                             && admin.getParentActiveAdmin().permittedInputMethods != null) {
24425                         mDevicePolicyEngine.setLocalPolicy(
24426                                 PolicyDefinition.PERMITTED_INPUT_METHODS,
24427                                 enforcingAdmin,
24428                                 new StringSetPolicyValue(
24429                                         new HashSet<>(admin.getParentActiveAdmin()
24430                                                 .permittedInputMethods)),
24431                                 getProfileParentId(admin.getUserHandle().getIdentifier()));
24432                     }
24433                 }
24434             }
24435         });
24436     }
24437 
24438     private void migrateAccountManagementDisabledPolicyLocked() {
24439         Binder.withCleanCallingIdentity(() -> {
24440             List<UserInfo> users = mUserManager.getUsers();
24441             for (UserInfo userInfo : users) {
24442                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
24443                 if (admin != null) {
24444                     EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24445                             admin.info.getComponent(),
24446                             admin.getUserHandle().getIdentifier(),
24447                             admin);
24448                     for (String accountType : admin.accountTypesWithManagementDisabled) {
24449                         mDevicePolicyEngine.setLocalPolicy(
24450                                 PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
24451                                 enforcingAdmin,
24452                                 new BooleanPolicyValue(true),
24453                                 admin.getUserHandle().getIdentifier());
24454                     }
24455                     if (admin.getParentActiveAdmin() != null) {
24456                         for (String accountType : admin.getParentActiveAdmin()
24457                                 .accountTypesWithManagementDisabled) {
24458                             mDevicePolicyEngine.setLocalPolicy(
24459                                     PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
24460                                     enforcingAdmin,
24461                                     new BooleanPolicyValue(true),
24462                                     getProfileParentId(admin.getUserHandle().getIdentifier()));
24463                         }
24464                     }
24465                 }
24466             }
24467         });
24468     }
24469 
24470     private void migrateUserControlDisabledPackagesLocked() {
24471         Binder.withCleanCallingIdentity(() -> {
24472             List<UserInfo> users = mUserManager.getUsers();
24473             for (UserInfo userInfo : users) {
24474                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
24475                 if (admin != null && admin.protectedPackages != null) {
24476                     EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24477                             admin.info.getComponent(),
24478                             admin.getUserHandle().getIdentifier(),
24479                             admin);
24480                     if (isDeviceOwner(admin)) {
24481                         mDevicePolicyEngine.setGlobalPolicy(
24482                                 PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
24483                                 enforcingAdmin,
24484                                 new StringSetPolicyValue(new HashSet<>(admin.protectedPackages)));
24485                     } else {
24486                         mDevicePolicyEngine.setLocalPolicy(
24487                                 PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
24488                                 enforcingAdmin,
24489                                 new StringSetPolicyValue(new HashSet<>(admin.protectedPackages)),
24490                                 admin.getUserHandle().getIdentifier());
24491                     }
24492                 }
24493             }
24494         });
24495     }
24496 
24497     private List<PackageInfo> getInstalledPackagesOnUser(int userId) {
24498         return mInjector.binderWithCleanCallingIdentity(() ->
24499                 mContext.getPackageManager().getInstalledPackagesAsUser(
24500                         PackageManager.PackageInfoFlags.of(
24501                                 PackageManager.GET_PERMISSIONS), userId));
24502     }
24503 
24504     /**
24505      * Returns the most probable admin to have set a global policy according to the following
24506      * heuristics:
24507      *
24508      * <ul>
24509      * <li>The device owner on any user</li>
24510      * <li>The org owned profile owner on any user</li>
24511      * <li>The profile owner on any user</li>
24512      * </ul>
24513      */
24514     @Nullable
24515     // TODO(b/266928216): Check what the admin capabilities are when deciding which admin to return.
24516     private ActiveAdmin getMostProbableDPCAdminForGlobalPolicy() {
24517         synchronized (getLockObject()) {
24518             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
24519             if (deviceOwner != null) {
24520                 return deviceOwner;
24521             }
24522 
24523             List<UserInfo> users = mUserManager.getUsers();
24524             for (UserInfo userInfo : users) {
24525                 if (isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
24526                     return getProfileOwnerAdminLocked(userInfo.id);
24527                 }
24528             }
24529 
24530             for (UserInfo userInfo : users) {
24531                 ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
24532                 if (profileOwner != null) {
24533                     return profileOwner;
24534                 }
24535             }
24536             return null;
24537         }
24538     }
24539 
24540     /**
24541      * Returns the most probable admin to have set a policy on the given {@code userId} according
24542      * to the following heuristics:
24543      *
24544      * <ul>
24545      * <li>The device owner on the given userId</li>
24546      * <li>The profile owner on the given userId</li>
24547      * <li>The org owned profile owner of which the given userId is its parent</li>
24548      * <li>The profile owner of which the given userId is its parent</li>
24549      * <li>The device owner on any user</li>
24550      * <li>The profile owner on any user</li>
24551      * </ul>
24552      */
24553     @Nullable
24554     // TODO(b/266928216): Check what the admin capabilities are when deciding which admin to return.
24555     private ActiveAdmin getMostProbableDPCAdminForLocalPolicy(int userId) {
24556         synchronized (getLockObject()) {
24557             ActiveAdmin localDeviceOwner = getDeviceOwnerLocked(userId);
24558             if (localDeviceOwner != null) {
24559                 return localDeviceOwner;
24560             }
24561 
24562             ActiveAdmin localProfileOwner = getProfileOwnerLocked(userId);
24563             if (localProfileOwner != null) {
24564                 return localProfileOwner;
24565             }
24566 
24567             int[] profileIds = mUserManager.getProfileIds(userId, /* enabledOnly= */ false);
24568             for (int id : profileIds) {
24569                 if (id == userId) {
24570                     continue;
24571                 }
24572                 if (isProfileOwnerOfOrganizationOwnedDevice(id)) {
24573                     return getProfileOwnerAdminLocked(id);
24574                 }
24575             }
24576 
24577             for (int id : profileIds) {
24578                 if (id == userId) {
24579                     continue;
24580                 }
24581                 if (isManagedProfile(id)) {
24582                     return getProfileOwnerAdminLocked(id);
24583                 }
24584             }
24585 
24586             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
24587             if (deviceOwner != null) {
24588                 return deviceOwner;
24589             }
24590 
24591             for (UserInfo userInfo : mUserManager.getUsers()) {
24592                 ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
24593                 if (profileOwner != null) {
24594                     return profileOwner;
24595                 }
24596             }
24597             return null;
24598         }
24599     }
24600 
24601     // We need to add a mapping of policyId to permission in POLICY_IDENTIFIER_TO_PERMISSION
24602     // for each migrated permission.
24603     private List<ActiveAdmin> getNonDPCActiveAdminsForPolicyLocked(String policyIdentifier) {
24604         Integer activeAdminPolicy = POLICY_IDENTIFIER_TO_ACTIVE_ADMIN_POLICY.get(policyIdentifier);
24605         if (activeAdminPolicy == null) {
24606             Slogf.e(LOG_TAG,
24607                     "Can't find a active admin policy for %s in POLICY_IDENTIFIER_TO_PERMISSION",
24608                     policyIdentifier);
24609             return new ArrayList<>();
24610         }
24611 
24612         List<ActiveAdmin> admins = new ArrayList<>();
24613         for (UserInfo userInfo : mUserManager.getUsers()) {
24614             List<ComponentName> activeAdmins = getActiveAdmins(userInfo.id);
24615             for (ComponentName admin : activeAdmins) {
24616                 if (isDeviceOwner(admin, userInfo.id) || isProfileOwner(admin, userInfo.id)) {
24617                     continue;
24618                 }
24619                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
24620                 if (isActiveAdminWithPolicyForUserLocked(
24621                         policy.mAdminMap.get(admin), activeAdminPolicy,
24622                         userInfo.id)) {
24623                     admins.add(policy.mAdminMap.get(admin));
24624                 }
24625             }
24626         }
24627         return admins;
24628     }
24629 
24630     // TODO: this can actually accept an EnforcingAdmin that gets created in the permission
24631     //  check method.
24632     private boolean isCallerActiveAdminOrDelegate(
24633             CallerIdentity caller, @Nullable String delegateScope) {
24634         return mInjector.binderWithCleanCallingIdentity(() -> {
24635             List<ComponentName> activeAdmins = getActiveAdmins(caller.getUserId());
24636             if (activeAdmins != null) {
24637                 for (ComponentName admin : activeAdmins) {
24638                     if (admin.getPackageName().equals(caller.getPackageName())) {
24639                         return true;
24640                     }
24641                 }
24642             }
24643             return delegateScope != null && isCallerDelegate(caller, delegateScope);
24644         });
24645     }
24646 
24647     /**
24648      * Truncates char sequence to maximum length, nulls are ignored.
24649      */
24650     private static CharSequence truncateIfLonger(CharSequence input, int maxLength) {
24651         return input == null || input.length() <= maxLength
24652                 ? input
24653                 : input.subSequence(0, maxLength);
24654     }
24655 
24656     /**
24657      * Throw if string argument is too long to be serialized.
24658      */
24659     private static void enforceMaxStringLength(String str, String argName) {
24660         Preconditions.checkArgument(
24661                 str.length() <= MAX_POLICY_STRING_LENGTH, argName + " loo long");
24662     }
24663 
24664     private static void enforceMaxPackageNameLength(String pkg) {
24665         Preconditions.checkArgument(
24666                 pkg.length() <= MAX_PACKAGE_NAME_LENGTH, "Package name too long");
24667     }
24668 
24669     /**
24670      * Throw if persistable bundle contains any string that we can't serialize.
24671      */
24672     private static void enforceMaxStringLength(PersistableBundle bundle, String argName) {
24673         // Persistable bundles can have other persistable bundles as values, traverse with a queue.
24674         Queue<PersistableBundle> queue = new ArrayDeque<>();
24675         queue.add(bundle);
24676         while (!queue.isEmpty()) {
24677             PersistableBundle current = queue.remove();
24678             for (String key : current.keySet()) {
24679                 enforceMaxStringLength(key, "key in " + argName);
24680                 Object value = current.get(key);
24681                 if (value instanceof String) {
24682                     enforceMaxStringLength((String) value, "string value in " + argName);
24683                 } else if (value instanceof String[]) {
24684                     for (String str : (String[]) value) {
24685                         enforceMaxStringLength(str, "string value in " + argName);
24686                     }
24687                 } else if (value instanceof PersistableBundle) {
24688                     queue.add((PersistableBundle) value);
24689                 }
24690             }
24691         }
24692     }
24693 
24694     private ActiveAdmin getActiveAdminForCaller(@Nullable ComponentName who,
24695             CallerIdentity caller) {
24696         synchronized (getLockObject()) {
24697             if (who != null) {
24698                 return getActiveAdminUncheckedLocked(who, caller.getUserId());
24699             }
24700             return mInjector.binderWithCleanCallingIdentity(() -> {
24701                 List<ComponentName> activeAdmins = getActiveAdmins(caller.getUserId());
24702                 if (activeAdmins != null) {
24703                     for (ComponentName admin : activeAdmins) {
24704                         if (admin.getPackageName().equals(caller.getPackageName())) {
24705                             return getActiveAdminUncheckedLocked(admin, caller.getUserId());
24706                         }
24707                     }
24708                 }
24709                 return null;
24710             });
24711         }
24712     }
24713 
24714     @Override
24715     public boolean isDeviceFinanced(String callerPackageName) {
24716         CallerIdentity caller = getCallerIdentity(callerPackageName);
24717         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
24718                 || isProfileOwnerOfOrganizationOwnedDevice(caller)
24719                 || isProfileOwnerOnUser0(caller)
24720                 || isCallerDevicePolicyManagementRoleHolder(caller)
24721                 || isCallerSystemSupervisionRoleHolder(caller));
24722         return getFinancedDeviceKioskRoleHolderOnAnyUser() != null;
24723     };
24724 
24725     @Override
24726     public String getFinancedDeviceKioskRoleHolder(String callerPackageName) {
24727         CallerIdentity caller = getCallerIdentity(callerPackageName);
24728         enforcePermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, caller.getPackageName(),
24729                 caller.getUserId());
24730         return getFinancedDeviceKioskRoleHolderOnAnyUser();
24731     }
24732 
24733     private String getFinancedDeviceKioskRoleHolderOnAnyUser() {
24734         return getRoleHolderPackageNameOnUser(
24735                 RoleManager.ROLE_FINANCED_DEVICE_KIOSK, UserHandle.USER_ALL);
24736     }
24737 }
24738