• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_ASSIST_CONTENT;
31 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AUDIO_OUTPUT;
32 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AUDIT_LOGGING;
33 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_AUTOFILL;
34 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL;
35 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_BLUETOOTH;
36 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CALLS;
37 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CAMERA;
38 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CAMERA_TOGGLE;
39 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CERTIFICATES;
40 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE;
41 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_CONTENT_PROTECTION;
42 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES;
43 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DEFAULT_SMS;
44 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_DISPLAY;
45 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FACTORY_RESET;
46 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_FUN;
47 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INPUT_METHODS;
48 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES;
49 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_KEYGUARD;
50 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCALE;
51 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCATION;
52 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK;
53 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS;
54 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_LOCK_TASK;
55 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS;
56 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MICROPHONE;
57 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE;
58 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MOBILE_NETWORK;
59 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MODIFY_USERS;
60 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_MTE;
61 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION;
62 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY;
63 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PACKAGE_STATE;
64 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA;
65 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PRINTING;
66 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILES;
67 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_PROFILE_INTERACTION;
68 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES;
69 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESET_PASSWORD;
70 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS;
71 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS;
72 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_RUN_IN_BACKGROUND;
73 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SAFE_BOOT;
74 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CAPTURE;
75 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SCREEN_CONTENT;
76 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SECURITY_LOGGING;
77 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SMS;
78 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_STATUS_BAR;
79 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_STORAGE_LIMIT;
80 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE;
81 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS;
82 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_SYSTEM_UPDATES;
83 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_THREAD_NETWORK;
84 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_TIME;
85 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING;
86 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER;
87 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_VPN;
88 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WALLPAPER;
89 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIFI;
90 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WINDOWS;
91 import static android.Manifest.permission.MANAGE_DEVICE_POLICY_WIPE_DATA;
92 import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
93 import static android.Manifest.permission.MASTER_CLEAR;
94 import static android.Manifest.permission.NOTIFY_PENDING_SYSTEM_UPDATE;
95 import static android.Manifest.permission.QUERY_ADMIN_POLICY;
96 import static android.Manifest.permission.QUERY_DEVICE_STOLEN_STATE;
97 import static android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY;
98 import static android.Manifest.permission.SET_TIME;
99 import static android.Manifest.permission.SET_TIME_ZONE;
100 import static android.accessibilityservice.AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
101 import static android.accounts.AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION;
102 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
103 import static android.app.AppOpsManager.MODE_ALLOWED;
104 import static android.app.AppOpsManager.MODE_DEFAULT;
105 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION;
106 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS;
107 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION;
108 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS;
109 import static android.app.AppOpsManager.OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION;
110 import static android.app.AppOpsManager.OP_RUN_ANY_IN_BACKGROUND;
111 import static android.app.AppOpsManager.OP_RUN_IN_BACKGROUND;
112 import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_AFFILIATED;
113 import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER;
114 import static android.app.admin.DeviceAdminInfo.HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED;
115 import static android.app.admin.DeviceAdminInfo.USES_POLICY_FORCE_LOCK;
116 import static android.app.admin.DeviceAdminInfo.USES_POLICY_WIPE_DATA;
117 import static android.app.admin.DeviceAdminReceiver.ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED;
118 import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE;
119 import static android.app.admin.DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE;
120 import static android.app.admin.DevicePolicyManager.ACTION_DEVICE_FINANCING_STATE_CHANGED;
121 import static android.app.admin.DevicePolicyManager.ACTION_DEVICE_POLICY_RESOURCE_UPDATED;
122 import static android.app.admin.DevicePolicyManager.ACTION_MANAGED_PROFILE_PROVISIONED;
123 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE;
124 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE;
125 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
126 import static android.app.admin.DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED;
127 import static android.app.admin.DevicePolicyManager.CONTENT_PROTECTION_DISABLED;
128 import static android.app.admin.DevicePolicyManager.ContentProtectionPolicy;
129 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
130 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
131 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
132 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_SELECTION;
133 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
134 import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE;
135 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
136 import static android.app.admin.DevicePolicyManager.DELEGATION_NETWORK_LOGGING;
137 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
138 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
139 import static android.app.admin.DevicePolicyManager.DELEGATION_SECURITY_LOGGING;
140 import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_DEFAULT;
141 import static android.app.admin.DevicePolicyManager.DEVICE_OWNER_TYPE_FINANCED;
142 import static android.app.admin.DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
143 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION;
144 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS;
145 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_HIBERNATION;
146 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_POWER_RESTRICTIONS;
147 import static android.app.admin.DevicePolicyManager.EXEMPT_FROM_SUSPENSION;
148 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE;
149 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_IDS;
150 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE;
151 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_DRAWABLE;
152 import static android.app.admin.DevicePolicyManager.EXTRA_RESOURCE_TYPE_STRING;
153 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
154 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
155 import static android.app.admin.DevicePolicyManager.ID_TYPE_INDIVIDUAL_ATTESTATION;
156 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
157 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
158 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
159 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK;
160 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
161 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME;
162 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_KEYGUARD;
163 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS;
164 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
165 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO;
166 import static android.app.admin.DevicePolicyManager.NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
167 import static android.app.admin.DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
168 import static android.app.admin.DevicePolicyManager.OPERATION_SAFETY_REASON_NONE;
169 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
170 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_LOW;
171 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
172 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
173 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
174 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
175 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK;
176 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
177 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED;
178 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
179 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
180 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
181 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
182 import static android.app.admin.DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
183 import static android.app.admin.DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED;
184 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED;
185 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_EXPLICITLY;
186 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT;
187 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OFF;
188 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
189 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
190 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_UNKNOWN;
191 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
192 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR;
193 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
194 import static android.app.admin.DevicePolicyManager.STATE_USER_SETUP_FINALIZED;
195 import static android.app.admin.DevicePolicyManager.STATE_USER_UNMANAGED;
196 import static android.app.admin.DevicePolicyManager.STATUS_ACCOUNTS_NOT_EMPTY;
197 import static android.app.admin.DevicePolicyManager.STATUS_CANNOT_ADD_MANAGED_PROFILE;
198 import static android.app.admin.DevicePolicyManager.STATUS_DEVICE_ADMIN_NOT_SUPPORTED;
199 import static android.app.admin.DevicePolicyManager.STATUS_HAS_DEVICE_OWNER;
200 import static android.app.admin.DevicePolicyManager.STATUS_HAS_PAIRED;
201 import static android.app.admin.DevicePolicyManager.STATUS_HEADLESS_ONLY_SYSTEM_USER;
202 import static android.app.admin.DevicePolicyManager.STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED;
203 import static android.app.admin.DevicePolicyManager.STATUS_MANAGED_USERS_NOT_SUPPORTED;
204 import static android.app.admin.DevicePolicyManager.STATUS_NONSYSTEM_USER_EXISTS;
205 import static android.app.admin.DevicePolicyManager.STATUS_NOT_SYSTEM_USER;
206 import static android.app.admin.DevicePolicyManager.STATUS_OK;
207 import static android.app.admin.DevicePolicyManager.STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
208 import static android.app.admin.DevicePolicyManager.STATUS_SYSTEM_USER;
209 import static android.app.admin.DevicePolicyManager.STATUS_USER_HAS_PROFILE_OWNER;
210 import static android.app.admin.DevicePolicyManager.STATUS_USER_NOT_RUNNING;
211 import static android.app.admin.DevicePolicyManager.STATUS_USER_SETUP_COMPLETED;
212 import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
213 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
214 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
215 import static android.app.admin.DevicePolicyManager.WIPE_SILENTLY;
216 import static android.app.admin.DevicePolicyResources.Strings.Core.LOCATION_CHANGED_MESSAGE;
217 import static android.app.admin.DevicePolicyResources.Strings.Core.LOCATION_CHANGED_TITLE;
218 import static android.app.admin.DevicePolicyResources.Strings.Core.NETWORK_LOGGING_MESSAGE;
219 import static android.app.admin.DevicePolicyResources.Strings.Core.NETWORK_LOGGING_TITLE;
220 import static android.app.admin.DevicePolicyResources.Strings.Core.NOTIFICATION_WORK_PROFILE_CONTENT_DESCRIPTION;
221 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_MESSAGE;
222 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_SOON_MESSAGE;
223 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_TITLE;
224 import static android.app.admin.DevicePolicyResources.Strings.Core.PERSONAL_APP_SUSPENSION_TURN_ON_PROFILE;
225 import static android.app.admin.DevicePolicyResources.Strings.Core.PRINTING_DISABLED_NAMED_ADMIN;
226 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_FAILED_PASSWORD_ATTEMPTS_MESSAGE;
227 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_GENERIC_MESSAGE;
228 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_ORG_OWNED_MESSAGE;
229 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_DELETED_TITLE;
230 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_BODY;
231 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_TITLE;
232 import static android.app.admin.DevicePolicyResources.Strings.Core.WORK_PROFILE_TELEPHONY_PAUSED_TURN_ON_BUTTON;
233 import static android.app.admin.PolicySizeVerifier.MAX_LONG_SUPPORT_MESSAGE_LENGTH;
234 import static android.app.admin.PolicySizeVerifier.MAX_ORG_NAME_LENGTH;
235 import static android.app.admin.PolicySizeVerifier.MAX_PROFILE_NAME_LENGTH;
236 import static android.app.admin.PolicySizeVerifier.MAX_SHORT_SUPPORT_MESSAGE_LENGTH;
237 import static android.app.admin.ProvisioningException.ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED;
238 import static android.app.admin.ProvisioningException.ERROR_PRE_CONDITION_FAILED;
239 import static android.app.admin.ProvisioningException.ERROR_PROFILE_CREATION_FAILED;
240 import static android.app.admin.ProvisioningException.ERROR_REMOVE_NON_REQUIRED_APPS_FAILED;
241 import static android.app.admin.ProvisioningException.ERROR_SETTING_PROFILE_OWNER_FAILED;
242 import static android.app.admin.ProvisioningException.ERROR_SET_DEVICE_OWNER_FAILED;
243 import static android.app.admin.ProvisioningException.ERROR_STARTING_PROFILE_FAILED;
244 import static android.content.Intent.ACTION_MANAGED_PROFILE_AVAILABLE;
245 import static android.content.Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE;
246 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
247 import static android.content.pm.PackageManager.GET_META_DATA;
248 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
249 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
250 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
251 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
252 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT;
253 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE;
254 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING;
255 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK;
256 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
257 import static android.provider.DeviceConfig.NAMESPACE_DEVICE_POLICY_MANAGER;
258 import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER;
259 import static android.provider.Settings.Secure.MANAGED_PROVISIONING_DPC_DOWNLOADED;
260 import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
261 import static android.provider.Telephony.Carriers.DPC_URI;
262 import static android.provider.Telephony.Carriers.ENFORCE_KEY;
263 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI;
264 import static android.provider.Telephony.Carriers.INVALID_APN_ID;
265 import static android.security.keystore.AttestationUtils.USE_INDIVIDUAL_ATTESTATION;
266 
267 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
268 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
269 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST;
270 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
271 import static com.android.server.SystemTimeZone.TIME_ZONE_CONFIDENCE_HIGH;
272 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
273 import static com.android.server.devicepolicy.DevicePolicyEngine.DEFAULT_POLICY_SIZE_LIMIT;
274 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER;
275 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER;
276 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
277 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_DEVICE_OWNER;
278 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER;
279 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;
280 
281 import android.Manifest;
282 import android.Manifest.permission;
283 import android.accessibilityservice.AccessibilityServiceInfo;
284 import android.accounts.Account;
285 import android.accounts.AccountManager;
286 import android.accounts.AuthenticatorException;
287 import android.accounts.OperationCanceledException;
288 import android.annotation.IntDef;
289 import android.annotation.NonNull;
290 import android.annotation.Nullable;
291 import android.annotation.UserIdInt;
292 import android.app.Activity;
293 import android.app.ActivityManager;
294 import android.app.ActivityManagerInternal;
295 import android.app.ActivityTaskManager;
296 import android.app.AlarmManager;
297 import android.app.AppGlobals;
298 import android.app.AppOpsManager;
299 import android.app.AppOpsManager.Mode;
300 import android.app.BroadcastOptions;
301 import android.app.IActivityManager;
302 import android.app.IActivityTaskManager;
303 import android.app.IApplicationThread;
304 import android.app.IServiceConnection;
305 import android.app.Notification;
306 import android.app.NotificationManager;
307 import android.app.PendingIntent;
308 import android.app.StatusBarManager;
309 import android.app.admin.AccountTypePolicyKey;
310 import android.app.admin.BooleanPolicyValue;
311 import android.app.admin.BundlePolicyValue;
312 import android.app.admin.ComponentNamePolicyValue;
313 import android.app.admin.DeviceAdminInfo;
314 import android.app.admin.DeviceAdminReceiver;
315 import android.app.admin.DevicePolicyCache;
316 import android.app.admin.DevicePolicyDrawableResource;
317 import android.app.admin.DevicePolicyEventLogger;
318 import android.app.admin.DevicePolicyManager;
319 import android.app.admin.DevicePolicyManager.DeviceOwnerType;
320 import android.app.admin.DevicePolicyManager.DevicePolicyOperation;
321 import android.app.admin.DevicePolicyManager.OperationSafetyReason;
322 import android.app.admin.DevicePolicyManager.PasswordComplexity;
323 import android.app.admin.DevicePolicyManager.PersonalAppsSuspensionReason;
324 import android.app.admin.DevicePolicyManagerInternal;
325 import android.app.admin.DevicePolicyManagerLiteInternal;
326 import android.app.admin.DevicePolicySafetyChecker;
327 import android.app.admin.DevicePolicyState;
328 import android.app.admin.DevicePolicyStringResource;
329 import android.app.admin.DeviceStateCache;
330 import android.app.admin.FactoryResetProtectionPolicy;
331 import android.app.admin.FullyManagedDeviceProvisioningParams;
332 import android.app.admin.IAuditLogEventsCallback;
333 import android.app.admin.IDevicePolicyManager;
334 import android.app.admin.IntegerPolicyValue;
335 import android.app.admin.IntentFilterPolicyKey;
336 import android.app.admin.LockTaskPolicy;
337 import android.app.admin.LongPolicyValue;
338 import android.app.admin.ManagedProfileProvisioningParams;
339 import android.app.admin.ManagedSubscriptionsPolicy;
340 import android.app.admin.NetworkEvent;
341 import android.app.admin.PackagePolicy;
342 import android.app.admin.PackageSetPolicyValue;
343 import android.app.admin.ParcelableGranteeMap;
344 import android.app.admin.ParcelableResource;
345 import android.app.admin.PasswordMetrics;
346 import android.app.admin.PasswordPolicy;
347 import android.app.admin.PolicyKey;
348 import android.app.admin.PolicySizeVerifier;
349 import android.app.admin.PolicyValue;
350 import android.app.admin.PreferentialNetworkServiceConfig;
351 import android.app.admin.SecurityLog;
352 import android.app.admin.SecurityLog.SecurityEvent;
353 import android.app.admin.StartInstallingUpdateCallback;
354 import android.app.admin.SystemUpdateInfo;
355 import android.app.admin.SystemUpdatePolicy;
356 import android.app.admin.UnsafeStateException;
357 import android.app.admin.UserRestrictionPolicyKey;
358 import android.app.admin.WifiSsidPolicy;
359 import android.app.admin.flags.Flags;
360 import android.app.backup.IBackupManager;
361 import android.app.compat.CompatChanges;
362 import android.app.role.OnRoleHoldersChangedListener;
363 import android.app.role.RoleManager;
364 import android.app.trust.TrustManager;
365 import android.app.usage.UsageStatsManagerInternal;
366 import android.compat.annotation.ChangeId;
367 import android.compat.annotation.EnabledAfter;
368 import android.compat.annotation.EnabledSince;
369 import android.content.ActivityNotFoundException;
370 import android.content.BroadcastReceiver;
371 import android.content.ComponentName;
372 import android.content.ContentResolver;
373 import android.content.ContentValues;
374 import android.content.Context;
375 import android.content.IIntentReceiver;
376 import android.content.IIntentSender;
377 import android.content.Intent;
378 import android.content.IntentFilter;
379 import android.content.IntentSender;
380 import android.content.PermissionChecker;
381 import android.content.pm.ActivityInfo;
382 import android.content.pm.ApplicationInfo;
383 import android.content.pm.CrossProfileApps;
384 import android.content.pm.CrossProfileAppsInternal;
385 import android.content.pm.IPackageDataObserver;
386 import android.content.pm.IPackageManager;
387 import android.content.pm.PackageInfo;
388 import android.content.pm.PackageInstaller;
389 import android.content.pm.PackageManager;
390 import android.content.pm.PackageManager.NameNotFoundException;
391 import android.content.pm.PackageManagerInternal;
392 import android.content.pm.ParceledListSlice;
393 import android.content.pm.PermissionInfo;
394 import android.content.pm.ResolveInfo;
395 import android.content.pm.ServiceInfo;
396 import android.content.pm.Signature;
397 import android.content.pm.StringParceledListSlice;
398 import android.content.pm.UserInfo;
399 import android.content.pm.UserPackage;
400 import android.content.pm.parsing.FrameworkParsingPackageUtils;
401 import android.content.res.Resources;
402 import android.database.ContentObserver;
403 import android.database.Cursor;
404 import android.graphics.Bitmap;
405 import android.hardware.usb.UsbManager;
406 import android.location.Location;
407 import android.location.LocationManager;
408 import android.media.AudioManager;
409 import android.net.ConnectivityManager;
410 import android.net.ConnectivitySettingsManager;
411 import android.net.IIpConnectivityMetrics;
412 import android.net.ProfileNetworkPreference;
413 import android.net.ProxyInfo;
414 import android.net.Uri;
415 import android.net.VpnManager;
416 import android.net.metrics.IpConnectivityLog;
417 import android.net.wifi.WifiManager;
418 import android.os.AsyncTask;
419 import android.os.Binder;
420 import android.os.Build;
421 import android.os.Bundle;
422 import android.os.Handler;
423 import android.os.IBinder;
424 import android.os.Looper;
425 import android.os.ParcelFileDescriptor;
426 import android.os.PersistableBundle;
427 import android.os.PowerManager;
428 import android.os.PowerManagerInternal;
429 import android.os.Process;
430 import android.os.RemoteCallback;
431 import android.os.RemoteException;
432 import android.os.ResultReceiver;
433 import android.os.ServiceManager;
434 import android.os.ServiceSpecificException;
435 import android.os.ShellCallback;
436 import android.os.SystemClock;
437 import android.os.SystemProperties;
438 import android.os.UserHandle;
439 import android.os.UserManager;
440 import android.os.UserManager.EnforcingUser;
441 import android.os.UserManager.UserRestrictionSource;
442 import android.os.storage.StorageManager;
443 import android.permission.AdminPermissionControlParams;
444 import android.permission.IPermissionManager;
445 import android.permission.PermissionControllerManager;
446 import android.provider.CalendarContract;
447 import android.provider.ContactsContract.QuickContact;
448 import android.provider.ContactsInternal;
449 import android.provider.DeviceConfig;
450 import android.provider.Settings;
451 import android.provider.Settings.Global;
452 import android.provider.Telephony;
453 import android.security.AppUriAuthenticationPolicy;
454 import android.security.IKeyChainAliasCallback;
455 import android.security.IKeyChainService;
456 import android.security.KeyChain;
457 import android.security.KeyChain.KeyChainConnection;
458 import android.security.keymaster.KeymasterCertificateChain;
459 import android.security.keystore.AttestationUtils;
460 import android.security.keystore.KeyGenParameterSpec;
461 import android.security.keystore.KeyProperties;
462 import android.security.keystore.ParcelableKeyGenParameterSpec;
463 import android.stats.devicepolicy.DevicePolicyEnums;
464 import android.telecom.TelecomManager;
465 import android.telephony.SubscriptionInfo;
466 import android.telephony.SubscriptionManager;
467 import android.telephony.TelephonyManager;
468 import android.telephony.data.ApnSetting;
469 import android.text.TextUtils;
470 import android.text.format.DateUtils;
471 import android.util.ArrayMap;
472 import android.util.ArraySet;
473 import android.util.AtomicFile;
474 import android.util.DebugUtils;
475 import android.util.IndentingPrintWriter;
476 import android.util.IntArray;
477 import android.util.Pair;
478 import android.util.Slog;
479 import android.util.SparseArray;
480 import android.util.Xml;
481 import android.view.IWindowManager;
482 import android.view.accessibility.AccessibilityManager;
483 import android.view.accessibility.IAccessibilityManager;
484 import android.view.inputmethod.InputMethodInfo;
485 
486 import com.android.internal.R;
487 import com.android.internal.annotations.GuardedBy;
488 import com.android.internal.annotations.VisibleForTesting;
489 import com.android.internal.app.LocalePicker;
490 import com.android.internal.infra.AndroidFuture;
491 import com.android.internal.logging.MetricsLogger;
492 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
493 import com.android.internal.net.NetworkUtilsInternal;
494 import com.android.internal.notification.SystemNotificationChannels;
495 import com.android.internal.os.BackgroundThread;
496 import com.android.internal.statusbar.IStatusBarService;
497 import com.android.internal.telephony.SmsApplication;
498 import com.android.internal.util.ArrayUtils;
499 import com.android.internal.util.DumpUtils;
500 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
501 import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
502 import com.android.internal.util.JournaledFile;
503 import com.android.internal.util.Preconditions;
504 import com.android.internal.util.StatLogger;
505 import com.android.internal.widget.LockPatternUtils;
506 import com.android.internal.widget.LockSettingsInternal;
507 import com.android.internal.widget.LockscreenCredential;
508 import com.android.internal.widget.PasswordValidationError;
509 import com.android.modules.utils.TypedXmlPullParser;
510 import com.android.modules.utils.TypedXmlSerializer;
511 import com.android.net.module.util.ProxyUtils;
512 import com.android.server.AlarmManagerInternal;
513 import com.android.server.LocalManagerRegistry;
514 import com.android.server.LocalServices;
515 import com.android.server.LockGuard;
516 import com.android.server.SystemServerInitThreadPool;
517 import com.android.server.SystemService;
518 import com.android.server.SystemServiceManager;
519 import com.android.server.devicepolicy.ActiveAdmin.TrustAgentInfo;
520 import com.android.server.inputmethod.InputMethodManagerInternal;
521 import com.android.server.net.NetworkPolicyManagerInternal;
522 import com.android.server.pdb.PersistentDataBlockManagerInternal;
523 import com.android.server.pm.DefaultCrossProfileIntentFilter;
524 import com.android.server.pm.DefaultCrossProfileIntentFiltersUtils;
525 import com.android.server.pm.PackageManagerLocal;
526 import com.android.server.pm.RestrictionsSet;
527 import com.android.server.pm.UserManagerInternal;
528 import com.android.server.pm.UserManagerInternal.UserRestrictionsListener;
529 import com.android.server.pm.UserRestrictionsUtils;
530 import com.android.server.pm.pkg.AndroidPackage;
531 import com.android.server.storage.DeviceStorageMonitorInternal;
532 import com.android.server.uri.NeededUriGrants;
533 import com.android.server.uri.UriGrantsManagerInternal;
534 import com.android.server.utils.Slogf;
535 import com.android.server.wm.ActivityTaskManagerInternal;
536 
537 import org.xmlpull.v1.XmlPullParserException;
538 
539 import java.io.ByteArrayInputStream;
540 import java.io.File;
541 import java.io.FileDescriptor;
542 import java.io.FileInputStream;
543 import java.io.FileOutputStream;
544 import java.io.IOException;
545 import java.io.PrintWriter;
546 import java.lang.reflect.Constructor;
547 import java.security.cert.CertificateException;
548 import java.security.cert.CertificateFactory;
549 import java.security.cert.X509Certificate;
550 import java.text.DateFormat;
551 import java.time.LocalDate;
552 import java.util.ArrayList;
553 import java.util.Arrays;
554 import java.util.Collection;
555 import java.util.Collections;
556 import java.util.Date;
557 import java.util.HashMap;
558 import java.util.HashSet;
559 import java.util.LinkedHashMap;
560 import java.util.List;
561 import java.util.Locale;
562 import java.util.Map;
563 import java.util.Objects;
564 import java.util.Set;
565 import java.util.concurrent.CompletableFuture;
566 import java.util.concurrent.ExecutionException;
567 import java.util.concurrent.Executor;
568 import java.util.concurrent.LinkedBlockingQueue;
569 import java.util.concurrent.ThreadPoolExecutor;
570 import java.util.concurrent.TimeUnit;
571 import java.util.concurrent.TimeoutException;
572 import java.util.function.BiConsumer;
573 import java.util.function.Consumer;
574 import java.util.function.Function;
575 import java.util.function.Predicate;
576 import java.util.stream.Collectors;
577 
578 /**
579  * Implementation of the device policy APIs.
580  */
581 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
582 
583     protected static final String LOG_TAG = "DevicePolicyManager";
584 
585     private static final String ATTRIBUTION_TAG = "DevicePolicyManagerService";
586 
587     static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
588 
589     static final String DEVICE_POLICIES_XML = "device_policies.xml";
590 
591     static final String POLICIES_VERSION_XML = "device_policies_version";
592 
593     private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML =
594             "transfer-ownership-parameters.xml";
595 
596     private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle";
597 
598     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
599 
600     private static final int REQUEST_PROFILE_OFF_DEADLINE = 5572;
601 
602     private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
603 
604     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
605     private static final long MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD = 3 * MS_PER_DAY;
606     /** When to warn the user about the approaching work profile off deadline: 1 day before */
607     private static final long MANAGED_PROFILE_OFF_WARNING_PERIOD = 1 * MS_PER_DAY;
608 
609     private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION =
610             "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
611 
612     /** Broadcast action invoked when the user taps a notification to turn the profile on. */
613     @VisibleForTesting
614     static final String ACTION_TURN_PROFILE_ON_NOTIFICATION =
615             "com.android.server.ACTION_TURN_PROFILE_ON_NOTIFICATION";
616 
617     /** Broadcast action for tracking managed profile maximum time off. */
618     @VisibleForTesting
619     static final String ACTION_PROFILE_OFF_DEADLINE =
620             "com.android.server.ACTION_PROFILE_OFF_DEADLINE";
621 
622     private static final String CALLED_FROM_PARENT = "calledFromParent";
623     private static final String NOT_CALLED_FROM_PARENT = "notCalledFromParent";
624 
625     private static final String CREDENTIAL_MANAGEMENT_APP = "credentialManagementApp";
626     private static final String NOT_CREDENTIAL_MANAGEMENT_APP = "notCredentialManagementApp";
627 
628     private static final String NULL_STRING_ARRAY = "nullStringArray";
629 
630     private static final String ALLOW_USER_PROVISIONING_KEY = "ro.config.allowuserprovisioning";
631 
632     // Comprehensive list of delegations.
633     private static final String DELEGATIONS[] = {
634         DELEGATION_CERT_INSTALL,
635         DELEGATION_APP_RESTRICTIONS,
636         DELEGATION_BLOCK_UNINSTALL,
637         DELEGATION_ENABLE_SYSTEM_APP,
638         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
639         DELEGATION_PACKAGE_ACCESS,
640         DELEGATION_PERMISSION_GRANT,
641         DELEGATION_INSTALL_EXISTING_PACKAGE,
642         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
643         DELEGATION_NETWORK_LOGGING,
644         DELEGATION_SECURITY_LOGGING,
645         DELEGATION_CERT_SELECTION,
646     };
647 
648     // Subset of delegations that can only be delegated by Device Owner or Profile Owner of a
649     // managed profile.
650     private static final List<String> DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS =
651             Arrays.asList(new String[]{
652                     DELEGATION_NETWORK_LOGGING,
653             });
654 
655     // Subset of delegations that can only be delegated by Device Owner or Profile Owner of an
656     // organization-owned and managed profile.
657     private static final List<String>
658             DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS =
659             Arrays.asList(new String[]{
660                     DELEGATION_SECURITY_LOGGING,
661             });
662 
663     // Subset of delegations that only one single package within a given user can hold
664     private static final List<String> EXCLUSIVE_DELEGATIONS = Arrays.asList(new String[] {
665             DELEGATION_NETWORK_LOGGING,
666             DELEGATION_SECURITY_LOGGING,
667             DELEGATION_CERT_SELECTION,
668     });
669 
670     private static final int STATUS_BAR_DISABLE_MASK =
671             StatusBarManager.DISABLE_EXPAND |
672             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
673             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
674             StatusBarManager.DISABLE_SEARCH;
675 
676     private static final int STATUS_BAR_DISABLE2_MASK =
677             StatusBarManager.DISABLE2_QUICK_SETTINGS;
678 
679     private static final Set<String> SECURE_SETTINGS_ALLOWLIST;
680     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST;
681     private static final Set<String> GLOBAL_SETTINGS_ALLOWLIST;
682     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
683     private static final Set<String> SYSTEM_SETTINGS_ALLOWLIST;
684     private static final Set<Integer> DA_DISALLOWED_POLICIES;
685     private static final String AB_DEVICE_KEY = "ro.build.ab_update";
686     // The version of the current DevicePolicyManagerService data. This version is used
687     // to decide whether an existing policy in the {@link #DEVICE_POLICIES_XML} needs to
688     // be upgraded. See {@link PolicyVersionUpgrader} on instructions how to add an upgrade
689     // step.
690     static final int DPMS_VERSION = 6;
691 
692     static {
693         SECURE_SETTINGS_ALLOWLIST = new ArraySet<>();
694         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
695         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
696         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
697 
698         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST = new ArraySet<>();
699         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.addAll(SECURE_SETTINGS_ALLOWLIST);
700         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.add(Settings.Secure.LOCATION_MODE);
701 
702         GLOBAL_SETTINGS_ALLOWLIST = new ArraySet<>();
703         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_ENABLED);
704         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_WIFI_ENABLED);
705         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME);
706         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME_ZONE);
707         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.DATA_ROAMING);
708         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
709         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_SLEEP_POLICY);
710         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
711         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
712         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_MODE);
713         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER);
714 
715         GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
716         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
717         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
718         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
719         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
720         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
721 
722         SYSTEM_SETTINGS_ALLOWLIST = new ArraySet<>();
723         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS);
724         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE);
725         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_OFF_TIMEOUT);
726 
727         DA_DISALLOWED_POLICIES = new ArraySet<>();
728         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
729         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
730         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
731         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
732     }
733 
734     /**
735      * Keyguard features that when set on a profile affect the profile content or challenge only.
736      * These cannot be set on the managed profile's parent DPM instance
737      */
738     private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
739             DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS
740                     | DevicePolicyManager.KEYGUARD_DISABLE_WIDGETS_ALL;
741 
742     /** Keyguard features that are allowed to be set on a managed profile */
743     private static final int PROFILE_KEYGUARD_FEATURES =
744             NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
745                     | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
746 
747     private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
748 
749     /**
750      * Minimum timeout in milliseconds after which unlocking with weak auth times out,
751      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
752      */
753     private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
754 
755     /**
756      * The amount of ms that a managed kiosk must go without user interaction to be considered
757      * unattended.
758      */
759     private static final int UNATTENDED_MANAGED_KIOSK_MS = 30000;
760 
761     /**
762      * Strings logged with {@link
763      * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB},
764      * {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB},
765      * {@link DevicePolicyEnums#SET_NETWORK_LOGGING_ENABLED} and
766      * {@link DevicePolicyEnums#RETRIEVE_NETWORK_LOGS}.
767      */
768     private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
769     private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
770 
771     /**
772      * For admin apps targeting R+, throw when the app sets password requirement
773      * that is not taken into account at given quality. For example when quality is set
774      * to {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, it doesn't
775      * make sense to require certain password length. If the intent is to require a password of
776      * certain length having at least NUMERIC quality, the admin should first call
777      * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} and only then call
778      * {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLength}.
779      *
780      * <p>Conversely when an admin app targeting R+ lowers password quality, those
781      * requirements that stop making sense are reset to default values.
782      */
783     @ChangeId
784     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
785     private static final long ADMIN_APP_PASSWORD_COMPLEXITY = 123562444L;
786 
787     /**
788      * Admin apps targeting Android R+ may not use
789      * {@link android.app.admin.DevicePolicyManager#setSecureSetting} to change the deprecated
790      * {@link android.provider.Settings.Secure#LOCATION_MODE} setting. Instead they should use
791      * {@link android.app.admin.DevicePolicyManager#setLocationEnabled}.
792      */
793     @ChangeId
794     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
795     private static final long USE_SET_LOCATION_ENABLED = 117835097L;
796 
797     /**
798      * Forces wipeDataNoLock to attempt removing the user or throw an error as
799      * opposed to trying to factory reset the device first and only then falling back to user
800      * removal.
801      */
802     @ChangeId
803     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
804     public static final long EXPLICIT_WIPE_BEHAVIOUR = 242193913L;
805 
806     /**
807      * Apps targeting V+ should now expect that attempts to grant sensor permissions without
808      * authorisation will result in a security exception.
809      */
810     @ChangeId
811     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.VANILLA_ICE_CREAM)
812     public static final long THROW_SECURITY_EXCEPTION_FOR_SENSOR_PERMISSIONS = 277035314L;
813 
814     /**
815      * Allows DPCs to provisioning fully managed headless devices in single-user mode.
816      */
817     @ChangeId
818     @EnabledSince(targetSdkVersion = 35)
819     public static final long PROVISION_SINGLE_USER_MODE = 289515470L;
820 
821     // Only add to the end of the list. Do not change or rearrange these values, that will break
822     // historical data. Do not use negative numbers or zero, logger only handles positive
823     // integers.
824     private static final int COPY_ACCOUNT_SUCCEEDED = 1;
825     private static final int COPY_ACCOUNT_FAILED = 2;
826     private static final int COPY_ACCOUNT_TIMED_OUT = 3;
827     private static final int COPY_ACCOUNT_EXCEPTION = 4;
828 
829     @IntDef({
830             COPY_ACCOUNT_SUCCEEDED,
831             COPY_ACCOUNT_FAILED,
832             COPY_ACCOUNT_TIMED_OUT,
833             COPY_ACCOUNT_EXCEPTION})
834     private @interface CopyAccountStatus {}
835 
836     /**
837      * Mapping of {@link android.app.admin.DevicePolicyManager.ApplicationExemptionConstants} to
838      * corresponding app-ops.
839      */
840     private static final Map<Integer, String> APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS =
841             new ArrayMap<>();
842     static {
APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put( EXEMPT_FROM_SUSPENSION, OPSTR_SYSTEM_EXEMPT_FROM_SUSPENSION)843         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
844                 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)845         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
846                 EXEMPT_FROM_DISMISSIBLE_NOTIFICATIONS,
847                 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)848         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
849                 EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION,
850                 OPSTR_SYSTEM_EXEMPT_FROM_ACTIVITY_BG_START_RESTRICTION);
APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put( EXEMPT_FROM_HIBERNATION, OPSTR_SYSTEM_EXEMPT_FROM_HIBERNATION)851         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
852                 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)853         APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.put(
854                 EXEMPT_FROM_POWER_RESTRICTIONS, OPSTR_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS);
855     }
856 
857     /**
858      * Admin apps targeting Android S+ may not use
859      * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} to set password quality
860      * on the {@code DevicePolicyManager} instance obtained by calling
861      * {@link android.app.admin.DevicePolicyManager#getParentProfileInstance}.
862      * Instead, they should use
863      * {@link android.app.admin.DevicePolicyManager#setRequiredPasswordComplexity} to set
864      * coarse-grained password requirements device-wide.
865      */
866     @ChangeId
867     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S)
868     private static final long PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT = 165573442L;
869 
870     /**
871      * For Admin Apps targeting U+
872      * If {@link android.security.IKeyChainService#setGrant} is called with an alias with no
873      * existing key, throw IllegalArgumentException.
874      */
875     @ChangeId
876     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
877     private static final long THROW_EXCEPTION_WHEN_KEY_MISSING = 175101461L;
878 
879     private static final String CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG =
880             "The alias provided must be contained in the aliases specified in the credential "
881                     + "management app's authentication policy";
882     private static final String NOT_SYSTEM_CALLER_MSG = "Only the system can %s";
883 
884     private static final String PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG =
885             "enable_permission_based_access";
886     private static final boolean DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG = false;
887 
888     private static final int RETRY_COPY_ACCOUNT_ATTEMPTS = 3;
889 
890     /**
891      * For apps targeting U+
892      * Enable multiple admins to coexist on the same device.
893      */
894     @ChangeId
895     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
896     static final long ENABLE_COEXISTENCE_CHANGE = 260560985L;
897 
898     final Context mContext;
899     final Injector mInjector;
900     final PolicyPathProvider mPathProvider;
901     final IPackageManager mIPackageManager;
902     final IPermissionManager mIPermissionManager;
903     final UserManager mUserManager;
904     final UserManagerInternal mUserManagerInternal;
905     final UsageStatsManagerInternal mUsageStatsManagerInternal;
906     final TelephonyManager mTelephonyManager;
907     final RoleManager mRoleManager;
908     private final LockPatternUtils mLockPatternUtils;
909     private final LockSettingsInternal mLockSettingsInternal;
910     private final DeviceAdminServiceController mDeviceAdminServiceController;
911     private final OverlayPackagesProvider mOverlayPackagesProvider;
912 
913     private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl();
914     private final DeviceStateCacheImpl mStateCache = new DeviceStateCacheImpl();
915     private final Object mESIDInitilizationLock = new Object();
916     private EnterpriseSpecificIdCalculator mEsidCalculator;
917     private final Object mSubscriptionsChangedListenerLock = new Object();
918     @GuardedBy("mSubscriptionsChangedListenerLock")
919     private SubscriptionManager.OnSubscriptionsChangedListener mSubscriptionsChangedListener;
920 
921     /**
922      * Contains the list of OEM Default Role Holders for Contact-related roles
923      * (DIALER, SMS, SYSTEM_CONTACTS)
924      */
925     private final Set<String> mContactSystemRoleHolders;
926 
927     /**
928      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
929      * is requested for user u.
930      */
931     private final Set<UserPackage> mPackagesToRemove = new ArraySet<>();
932 
933     final LocalService mLocalService;
934 
935     // Stores and loads state on device and profile owners.
936     @VisibleForTesting
937     final Owners mOwners;
938 
939     private final Binder mToken = new Binder();
940 
941     /**
942      * Whether or not device admin feature is supported. If it isn't return defaults for all
943      * public methods, unless the caller has the appropriate permission for a particular method.
944      */
945     final boolean mHasFeature;
946 
947     /**
948      * Whether or not this device is a watch.
949      */
950     final boolean mIsWatch;
951 
952     /**
953      * Whether or not this device is an automotive.
954      */
955     private final boolean mIsAutomotive;
956 
957     /**
958      * Whether this device has the telephony feature.
959      */
960     final boolean mHasTelephonyFeature;
961 
962     private final CertificateMonitor mCertificateMonitor;
963     private final SecurityLogMonitor mSecurityLogMonitor;
964     private final RemoteBugreportManager mBugreportCollectionManager;
965 
966     @GuardedBy("getLockObject()")
967     private NetworkLogger mNetworkLogger;
968 
969     private final SetupContentObserver mSetupContentObserver;
970     private final DevicePolicyConstantsObserver mConstantsObserver;
971 
972     private DevicePolicyConstants mConstants;
973 
974     /**
975      * User to be switched to on {@code logoutUser()}.
976      *
977      * <p>Only used on devices with headless system user mode
978      */
979     @GuardedBy("getLockObject()")
980     private @UserIdInt int mLogoutUserId = UserHandle.USER_NULL;
981 
982     /**
983      * User the network logging notification was sent to.
984      */
985     // Guarded by mHandler
986     private @UserIdInt int mNetworkLoggingNotificationUserId = UserHandle.USER_NULL;
987 
988     private final DeviceManagementResourcesProvider mDeviceManagementResourcesProvider;
989     private final DevicePolicyManagementRoleObserver mDevicePolicyManagementRoleObserver;
990 
991     private final DevicePolicyEngine mDevicePolicyEngine;
992 
993     private static final boolean ENABLE_LOCK_GUARD = true;
994 
995     /**
996      * Profile off deadline is not set or more than MANAGED_PROFILE_OFF_WARNING_PERIOD away, or the
997      * user is running unlocked, no need for notification.
998      */
999     private static final int PROFILE_OFF_NOTIFICATION_NONE = 0;
1000     /**
1001      * Profile off deadline is closer than MANAGED_PROFILE_OFF_WARNING_PERIOD.
1002      */
1003     private static final int PROFILE_OFF_NOTIFICATION_WARNING = 1;
1004     /**
1005      * Profile off deadline reached, notify the user that personal apps blocked.
1006      */
1007     private static final int PROFILE_OFF_NOTIFICATION_SUSPENDED = 2;
1008 
1009     interface Stats {
1010         int LOCK_GUARD_GUARD = 0;
1011 
1012         int COUNT = LOCK_GUARD_GUARD + 1;
1013     }
1014 
1015     private final StatLogger mStatLogger = new StatLogger(new String[] {
1016             "LockGuard.guard()",
1017     });
1018 
1019     private final Object mLockDoNoUseDirectly = LockGuard.installNewLock(
1020             LockGuard.INDEX_DPMS, /* doWtf=*/ true);
1021 
getLockObject()1022     final Object getLockObject() {
1023         if (ENABLE_LOCK_GUARD) {
1024             final long start = mStatLogger.getTime();
1025             LockGuard.guard(LockGuard.INDEX_DPMS);
1026             mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start);
1027         }
1028         return mLockDoNoUseDirectly;
1029     }
1030 
1031     /**
1032      * Check if the current thread holds the DPMS lock, and if not, do a WTF.
1033      *
1034      * (Doing this check too much may be costly, so don't call it in a hot path.)
1035      */
ensureLocked()1036     final void ensureLocked() {
1037         if (Thread.holdsLock(mLockDoNoUseDirectly)) {
1038             return;
1039         }
1040         Slogf.wtfStack(LOG_TAG, "Not holding DPMS lock.");
1041     }
1042 
1043     /**
1044      * Calls wtfStack() if called with the DPMS lock held.
1045      */
wtfIfInLock()1046     private void wtfIfInLock() {
1047         if (Thread.holdsLock(mLockDoNoUseDirectly)) {
1048             Slogf.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
1049         }
1050     }
1051 
1052     @VisibleForTesting
1053     final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager;
1054 
1055     @Nullable
1056     private DevicePolicySafetyChecker mSafetyChecker;
1057 
1058     @GuardedBy("getLockObject()")
1059     private final ArrayList<Object> mPendingUserCreatedCallbackTokens = new ArrayList<>();
1060 
1061     public static final class Lifecycle extends SystemService {
1062         private DevicePolicyManagerService mService;
1063 
Lifecycle(Context context)1064         public Lifecycle(Context context) {
1065             super(context);
1066             String dpmsClassName = context.getResources()
1067                     .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
1068             if (TextUtils.isEmpty(dpmsClassName)) {
1069                 mService = new DevicePolicyManagerService(context);
1070             } else {
1071                 try {
1072                     Class<?> serviceClass = Class.forName(dpmsClassName);
1073                     Constructor<?> constructor = serviceClass.getConstructor(Context.class);
1074                     mService = (DevicePolicyManagerService) constructor.newInstance(context);
1075                 } catch (Exception e) {
1076                     throw new IllegalStateException(
1077                         "Failed to instantiate DevicePolicyManagerService with class name: "
1078                         + dpmsClassName, e);
1079                 }
1080             }
1081         }
1082 
1083         /** Sets the {@link DevicePolicySafetyChecker}. */
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1084         public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
1085             mService.setDevicePolicySafetyChecker(safetyChecker);
1086         }
1087 
1088         @Override
onStart()1089         public void onStart() {
1090             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
1091         }
1092 
1093         @Override
onBootPhase(int phase)1094         public void onBootPhase(int phase) {
1095             mService.systemReady(phase);
1096         }
1097 
1098         @Override
onUserStarting(@onNull TargetUser user)1099         public void onUserStarting(@NonNull TargetUser user) {
1100             if (user.isPreCreated()) return;
1101             mService.handleStartUser(user.getUserIdentifier());
1102         }
1103 
1104         @Override
onUserUnlocking(@onNull TargetUser user)1105         public void onUserUnlocking(@NonNull TargetUser user) {
1106             if (user.isPreCreated()) return;
1107             mService.handleUnlockUser(user.getUserIdentifier());
1108         }
1109 
1110         @Override
onUserStopping(@onNull TargetUser user)1111         public void onUserStopping(@NonNull TargetUser user) {
1112             if (user.isPreCreated()) return;
1113             mService.handleStopUser(user.getUserIdentifier());
1114         }
1115 
1116         @Override
onUserUnlocked(@onNull TargetUser user)1117         public void onUserUnlocked(@NonNull TargetUser user) {
1118             if (user.isPreCreated()) return;
1119             mService.handleOnUserUnlocked(user.getUserIdentifier());
1120         }
1121     }
1122 
1123     @GuardedBy("getLockObject()")
1124     final SparseArray<DevicePolicyData> mUserData;
1125 
1126     final Handler mHandler;
1127     final Handler mBackgroundHandler;
1128 
1129     /** Listens only if mHasFeature == true. */
1130     final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1131         @Override
1132         public void onReceive(Context context, Intent intent) {
1133             final String action = intent.getAction();
1134             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
1135                     getSendingUserId());
1136 
1137             /*
1138              * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
1139              * however it's too early in the boot process to register with IIpConnectivityMetrics
1140              * to listen for events.
1141              */
1142             if (Intent.ACTION_USER_STARTED.equals(action) && userHandle == UserHandle.USER_SYSTEM) {
1143                 synchronized (getLockObject()) {
1144                     if (isNetworkLoggingEnabledInternalLocked()) {
1145                         setNetworkLoggingActiveInternal(true);
1146                     }
1147                 }
1148             }
1149 
1150             if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
1151                 calculateHasIncompatibleAccounts();
1152             }
1153 
1154             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
1155                     && userHandle == mOwners.getDeviceOwnerUserId()) {
1156                 mBugreportCollectionManager.checkForPendingBugreportAfterBoot();
1157 
1158             }
1159             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
1160                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
1161                 if (VERBOSE_LOG) {
1162                     Slogf.v(LOG_TAG, "Sending password expiration notifications for action "
1163                             + action + " for user " + userHandle);
1164                 }
1165                 mHandler.post(new Runnable() {
1166                     @Override
1167                     public void run() {
1168                         handlePasswordExpirationNotification(userHandle);
1169                     }
1170                 });
1171             }
1172 
1173             if (Intent.ACTION_USER_ADDED.equals(action)) {
1174                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
1175                 synchronized (getLockObject()) {
1176                     // It might take a while for the user to become affiliated. Make security
1177                     // and network logging unavailable in the meantime.
1178                     maybePauseDeviceWideLoggingLocked();
1179                 }
1180             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
1181                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
1182                 synchronized (getLockObject()) {
1183                     // Check whether the user is affiliated, *before* removing its data.
1184                     boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
1185                     removeUserData(userHandle);
1186                     if (!isRemovedUserAffiliated) {
1187                         // We discard the logs when unaffiliated users are deleted (so that the
1188                         // device owner cannot retrieve data about that user after it's gone).
1189                         discardDeviceWideLogsLocked();
1190                         // Resume logging if all remaining users are affiliated.
1191                         maybeResumeDeviceWideLoggingLocked();
1192                     }
1193                 }
1194                 mDevicePolicyEngine.handleUserRemoved(userHandle);
1195             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
1196                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle);
1197                 synchronized (getLockObject()) {
1198                     maybeSendAdminEnabledBroadcastLocked(userHandle);
1199                     // Reset the policy data
1200                     mUserData.remove(userHandle);
1201                 }
1202                 handlePackagesChanged(null /* check all admins */, userHandle);
1203                 updatePersonalAppsSuspensionOnUserStart(userHandle);
1204             } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
1205                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle);
1206                 if (isManagedProfile(userHandle)) {
1207                     Slogf.d(LOG_TAG, "Managed profile was stopped");
1208                     updatePersonalAppsSuspension(userHandle);
1209                 }
1210             } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
1211                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle);
1212             } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
1213                 synchronized (getLockObject()) {
1214                     maybeSendAdminEnabledBroadcastLocked(userHandle);
1215                 }
1216                 if (isManagedProfile(userHandle)) {
1217                     Slogf.d(LOG_TAG, "Managed profile became unlocked");
1218                     final boolean suspended = updatePersonalAppsSuspension(userHandle);
1219                     triggerPolicyComplianceCheckIfNeeded(userHandle, suspended);
1220                 }
1221             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
1222                 handlePackagesChanged(null /* check all admins */, userHandle);
1223             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1224                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
1225             } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
1226                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1227                     handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
1228                 } else {
1229                     handleNewPackageInstalled(intent.getData().getSchemeSpecificPart(), userHandle);
1230                 }
1231             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
1232                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1233                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
1234                 removeCredentialManagementApp(intent.getData().getSchemeSpecificPart());
1235             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
1236                 clearWipeProfileNotification();
1237             } else if (Intent.ACTION_DATE_CHANGED.equals(action)
1238                     || Intent.ACTION_TIME_CHANGED.equals(action)) {
1239                 // Update freeze period record when clock naturally progresses to the next day
1240                 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made
1241                 // (ACTION_TIME_CHANGED)
1242                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
1243                 final int userId = getManagedUserId(getMainUserId());
1244                 if (userId >= 0) {
1245                     updatePersonalAppsSuspension(userId);
1246                 }
1247             } else if (ACTION_PROFILE_OFF_DEADLINE.equals(action)) {
1248                 Slogf.i(LOG_TAG, "Profile off deadline alarm was triggered");
1249                 final int userId = getManagedUserId(getMainUserId());
1250                 if (userId >= 0) {
1251                     updatePersonalAppsSuspension(userId);
1252                 } else {
1253                     Slogf.wtf(LOG_TAG, "Got deadline alarm for nonexistent profile");
1254                 }
1255             } else if (ACTION_TURN_PROFILE_ON_NOTIFICATION.equals(action)) {
1256                 Slogf.i(LOG_TAG, "requesting to turn on the profile: " + userHandle);
1257                 mUserManager.requestQuietModeEnabled(false, UserHandle.of(userHandle));
1258             } else if (ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action)) {
1259                 notifyIfManagedSubscriptionsAreUnavailable(
1260                         UserHandle.of(userHandle), /* managedProfileAvailable= */ false);
1261                 updatePersonalAppsSuspension(userHandle);
1262             } else if (ACTION_MANAGED_PROFILE_AVAILABLE.equals(action)) {
1263                 notifyIfManagedSubscriptionsAreUnavailable(
1264                         UserHandle.of(userHandle), /* managedProfileAvailable= */ true);
1265                 final boolean suspended = updatePersonalAppsSuspension(userHandle);
1266                 triggerPolicyComplianceCheckIfNeeded(userHandle, suspended);
1267             } else if (LOGIN_ACCOUNTS_CHANGED_ACTION.equals(action)) {
1268                 calculateHasIncompatibleAccounts();
1269             }
1270         }
1271 
1272         private void sendDeviceOwnerUserCommand(String action, int userHandle) {
1273             synchronized (getLockObject()) {
1274                 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
1275                 if (deviceOwner != null) {
1276                     Bundle extras = new Bundle();
1277                     extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
1278                     sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null,
1279                             /* inForeground */ true);
1280                 }
1281             }
1282         }
1283     };
1284 
1285     protected static class RestrictionsListener implements UserRestrictionsListener {
1286         private final Context mContext;
1287         private final UserManagerInternal mUserManagerInternal;
1288         private final DevicePolicyManagerService mDpms;
1289 
RestrictionsListener( Context context, UserManagerInternal userManagerInternal, DevicePolicyManagerService dpms)1290         public RestrictionsListener(
1291                 Context context,
1292                 UserManagerInternal userManagerInternal,
1293                 DevicePolicyManagerService dpms) {
1294             mContext = context;
1295             mUserManagerInternal = userManagerInternal;
1296             mDpms = dpms;
1297         }
1298 
1299         @Override
onUserRestrictionsChanged(int userId, Bundle newRestrictions, Bundle prevRestrictions)1300         public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
1301                 Bundle prevRestrictions) {
1302             resetCrossProfileIntentFiltersIfNeeded(userId, newRestrictions, prevRestrictions);
1303             resetUserVpnIfNeeded(userId, newRestrictions, prevRestrictions);
1304             if (Flags.deletePrivateSpaceUnderRestriction()) {
1305                 removePrivateSpaceIfRestrictionIsSet(userId, newRestrictions, prevRestrictions);
1306             }
1307         }
1308 
resetUserVpnIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1309         private void resetUserVpnIfNeeded(
1310                 int userId, Bundle newRestrictions, Bundle prevRestrictions) {
1311             final boolean newlyEnforced =
1312                     !prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN)
1313                     && newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN);
1314             if (newlyEnforced) {
1315                 mDpms.clearUserConfiguredVpns(userId);
1316             }
1317         }
1318 
resetCrossProfileIntentFiltersIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1319         private void resetCrossProfileIntentFiltersIfNeeded(
1320                 int userId, Bundle newRestrictions, Bundle prevRestrictions) {
1321             if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions,
1322                     UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE)) {
1323                 final int parentId = mUserManagerInternal.getProfileParentId(userId);
1324                 if (parentId == userId) {
1325                     return;
1326                 }
1327 
1328                 // Always reset filters on the parent user, which handles cross profile intent
1329                 // filters between the parent and its profiles.
1330                 Slogf.i(LOG_TAG, "Resetting cross-profile intent filters on restriction "
1331                         + "change");
1332                 mDpms.resetDefaultCrossProfileIntentFilters(parentId);
1333                 mContext.sendBroadcastAsUser(
1334                         new Intent(DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_APPLIED),
1335                         UserHandle.of(userId));
1336             }
1337         }
removePrivateSpaceIfRestrictionIsSet( int userId, Bundle newRestrictions, Bundle prevRestrictions)1338         private void removePrivateSpaceIfRestrictionIsSet(
1339                 int userId, Bundle newRestrictions, Bundle prevRestrictions) {
1340             final boolean newlyEnforced =
1341                     !prevRestrictions.getBoolean(UserManager.DISALLOW_ADD_PRIVATE_PROFILE)
1342                             && newRestrictions.getBoolean(UserManager.DISALLOW_ADD_PRIVATE_PROFILE);
1343             if (!newlyEnforced) {
1344                 return;
1345             }
1346             mDpms.removePrivateSpaceWithinUserGroupIfExists(userId);
1347         }
1348 
1349     }
1350 
clearUserConfiguredVpns(int userId)1351     private void clearUserConfiguredVpns(int userId) {
1352         final String adminConfiguredVpnPkg;
1353         synchronized (getLockObject()) {
1354             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
1355             if (owner == null) {
1356                 Slogf.wtf(LOG_TAG, "Admin not found");
1357                 return;
1358             }
1359             adminConfiguredVpnPkg = owner.mAlwaysOnVpnPackage;
1360         }
1361 
1362         // Clear always-on configuration if it wasn't set by the admin.
1363         if (adminConfiguredVpnPkg == null) {
1364             mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(userId, null, false, null);
1365         }
1366 
1367         // Clear app authorizations to establish VPNs. When DISALLOW_CONFIG_VPN is enforced apps
1368         // won't be able to get those authorizations unless it is configured by an admin.
1369         final List<AppOpsManager.PackageOps> allVpnOps = mInjector.getAppOpsManager()
1370                 .getPackagesForOps(new int[] {AppOpsManager.OP_ACTIVATE_VPN});
1371         if (allVpnOps == null) {
1372             return;
1373         }
1374         for (AppOpsManager.PackageOps pkgOps : allVpnOps) {
1375             if (UserHandle.getUserId(pkgOps.getUid()) != userId
1376                     || pkgOps.getPackageName().equals(adminConfiguredVpnPkg)) {
1377                 continue;
1378             }
1379             if (pkgOps.getOps().size() != 1) {
1380                 Slogf.wtf(LOG_TAG, "Unexpected number of ops returned");
1381                 continue;
1382             }
1383             final @Mode int mode = pkgOps.getOps().get(0).getMode();
1384             if (mode == MODE_ALLOWED) {
1385                 Slogf.i(LOG_TAG, String.format("Revoking VPN authorization for package %s uid %d",
1386                         pkgOps.getPackageName(), pkgOps.getUid()));
1387                 mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN, pkgOps.getUid(),
1388                         pkgOps.getPackageName(), MODE_DEFAULT);
1389             }
1390         }
1391     }
1392 
1393     /**
1394      * Given a parent userId, try removing all private space profiles with its profile group, and
1395      * post a notification if at least one private space profile is removed.
1396      */
removePrivateSpaceWithinUserGroupIfExists(int userId)1397     private void removePrivateSpaceWithinUserGroupIfExists(int userId) {
1398         boolean removed = false;
1399         if (mUserManager.isProfile(userId)) return;
1400         for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
1401             if (profileId == userId) continue;
1402             if (mUserManager.getUserInfo(profileId).isPrivateProfile()) {
1403                 Slogf.i(LOG_TAG, "Removing private space %d due to DISALLOW_ADD_PRIVATE_PROFILE",
1404                         profileId);
1405                 removed |= mUserManager.removeUserEvenWhenDisallowed(profileId);
1406             }
1407         }
1408         if (removed) {
1409             mHandler.post(() -> sendPrivateSpaceRemovedNotification(userId));
1410         }
1411     }
1412 
sendPrivateSpaceRemovedNotification(int parentUserId)1413     private void sendPrivateSpaceRemovedNotification(int parentUserId) {
1414         String notification_details = mContext.getString(
1415                 R.string.private_space_deleted_by_admin_details);
1416         Notification notification =
1417                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
1418                         .setSmallIcon(android.R.drawable.stat_sys_warning)
1419                         .setContentTitle(mContext.getString(
1420                                 R.string.private_space_deleted_by_admin))
1421                         .setContentText(notification_details)
1422                         .setColor(mContext.getColor(R.color.system_notification_accent_color))
1423                         .setStyle(new Notification.BigTextStyle().bigText(notification_details))
1424                         .build();
1425         mInjector.getNotificationManager().notifyAsUser(/* tag= */ null,
1426                 SystemMessage.NOTE_PROFILE_WIPED, notification, UserHandle.of(parentUserId));
1427     }
1428 
1429     private final class UserLifecycleListener implements UserManagerInternal.UserLifecycleListener {
1430 
1431         @Override
onUserCreated(UserInfo user, Object token)1432         public void onUserCreated(UserInfo user, Object token) {
1433             mHandler.post(() -> handleNewUserCreated(user, token));
1434         }
1435     }
1436 
handlePackagesChanged(@ullable String packageName, int userHandle)1437     private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1438         boolean removedAdmin = false;
1439         String removedAdminPackage = null;
1440         if (VERBOSE_LOG) {
1441             Slogf.d(LOG_TAG, "Handling package changes package " + packageName
1442                     + " for user " + userHandle);
1443         }
1444         DevicePolicyData policy = getUserData(userHandle);
1445         synchronized (getLockObject()) {
1446             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1447                 ActiveAdmin aa = policy.mAdminList.get(i);
1448                 try {
1449                     // If we're checking all packages or if the specific one we're checking matches,
1450                     // then check if the package and receiver still exist.
1451                     final String adminPackage = aa.info.getPackageName();
1452                     if (packageName == null || packageName.equals(adminPackage)) {
1453                         if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1454                                 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1455                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
1456                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1457                                 userHandle) == null) {
1458                             Slogf.e(LOG_TAG, String.format(
1459                                     "Admin package %s not found for user %d, removing active admin",
1460                                     packageName, userHandle));
1461                             removedAdmin = true;
1462                             removedAdminPackage = adminPackage;
1463                             policy.mAdminList.remove(i);
1464                             policy.mAdminMap.remove(aa.info.getComponent());
1465                             pushActiveAdminPackagesLocked(userHandle);
1466                         }
1467                     }
1468                 } catch (RemoteException re) {
1469                     // Shouldn't happen.
1470                     Slogf.wtf(LOG_TAG, "Error handling package changes", re);
1471                 }
1472             }
1473             if (removedAdmin) {
1474                 policy.validatePasswordOwner();
1475             }
1476 
1477             boolean removedDelegate = false;
1478 
1479             // Check if a delegate was removed.
1480             for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1481                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
1482                 if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1483                     policy.mDelegationMap.removeAt(i);
1484                     removedDelegate = true;
1485                 }
1486             }
1487 
1488             // If it's an owner package, we may need to refresh the bound connection.
1489             final ComponentName owner = getOwnerComponent(userHandle);
1490             if ((packageName != null) && (owner != null)
1491                     && (owner.getPackageName().equals(packageName))) {
1492                 startOwnerService(userHandle, "package-broadcast");
1493             }
1494             mDevicePolicyEngine.handlePackageChanged(packageName, userHandle, removedAdminPackage);
1495             // Persist updates if the removed package was an admin or delegate.
1496             if (removedAdmin || removedDelegate) {
1497                 saveSettingsLocked(policy.mUserId);
1498             }
1499         }
1500         if (removedAdmin) {
1501             // The removed admin might have disabled camera, so update user restrictions.
1502             pushMeteredDisabledPackages(userHandle);
1503         }
1504     }
1505 
removeCredentialManagementApp(String packageName)1506     private void removeCredentialManagementApp(String packageName) {
1507         mBackgroundHandler.post(() -> {
1508             try (KeyChainConnection connection = mInjector.keyChainBind()) {
1509                 IKeyChainService service = connection.getService();
1510                 if (service.hasCredentialManagementApp()
1511                         && packageName.equals(service.getCredentialManagementAppPackageName())) {
1512                     service.removeCredentialManagementApp();
1513                 }
1514             } catch (RemoteException | InterruptedException | IllegalStateException
1515                     | AssertionError e) {
1516                 Slogf.e(LOG_TAG, "Unable to remove the credential management app", e);
1517             }
1518         });
1519     }
1520 
isRemovedPackage(String changedPackage, String targetPackage, int userHandle)1521     private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1522         try {
1523             return targetPackage != null
1524                     && (changedPackage == null || changedPackage.equals(targetPackage))
1525                     && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1526         } catch (RemoteException e) {
1527             // Shouldn't happen
1528             Slogf.wtf(LOG_TAG, "Error checking isRemovedPackage", e);
1529         }
1530 
1531         return false;
1532     }
1533 
handleNewPackageInstalled(String packageName, int userHandle)1534     private void handleNewPackageInstalled(String packageName, int userHandle) {
1535         // If personal apps were suspended by the admin, suspend the newly installed one.
1536         if (!getUserData(userHandle).mAppsSuspended) {
1537             return;
1538         }
1539         final String[] packagesToSuspend = { packageName };
1540         // Check if package is considered not suspendable?
1541         if (mInjector.getPackageManager(userHandle)
1542                 .getUnsuspendablePackages(packagesToSuspend).length != 0) {
1543             Slogf.i(LOG_TAG, "Newly installed package is unsuspendable: " + packageName);
1544             return;
1545         }
1546         mInjector.getPackageManagerInternal()
1547                 .setPackagesSuspendedByAdmin(userHandle, packagesToSuspend, true /*suspend*/);
1548     }
1549 
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1550     public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
1551         CallerIdentity callerIdentity = getCallerIdentity();
1552         Preconditions.checkCallAuthorization(mIsAutomotive || isAdb(callerIdentity), "can only set "
1553                 + "DevicePolicySafetyChecker on automotive builds or from ADB (but caller is %s)",
1554                 callerIdentity);
1555         setDevicePolicySafetyCheckerUnchecked(safetyChecker);
1556     }
1557 
1558     /**
1559      * Used by {@code setDevicePolicySafetyChecker()} above and {@link OneTimeSafetyChecker}.
1560      */
setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker)1561     void setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker) {
1562         Slogf.i(LOG_TAG, "Setting DevicePolicySafetyChecker as %s", safetyChecker);
1563         mSafetyChecker = safetyChecker;
1564         mInjector.setDevicePolicySafetyChecker(safetyChecker);
1565     }
1566 
1567     /**
1568      * Used by {@link OneTimeSafetyChecker} only.
1569      */
getDevicePolicySafetyChecker()1570     DevicePolicySafetyChecker getDevicePolicySafetyChecker() {
1571         return mSafetyChecker;
1572     }
1573 
1574     /**
1575      * Checks if it's safe to execute the given {@code operation}.
1576      *
1577      * @throws UnsafeStateException if it's not safe to execute the operation.
1578      */
checkCanExecuteOrThrowUnsafe(@evicePolicyOperation int operation)1579     private void checkCanExecuteOrThrowUnsafe(@DevicePolicyOperation int operation) {
1580         int reason = getUnsafeOperationReason(operation);
1581         if (reason == OPERATION_SAFETY_REASON_NONE) return;
1582 
1583         if (mSafetyChecker == null) {
1584             // Happens on CTS after it's set just once (by OneTimeSafetyChecker)
1585             throw new UnsafeStateException(operation, reason);
1586         }
1587         // Let mSafetyChecker customize it (for example, by explaining how to retry)
1588         throw mSafetyChecker.newUnsafeStateException(operation, reason);
1589     }
1590 
1591     /**
1592      * Returns whether it's safe to execute the given {@code operation}, and why.
1593      */
1594     @OperationSafetyReason
getUnsafeOperationReason(@evicePolicyOperation int operation)1595     int getUnsafeOperationReason(@DevicePolicyOperation int operation) {
1596         return mSafetyChecker == null ? OPERATION_SAFETY_REASON_NONE
1597                 : mSafetyChecker.getUnsafeOperationReason(operation);
1598     }
1599 
1600     @Override
setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)1601     public void setNextOperationSafety(@DevicePolicyOperation int operation,
1602             @OperationSafetyReason int reason) {
1603         Preconditions.checkCallAuthorization(
1604                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
1605         Slogf.i(LOG_TAG, "setNextOperationSafety(%s, %s)",
1606                 DevicePolicyManager.operationToString(operation),
1607                 DevicePolicyManager.operationSafetyReasonToString(reason));
1608         mSafetyChecker = new OneTimeSafetyChecker(this, operation, reason);
1609     }
1610 
1611     @Override
isSafeOperation(@perationSafetyReason int reason)1612     public boolean isSafeOperation(@OperationSafetyReason int reason) {
1613         if (VERBOSE_LOG) {
1614             Slogf.v(LOG_TAG, "checking isSafeOperation(%s) using mSafetyChecker %s",
1615                     DevicePolicyManager.operationSafetyReasonToString(reason), mSafetyChecker);
1616         }
1617         return mSafetyChecker == null ? true : mSafetyChecker.isSafeOperation(reason);
1618     }
1619 
1620     // Used by DevicePolicyManagerServiceShellCommand
listAllOwners()1621     List<OwnerShellData> listAllOwners() {
1622         Preconditions.checkCallAuthorization(
1623                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
1624         return mInjector.binderWithCleanCallingIdentity(() -> {
1625             SparseArray<DevicePolicyData> userData;
1626 
1627             // Gets the owners of "full users" first (device owner and profile owners)
1628             List<OwnerShellData> owners = mOwners.listAllOwners();
1629             synchronized (getLockObject()) {
1630                 for (int i = 0; i < owners.size(); i++) {
1631                     OwnerShellData owner = owners.get(i);
1632                     owner.isAffiliated = isUserAffiliatedWithDeviceLocked(owner.userId);
1633                 }
1634                 userData = mUserData;
1635             }
1636 
1637             // Then the owners of profile users (managed profiles)
1638             for (int i = 0; i < userData.size(); i++) {
1639                 DevicePolicyData policyData = mUserData.valueAt(i);
1640                 int userId = userData.keyAt(i);
1641                 int parentUserId = mUserManagerInternal.getProfileParentId(userId);
1642                 boolean isProfile = parentUserId != userId;
1643                 if (!isProfile) continue;
1644                 for (int j = 0; j < policyData.mAdminList.size(); j++) {
1645                     ActiveAdmin admin = policyData.mAdminList.get(j);
1646                     OwnerShellData owner = OwnerShellData.forManagedProfileOwner(userId,
1647                             parentUserId, admin.info.getComponent());
1648                     owners.add(owner);
1649                 }
1650             }
1651 
1652             return owners;
1653         });
1654     }
1655 
1656     /**
1657      * Unit test will subclass it to inject mocks.
1658      */
1659     @VisibleForTesting
1660     static class Injector {
1661 
1662         public final Context mContext;
1663 
1664         @Nullable private DevicePolicySafetyChecker mSafetyChecker;
1665 
Injector(Context context)1666         Injector(Context context) {
1667             mContext = context;
1668         }
1669 
hasFeature()1670         public boolean hasFeature() {
1671             return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1672         }
1673 
createContextAsUser(UserHandle user)1674         Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1675             final String packageName = mContext.getPackageName();
1676             return mContext.createPackageContextAsUser(packageName, 0, user);
1677         }
1678 
getResources()1679         Resources getResources() {
1680             return mContext.getResources();
1681         }
1682 
getUserManager()1683         UserManager getUserManager() {
1684             return UserManager.get(mContext);
1685         }
1686 
getUserManagerInternal()1687         UserManagerInternal getUserManagerInternal() {
1688             return LocalServices.getService(UserManagerInternal.class);
1689         }
1690 
getPackageManagerInternal()1691         PackageManagerInternal getPackageManagerInternal() {
1692             return LocalServices.getService(PackageManagerInternal.class);
1693         }
1694 
getPackageManagerLocal()1695         PackageManagerLocal getPackageManagerLocal() {
1696             return LocalManagerRegistry.getManager(PackageManagerLocal.class);
1697         }
1698 
getActivityTaskManagerInternal()1699         ActivityTaskManagerInternal getActivityTaskManagerInternal() {
1700             return LocalServices.getService(ActivityTaskManagerInternal.class);
1701         }
1702 
getPermissionControllerManager( @onNull UserHandle user)1703         @NonNull PermissionControllerManager getPermissionControllerManager(
1704                 @NonNull UserHandle user) {
1705             if (user.equals(mContext.getUser())) {
1706                 return mContext.getSystemService(PermissionControllerManager.class);
1707             } else {
1708                 try {
1709                     return mContext.createPackageContextAsUser(mContext.getPackageName(), 0,
1710                             user).getSystemService(PermissionControllerManager.class);
1711                 } catch (NameNotFoundException notPossible) {
1712                     // not possible
1713                     throw new IllegalStateException(notPossible);
1714                 }
1715             }
1716         }
1717 
getUsageStatsManagerInternal()1718         UsageStatsManagerInternal getUsageStatsManagerInternal() {
1719             return LocalServices.getService(UsageStatsManagerInternal.class);
1720         }
1721 
getNetworkPolicyManagerInternal()1722         NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() {
1723             return LocalServices.getService(NetworkPolicyManagerInternal.class);
1724         }
1725 
getNotificationManager()1726         NotificationManager getNotificationManager() {
1727             return mContext.getSystemService(NotificationManager.class);
1728         }
1729 
getIIpConnectivityMetrics()1730         IIpConnectivityMetrics getIIpConnectivityMetrics() {
1731             return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1732                 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1733         }
1734 
getPackageManager()1735         PackageManager getPackageManager() {
1736             return mContext.getPackageManager();
1737         }
1738 
getPackageManager(int userId)1739         PackageManager getPackageManager(int userId) {
1740             try {
1741                 return createContextAsUser(UserHandle.of(userId)).getPackageManager();
1742             } catch (NameNotFoundException e) {
1743                 throw new IllegalStateException(e);
1744             }
1745         }
1746 
getPowerManagerInternal()1747         PowerManagerInternal getPowerManagerInternal() {
1748             return LocalServices.getService(PowerManagerInternal.class);
1749         }
1750 
getTelephonyManager()1751         TelephonyManager getTelephonyManager() {
1752             return mContext.getSystemService(TelephonyManager.class);
1753         }
1754 
getRoleManager()1755         RoleManager getRoleManager() {
1756             return mContext.getSystemService(RoleManager.class);
1757         }
1758 
getTrustManager()1759         TrustManager getTrustManager() {
1760             return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1761         }
1762 
getAlarmManager()1763         AlarmManager getAlarmManager() {
1764             return mContext.getSystemService(AlarmManager.class);
1765         }
1766 
getAlarmManagerInternal()1767         AlarmManagerInternal getAlarmManagerInternal() {
1768             return LocalServices.getService(AlarmManagerInternal.class);
1769         }
1770 
getConnectivityManager()1771         ConnectivityManager getConnectivityManager() {
1772             return mContext.getSystemService(ConnectivityManager.class);
1773         }
1774 
getVpnManager()1775         VpnManager getVpnManager() {
1776             return mContext.getSystemService(VpnManager.class);
1777         }
1778 
getLocationManager()1779         LocationManager getLocationManager() {
1780             return mContext.getSystemService(LocationManager.class);
1781         }
1782 
getIWindowManager()1783         IWindowManager getIWindowManager() {
1784             return IWindowManager.Stub
1785                     .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1786         }
1787 
getIActivityManager()1788         IActivityManager getIActivityManager() {
1789             return ActivityManager.getService();
1790         }
1791 
getIActivityTaskManager()1792         IActivityTaskManager getIActivityTaskManager() {
1793             return ActivityTaskManager.getService();
1794         }
1795 
getActivityManagerInternal()1796         ActivityManagerInternal getActivityManagerInternal() {
1797             return LocalServices.getService(ActivityManagerInternal.class);
1798         }
1799 
getIPackageManager()1800         IPackageManager getIPackageManager() {
1801             return AppGlobals.getPackageManager();
1802         }
1803 
getIPermissionManager()1804         IPermissionManager getIPermissionManager() {
1805             return AppGlobals.getPermissionManager();
1806         }
1807 
getIBackupManager()1808         IBackupManager getIBackupManager() {
1809             return IBackupManager.Stub.asInterface(
1810                     ServiceManager.getService(Context.BACKUP_SERVICE));
1811         }
1812 
getPersistentDataBlockManagerInternal()1813         PersistentDataBlockManagerInternal getPersistentDataBlockManagerInternal() {
1814             return LocalServices.getService(PersistentDataBlockManagerInternal.class);
1815         }
1816 
getAppOpsManager()1817         AppOpsManager getAppOpsManager() {
1818             return mContext.getSystemService(AppOpsManager.class);
1819         }
1820 
getLockSettingsInternal()1821         LockSettingsInternal getLockSettingsInternal() {
1822             return LocalServices.getService(LockSettingsInternal.class);
1823         }
1824 
getCrossProfileApps(@serIdInt int userId)1825         CrossProfileApps getCrossProfileApps(@UserIdInt int userId) {
1826             return mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0)
1827                     .getSystemService(CrossProfileApps.class);
1828         }
1829 
hasUserSetupCompleted(DevicePolicyData userData)1830         boolean hasUserSetupCompleted(DevicePolicyData userData) {
1831             return userData.mUserSetupComplete;
1832         }
1833 
isBuildDebuggable()1834         boolean isBuildDebuggable() {
1835             return Build.IS_DEBUGGABLE;
1836         }
1837 
newLockPatternUtils()1838         LockPatternUtils newLockPatternUtils() {
1839             return new LockPatternUtils(mContext);
1840         }
1841 
newEnterpriseSpecificIdCalculator()1842         EnterpriseSpecificIdCalculator newEnterpriseSpecificIdCalculator() {
1843             return new EnterpriseSpecificIdCalculator(mContext);
1844         }
1845 
storageManagerIsFileBasedEncryptionEnabled()1846         boolean storageManagerIsFileBasedEncryptionEnabled() {
1847             return StorageManager.isFileEncrypted();
1848         }
1849 
getMyLooper()1850         Looper getMyLooper() {
1851             return Looper.myLooper();
1852         }
1853 
getWifiManager()1854         WifiManager getWifiManager() {
1855             return mContext.getSystemService(WifiManager.class);
1856         }
1857 
getUsbManager()1858         UsbManager getUsbManager() {
1859             return mContext.getSystemService(UsbManager.class);
1860         }
1861 
1862         @SuppressWarnings("ResultOfClearIdentityCallNotStoredInVariable")
binderClearCallingIdentity()1863         long binderClearCallingIdentity() {
1864             return Binder.clearCallingIdentity();
1865         }
1866 
binderRestoreCallingIdentity(long token)1867         void binderRestoreCallingIdentity(long token) {
1868             Binder.restoreCallingIdentity(token);
1869         }
1870 
binderGetCallingUid()1871         int binderGetCallingUid() {
1872             return Binder.getCallingUid();
1873         }
1874 
binderGetCallingPid()1875         int binderGetCallingPid() {
1876             return Binder.getCallingPid();
1877         }
1878 
binderGetCallingUserHandle()1879         UserHandle binderGetCallingUserHandle() {
1880             return Binder.getCallingUserHandle();
1881         }
1882 
binderIsCallingUidMyUid()1883         boolean binderIsCallingUidMyUid() {
1884             return getCallingUid() == Process.myUid();
1885         }
1886 
binderWithCleanCallingIdentity(@onNull ThrowingRunnable action)1887         void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
1888              Binder.withCleanCallingIdentity(action);
1889         }
1890 
binderWithCleanCallingIdentity(@onNull ThrowingSupplier<T> action)1891         final <T> T binderWithCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
1892             return Binder.withCleanCallingIdentity(action);
1893         }
1894 
userHandleGetCallingUserId()1895         final int userHandleGetCallingUserId() {
1896             return UserHandle.getUserId(binderGetCallingUid());
1897         }
1898 
powerManagerGoToSleep(long time, int reason, int flags)1899         void powerManagerGoToSleep(long time, int reason, int flags) {
1900             mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1901         }
1902 
powerManagerReboot(String reason)1903         void powerManagerReboot(String reason) {
1904             mContext.getSystemService(PowerManager.class).reboot(reason);
1905         }
1906 
recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)1907         boolean recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1908                 boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)
1909                         throws IOException {
1910             return FactoryResetter.newBuilder(mContext).setSafetyChecker(mSafetyChecker)
1911                     .setReason(reason).setShutdown(shutdown).setForce(force).setWipeEuicc(wipeEuicc)
1912                     .setWipeAdoptableStorage(wipeExtRequested)
1913                     .setWipeFactoryResetProtection(wipeResetProtectionData)
1914                     .build().factoryReset();
1915         }
1916 
systemPropertiesGetBoolean(String key, boolean def)1917         boolean systemPropertiesGetBoolean(String key, boolean def) {
1918             return SystemProperties.getBoolean(key, def);
1919         }
1920 
systemPropertiesGetLong(String key, long def)1921         long systemPropertiesGetLong(String key, long def) {
1922             return SystemProperties.getLong(key, def);
1923         }
1924 
systemPropertiesGet(String key, String def)1925         String systemPropertiesGet(String key, String def) {
1926             return SystemProperties.get(key, def);
1927         }
1928 
systemPropertiesGet(String key)1929         String systemPropertiesGet(String key) {
1930             return SystemProperties.get(key);
1931         }
1932 
systemPropertiesSet(String key, String value)1933         void systemPropertiesSet(String key, String value) {
1934             SystemProperties.set(key, value);
1935         }
1936 
userManagerIsHeadlessSystemUserMode()1937         boolean userManagerIsHeadlessSystemUserMode() {
1938             return UserManager.isHeadlessSystemUserMode();
1939         }
1940 
1941         @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
pendingIntentGetActivityAsUser(Context context, int requestCode, @NonNull Intent intent, int flags, Bundle options, UserHandle user)1942         PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1943                 @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
1944             return PendingIntent.getActivityAsUser(
1945                     context, requestCode, intent, flags, options, user);
1946         }
1947 
1948         @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
pendingIntentGetBroadcast( Context context, int requestCode, Intent intent, int flags)1949         PendingIntent pendingIntentGetBroadcast(
1950                 Context context, int requestCode, Intent intent, int flags) {
1951             return PendingIntent.getBroadcast(context, requestCode, intent, flags);
1952         }
1953 
registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer, int userHandle)1954         void registerContentObserver(Uri uri, boolean notifyForDescendents,
1955                 ContentObserver observer, int userHandle) {
1956             mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1957                     observer, userHandle);
1958         }
1959 
settingsSecureGetIntForUser(String name, int def, int userHandle)1960         int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1961             return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1962                     name, def, userHandle);
1963         }
1964 
settingsSecureGetStringForUser(String name, int userHandle)1965         String settingsSecureGetStringForUser(String name, int userHandle) {
1966             return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
1967                     userHandle);
1968         }
1969 
settingsSecurePutIntForUser(String name, int value, int userHandle)1970         void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1971             Settings.Secure.putIntForUser(mContext.getContentResolver(),
1972                     name, value, userHandle);
1973         }
1974 
settingsSecurePutStringForUser(String name, String value, int userHandle)1975         void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1976             Settings.Secure.putStringForUser(mContext.getContentResolver(),
1977                     name, value, userHandle);
1978         }
1979 
settingsGlobalPutStringForUser(String name, String value, int userHandle)1980         void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1981             Settings.Global.putStringForUser(mContext.getContentResolver(),
1982                     name, value, userHandle);
1983         }
1984 
settingsGlobalGetInt(String name, int def)1985         int settingsGlobalGetInt(String name, int def) {
1986             return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1987         }
1988 
1989         @Nullable
settingsGlobalGetString(String name)1990         String settingsGlobalGetString(String name) {
1991             return Settings.Global.getString(mContext.getContentResolver(), name);
1992         }
1993 
settingsGlobalPutInt(String name, int value)1994         void settingsGlobalPutInt(String name, int value) {
1995             Settings.Global.putInt(mContext.getContentResolver(), name, value);
1996         }
1997 
settingsGlobalPutString(String name, String value)1998         void settingsGlobalPutString(String name, String value) {
1999             Settings.Global.putString(mContext.getContentResolver(), name, value);
2000         }
2001 
settingsSystemPutStringForUser(String name, String value, int userId)2002         void settingsSystemPutStringForUser(String name, String value, int userId) {
2003           Settings.System.putStringForUser(
2004               mContext.getContentResolver(), name, value, userId);
2005         }
2006 
securityLogSetLoggingEnabledProperty(boolean enabled)2007         void securityLogSetLoggingEnabledProperty(boolean enabled) {
2008             SecurityLog.setLoggingEnabledProperty(enabled);
2009         }
2010 
securityLogGetLoggingEnabledProperty()2011         boolean securityLogGetLoggingEnabledProperty() {
2012             return SecurityLog.getLoggingEnabledProperty();
2013         }
2014 
securityLogIsLoggingEnabled()2015         boolean securityLogIsLoggingEnabled() {
2016             return SecurityLog.isLoggingEnabled();
2017         }
2018 
keyChainBind()2019         KeyChainConnection keyChainBind() throws InterruptedException {
2020             return KeyChain.bind(mContext);
2021         }
2022 
keyChainBindAsUser(UserHandle user)2023         KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
2024             return KeyChain.bindAsUser(mContext, user);
2025         }
2026 
postOnSystemServerInitThreadPool(Runnable runnable)2027         void postOnSystemServerInitThreadPool(Runnable runnable) {
2028             SystemServerInitThreadPool.submit(runnable, LOG_TAG);
2029         }
2030 
newTransferOwnershipMetadataManager()2031         public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() {
2032             return new TransferOwnershipMetadataManager();
2033         }
2034 
runCryptoSelfTest()2035         public void runCryptoSelfTest() {
2036             CryptoTestHelper.runAndLogSelfTest();
2037         }
2038 
systemCurrentTimeMillis()2039         public long systemCurrentTimeMillis() {
2040             return System.currentTimeMillis();
2041         }
2042 
isChangeEnabled(long changeId, String packageName, int userId)2043         public boolean isChangeEnabled(long changeId, String packageName, int userId) {
2044             return CompatChanges.isChangeEnabled(changeId, packageName, UserHandle.of(userId));
2045         }
2046 
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)2047         void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
2048             mSafetyChecker = safetyChecker;
2049         }
2050 
getDeviceManagementResourcesProvider()2051         DeviceManagementResourcesProvider getDeviceManagementResourcesProvider() {
2052             return new DeviceManagementResourcesProvider();
2053         }
2054 
isAdminInstalledCaCertAutoApproved()2055         boolean isAdminInstalledCaCertAutoApproved() {
2056             return false;
2057         }
2058     }
2059 
2060     /**
2061      * Instantiates the service.
2062      */
DevicePolicyManagerService(Context context)2063     public DevicePolicyManagerService(Context context) {
2064         this(new Injector(
2065                 context.createAttributionContext(ATTRIBUTION_TAG)), new PolicyPathProvider() {});
2066     }
2067 
2068     @VisibleForTesting
DevicePolicyManagerService(Injector injector, PolicyPathProvider pathProvider)2069     DevicePolicyManagerService(Injector injector, PolicyPathProvider pathProvider) {
2070         DevicePolicyManager.disableLocalCaches();
2071 
2072         mInjector = injector;
2073         mPathProvider = pathProvider;
2074         mContext = Objects.requireNonNull(injector.mContext);
2075         mHandler = new Handler(Objects.requireNonNull(injector.getMyLooper()));
2076 
2077         mConstantsObserver = new DevicePolicyConstantsObserver(mHandler);
2078         mConstantsObserver.register();
2079         mConstants = loadConstants();
2080 
2081         mUserManager = Objects.requireNonNull(injector.getUserManager());
2082         mUserManagerInternal = Objects.requireNonNull(injector.getUserManagerInternal());
2083         mUsageStatsManagerInternal = Objects.requireNonNull(
2084                 injector.getUsageStatsManagerInternal());
2085         mIPackageManager = Objects.requireNonNull(injector.getIPackageManager());
2086         mIPermissionManager = Objects.requireNonNull(injector.getIPermissionManager());
2087         mTelephonyManager = Objects.requireNonNull(injector.getTelephonyManager());
2088         mRoleManager = Objects.requireNonNull(injector.getRoleManager());
2089 
2090         mLocalService = new LocalService();
2091         mLockPatternUtils = injector.newLockPatternUtils();
2092         mLockSettingsInternal = injector.getLockSettingsInternal();
2093         // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
2094         mSecurityLogMonitor = new SecurityLogMonitor(this, mHandler);
2095 
2096         mHasFeature = mInjector.hasFeature();
2097         mIsWatch = mInjector.getPackageManager()
2098                 .hasSystemFeature(PackageManager.FEATURE_WATCH);
2099         mHasTelephonyFeature = mInjector.getPackageManager()
2100                 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
2101         mIsAutomotive = mInjector.getPackageManager()
2102                 .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
2103         mBackgroundHandler = BackgroundThread.getHandler();
2104 
2105         // Needed when mHasFeature == false, because it controls the certificate warning text.
2106         mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
2107 
2108         mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
2109         mOverlayPackagesProvider = new OverlayPackagesProvider(mContext);
2110         mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager();
2111         mBugreportCollectionManager = new RemoteBugreportManager(this, mInjector);
2112 
2113         mDeviceManagementResourcesProvider = mInjector.getDeviceManagementResourcesProvider();
2114         mDevicePolicyManagementRoleObserver = new DevicePolicyManagementRoleObserver(mContext);
2115         mDevicePolicyManagementRoleObserver.register();
2116 
2117         // "Lite" interface is available even when the device doesn't have the feature
2118         LocalServices.addService(DevicePolicyManagerLiteInternal.class, mLocalService);
2119 
2120         // Policy version upgrade must not depend on either mOwners or mUserData, so they are
2121         // initialized only after performing the upgrade.
2122         if (mHasFeature) {
2123             performPolicyVersionUpgrade();
2124         }
2125 
2126         mUserData = new SparseArray<>();
2127         mOwners = makeOwners(injector, pathProvider);
2128 
2129         mDevicePolicyEngine = new DevicePolicyEngine(
2130                 mContext, mDeviceAdminServiceController, getLockObject());
2131 
2132         if (!mHasFeature) {
2133             // Skip the rest of the initialization
2134             mSetupContentObserver = null;
2135             mContactSystemRoleHolders = Collections.emptySet();
2136             return;
2137         }
2138 
2139         loadOwners();
2140 
2141         IntentFilter filter = new IntentFilter();
2142         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
2143         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
2144         filter.addAction(ACTION_TURN_PROFILE_ON_NOTIFICATION);
2145         filter.addAction(ACTION_PROFILE_OFF_DEADLINE);
2146         filter.addAction(Intent.ACTION_USER_ADDED);
2147         filter.addAction(Intent.ACTION_USER_REMOVED);
2148         filter.addAction(Intent.ACTION_USER_STARTED);
2149         filter.addAction(Intent.ACTION_USER_STOPPED);
2150         filter.addAction(Intent.ACTION_USER_SWITCHED);
2151         filter.addAction(Intent.ACTION_USER_UNLOCKED);
2152         filter.addAction(LOGIN_ACCOUNTS_CHANGED_ACTION);
2153         filter.addAction(ACTION_MANAGED_PROFILE_UNAVAILABLE);
2154         filter.addAction(ACTION_MANAGED_PROFILE_AVAILABLE);
2155         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2156         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2157         filter = new IntentFilter();
2158         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
2159         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2160         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
2161         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
2162         filter.addDataScheme("package");
2163         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2164         filter = new IntentFilter();
2165         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
2166         filter.addAction(Intent.ACTION_TIME_CHANGED);
2167         filter.addAction(Intent.ACTION_DATE_CHANGED);
2168         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2169 
2170         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
2171 
2172         mSetupContentObserver = new SetupContentObserver(mHandler);
2173 
2174         mUserManagerInternal.addUserRestrictionsListener(
2175                 new RestrictionsListener(mContext, mUserManagerInternal, this));
2176         mUserManagerInternal.addUserLifecycleListener(new UserLifecycleListener());
2177 
2178         mDeviceManagementResourcesProvider.load();
2179         mDevicePolicyEngine.load();
2180 
2181         mContactSystemRoleHolders = fetchOemSystemHolders(/* roleResIds...= */
2182                 R.string.config_defaultSms,
2183                 R.string.config_defaultDialer,
2184                 R.string.config_systemContacts
2185         );
2186 
2187         // The binder caches are not enabled until the first invalidation.
2188         invalidateBinderCaches();
2189     }
2190 
2191     /**
2192      * Fetch the OEM System Holders for the supplied roleNames
2193      *
2194      * @param roleResIds the list of resource ids whose role holders are needed
2195      * @return the set of packageNames that handle the requested roles
2196      */
fetchOemSystemHolders(int... roleResIds)2197     private @NonNull Set<String> fetchOemSystemHolders(int... roleResIds) {
2198         Set<String> packageNames = new ArraySet<>();
2199 
2200         for (int roleResId : roleResIds) {
2201             String packageName = getDefaultRoleHolderPackageName(roleResId);
2202             if (packageName != null) {
2203                 packageNames.add(packageName);
2204             }
2205         }
2206 
2207         return Collections.unmodifiableSet(packageNames);
2208     }
2209 
2210 
getDefaultRoleHolderPackageName(int resId)2211     private @Nullable String getDefaultRoleHolderPackageName(int resId) {
2212         String packageNameAndSignature = mContext.getString(resId);
2213 
2214         if (TextUtils.isEmpty(packageNameAndSignature)) {
2215             return null;
2216         }
2217 
2218         if (packageNameAndSignature.contains(":")) {
2219             return packageNameAndSignature.split(":")[0];
2220         }
2221 
2222         return packageNameAndSignature;
2223     }
2224 
makeOwners(Injector injector, PolicyPathProvider pathProvider)2225     private Owners makeOwners(Injector injector, PolicyPathProvider pathProvider) {
2226         return new Owners(
2227                 injector.getUserManager(), injector.getUserManagerInternal(),
2228                 injector.getPackageManagerInternal(),
2229                 injector.getActivityTaskManagerInternal(),
2230                 injector.getActivityManagerInternal(), mStateCache, pathProvider);
2231     }
2232 
2233     /**
2234      * Invalidate the binder API caches. The invalidation itself does not require any
2235      * locking, but this specific call should be protected by getLockObject() to ensure
2236      * that the invalidation is synchronous with cached queries, for those queries that
2237      * are served under getLockObject().
2238      */
invalidateBinderCaches()2239     static void invalidateBinderCaches() {
2240         DevicePolicyManager.invalidateBinderCaches();
2241     }
2242 
2243     /**
2244      * Creates and loads the policy data from xml.
2245      * @param userHandle the user for whom to load the policy data
2246      * @return
2247      */
2248     @NonNull
getUserData(int userHandle)2249     DevicePolicyData getUserData(int userHandle) {
2250         synchronized (getLockObject()) {
2251             DevicePolicyData policy = mUserData.get(userHandle);
2252             if (policy == null) {
2253                 policy = new DevicePolicyData(userHandle);
2254                 mUserData.append(userHandle, policy);
2255                 loadSettingsLocked(policy, userHandle);
2256                 if (userHandle == UserHandle.USER_SYSTEM) {
2257                     mStateCache.setDeviceProvisioned(policy.mUserSetupComplete);
2258                 }
2259             }
2260             return policy;
2261         }
2262     }
2263 
2264     /**
2265      * Creates and loads the policy data from xml for data that is shared between
2266      * various profiles of a user. In contrast to {@link #getUserData(int)}
2267      * it allows access to data of users other than the calling user.
2268      *
2269      * This function should only be used for shared data, e.g. everything regarding
2270      * passwords and should be removed once multiple screen locks are present.
2271      * @param userHandle the user for whom to load the policy data
2272      * @return
2273      */
getUserDataUnchecked(int userHandle)2274     DevicePolicyData getUserDataUnchecked(int userHandle) {
2275         return mInjector.binderWithCleanCallingIdentity(() -> getUserData(userHandle));
2276     }
2277 
removeUserData(int userHandle)2278     void removeUserData(int userHandle) {
2279         final boolean isOrgOwned;
2280         synchronized (getLockObject()) {
2281             if (userHandle == UserHandle.USER_SYSTEM) {
2282                 Slogf.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
2283                 return;
2284             }
2285             updatePasswordQualityCacheForUserGroup(userHandle);
2286             mPolicyCache.onUserRemoved(userHandle);
2287 
2288             if (isManagedProfile(userHandle)) {
2289                 clearManagedProfileApnUnchecked();
2290             }
2291             isOrgOwned = mOwners.isProfileOwnerOfOrganizationOwnedDevice(userHandle);
2292 
2293             // Clear any restrictions set by the a profile owner and the parent admin.
2294             final ActiveAdmin admin = getProfileOwnerLocked(userHandle);
2295             if (admin != null) {
2296                 admin.userRestrictions = null;
2297                 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
2298                 if (parentAdmin != null) {
2299                     parentAdmin.userRestrictions = null;
2300                 }
2301             }
2302             mOwners.removeProfileOwner(userHandle);
2303             mOwners.writeProfileOwner(userHandle);
2304 
2305             DevicePolicyData policy = mUserData.get(userHandle);
2306             if (policy != null) {
2307                 mUserData.remove(userHandle);
2308             }
2309 
2310             File policyFile =
2311                     new File(mPathProvider.getUserSystemDirectory(userHandle), DEVICE_POLICIES_XML);
2312             policyFile.delete();
2313             Slogf.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
2314         }
2315         if (isOrgOwned) {
2316             final UserInfo primaryUser = mUserManager.getPrimaryUser();
2317             if (primaryUser != null) {
2318                 clearOrgOwnedProfileOwnerDeviceWidePolicies(primaryUser.id);
2319             } else {
2320                 Slogf.wtf(LOG_TAG, "Was unable to get primary user.");
2321             }
2322         }
2323     }
2324 
2325     /**
2326      * Load information about device and profile owners of the device, populating mOwners and
2327      * pushing owner info to other system services. This is called at a fairly early stage of
2328      * system server initialiation (via DevicePolicyManagerService's ctor), so care should to
2329      * be taken to not interact with system services that are initialiated after DPMS.
2330      * onLockSettingsReady() is a safer place to do initialization work not critical during
2331      * the first boot stage.
2332      * Note this only loads the list of owners, and not their actual policy (DevicePolicyData).
2333      * The policy is normally loaded lazily when it's first accessed. In several occasions
2334      * the list of owners is necessary for providing callers with aggregated policies across
2335      * multiple owners, hence the owner list is loaded as part of DPMS's construction here.
2336      */
loadOwners()2337     void loadOwners() {
2338         synchronized (getLockObject()) {
2339             mOwners.load();
2340             if (mOwners.hasDeviceOwner()) {
2341                 setGlobalSettingDeviceOwnerType(
2342                         mOwners.getDeviceOwnerType(mOwners.getDeviceOwnerPackageName()));
2343             }
2344         }
2345     }
2346 
2347     /**
2348      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
2349      */
getCallerIdentity()2350     private CallerIdentity getCallerIdentity() {
2351         return getCallerIdentity(null, null);
2352     }
2353 
2354     /**
2355      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
2356      */
getCallerIdentity(@ullable String callerPackage)2357     private CallerIdentity getCallerIdentity(@Nullable String callerPackage) {
2358         return getCallerIdentity(null, callerPackage);
2359     }
2360 
2361     /**
2362      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
2363      * The component name should be an active admin for the calling user.
2364      */
2365     @VisibleForTesting
getCallerIdentity(@ullable ComponentName adminComponent)2366     CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent) {
2367         return getCallerIdentity(adminComponent, null);
2368     }
2369 
2370     /**
2371      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
2372      * If {@code adminComponent} is provided, it's validated against the list of known
2373      * active admins and caller uid. If {@code callerPackage} is provided, it's validated
2374      * against the caller uid. If a valid {@code adminComponent} is provided but not
2375      * {@code callerPackage}, the package name of the {@code adminComponent} is used instead.
2376      */
2377     @VisibleForTesting
getCallerIdentity(@ullable ComponentName adminComponent, @Nullable String callerPackage)2378     CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent,
2379             @Nullable String callerPackage) {
2380         final int callerUid = mInjector.binderGetCallingUid();
2381 
2382         if (callerPackage != null) {
2383             if (!isCallingFromPackage(callerPackage, callerUid)) {
2384                 throw new SecurityException(
2385                         String.format("Caller with uid %d is not %s", callerUid, callerPackage));
2386             }
2387         }
2388 
2389         if (adminComponent != null) {
2390             final DevicePolicyData policy = getUserData(UserHandle.getUserId(callerUid));
2391             ActiveAdmin admin = policy.mAdminMap.get(adminComponent);
2392 
2393             // Throwing combined exception message for both the cases here, because from different
2394             // security exceptions it could be deduced if particular package is admin package.
2395             if (admin == null || admin.getUid() != callerUid) {
2396                 throw new SecurityException(String.format(
2397                         "Admin %s does not exist or is not owned by uid %d", adminComponent,
2398                         callerUid));
2399             }
2400             if (callerPackage != null) {
2401                 Preconditions.checkArgument(callerPackage.equals(adminComponent.getPackageName()));
2402             } else {
2403                 callerPackage = adminComponent.getPackageName();
2404             }
2405         }
2406 
2407         return new CallerIdentity(callerUid, callerPackage, adminComponent);
2408     }
2409 
2410     /**
2411      * Checks if the device is in COMP mode, and if so migrates it to managed profile on a
2412      * corporate owned device.
2413      */
2414     @GuardedBy("getLockObject()")
migrateToProfileOnOrganizationOwnedDeviceIfCompLocked()2415     private void migrateToProfileOnOrganizationOwnedDeviceIfCompLocked() {
2416         if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Checking whether we need to migrate COMP ");
2417         final int doUserId = mOwners.getDeviceOwnerUserId();
2418         if (doUserId == UserHandle.USER_NULL) {
2419             if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping migration.");
2420             return;
2421         }
2422 
2423         final List<UserInfo> profiles = mUserManager.getProfiles(doUserId);
2424         if (profiles.size() != 2) {
2425             if (profiles.size() == 1) {
2426                 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Profile not found, skipping migration.");
2427             } else {
2428                 Slogf.wtf(LOG_TAG, "Found " + profiles.size() + " profiles, skipping migration");
2429             }
2430             return;
2431         }
2432 
2433         final int poUserId = getManagedUserId(doUserId);
2434         if (poUserId < 0) {
2435             Slogf.wtf(LOG_TAG, "Found DO and a profile, but it is not managed, skipping migration");
2436             return;
2437         }
2438 
2439         final ActiveAdmin doAdmin = getDeviceOwnerAdminLocked();
2440         final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(poUserId);
2441         if (doAdmin == null || poAdmin == null) {
2442             Slogf.wtf(LOG_TAG, "Failed to get either PO or DO admin, aborting migration.");
2443             return;
2444         }
2445 
2446         final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent();
2447         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(poUserId);
2448         if (doAdminComponent == null || poAdminComponent == null) {
2449             Slogf.wtf(LOG_TAG, "Cannot find PO or DO component name, aborting migration.");
2450             return;
2451         }
2452         if (!doAdminComponent.getPackageName().equals(poAdminComponent.getPackageName())) {
2453             Slogf.e(LOG_TAG, "DO and PO are different packages, aborting migration.");
2454             return;
2455         }
2456 
2457         Slogf.i(LOG_TAG, "Migrating COMP to PO on a corp owned device; primary user: %d; "
2458                 + "profile: %d", doUserId, poUserId);
2459 
2460         Slogf.i(LOG_TAG, "Giving the PO additional power...");
2461         setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(poAdminComponent, poUserId, true);
2462         Slogf.i(LOG_TAG, "Migrating DO policies to PO...");
2463         moveDoPoliciesToProfileParentAdminLocked(doAdmin, poAdmin.getParentActiveAdmin());
2464         migratePersonalAppSuspensionLocked(doUserId, poUserId, poAdmin);
2465         saveSettingsLocked(poUserId);
2466         Slogf.i(LOG_TAG, "Clearing the DO...");
2467         final ComponentName doAdminReceiver = doAdmin.info.getComponent();
2468         clearDeviceOwnerLocked(doAdmin, doUserId);
2469         Slogf.i(LOG_TAG, "Removing admin artifacts...");
2470         removeAdminArtifacts(doAdminReceiver, doUserId);
2471         Slogf.i(LOG_TAG, "Uninstalling the DO...");
2472         uninstallOrDisablePackage(doAdminComponent.getPackageName(), doUserId);
2473         Slogf.i(LOG_TAG, "Migration complete.");
2474 
2475         // Note: KeyChain keys are not removed and will remain accessible for the apps that have
2476         // been given grants to use them.
2477 
2478         DevicePolicyEventLogger
2479                 .createEvent(DevicePolicyEnums.COMP_TO_ORG_OWNED_PO_MIGRATED)
2480                 .setAdmin(poAdminComponent)
2481                 .write();
2482     }
2483 
2484     @GuardedBy("getLockObject()")
migratePersonalAppSuspensionLocked( int doUserId, int poUserId, ActiveAdmin poAdmin)2485     private void migratePersonalAppSuspensionLocked(
2486             int doUserId, int poUserId, ActiveAdmin poAdmin) {
2487         final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
2488         if (!pmi.isAdminSuspendingAnyPackages(doUserId)) {
2489             Slogf.i(LOG_TAG, "DO is not suspending any apps.");
2490             return;
2491         }
2492 
2493         if (getTargetSdk(poAdmin.info.getPackageName(), poUserId) >= Build.VERSION_CODES.R) {
2494             Slogf.i(LOG_TAG, "PO is targeting R+, keeping personal apps suspended.");
2495             getUserData(doUserId).mAppsSuspended = true;
2496             poAdmin.mSuspendPersonalApps = true;
2497         } else {
2498             Slogf.i(LOG_TAG, "PO isn't targeting R+, unsuspending personal apps.");
2499             pmi.unsuspendAdminSuspendedPackages(doUserId);
2500         }
2501     }
2502 
uninstallOrDisablePackage(String packageName, @UserIdInt int userId)2503     private void uninstallOrDisablePackage(String packageName, @UserIdInt int userId) {
2504         final ApplicationInfo appInfo;
2505         try {
2506             appInfo = mIPackageManager.getApplicationInfo(
2507                     packageName, MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId);
2508         } catch (RemoteException e) {
2509             // Shouldn't happen.
2510             Slogf.wtf(LOG_TAG, "Error getting application info", e);
2511             return;
2512         }
2513         if (appInfo == null) {
2514             Slogf.wtf(LOG_TAG, "Failed to get package info for " + packageName);
2515             return;
2516         }
2517         if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2518             Slogf.i(LOG_TAG, "Package %s is pre-installed, marking disabled until used",
2519                     packageName);
2520             mContext.getPackageManager().setApplicationEnabledSetting(packageName,
2521                     PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, /* flags= */ 0);
2522             return;
2523         }
2524 
2525         final IIntentSender.Stub mLocalSender = new IIntentSender.Stub() {
2526             @Override
2527             public void send(int code, Intent intent, String resolvedType, IBinder allowlistToken,
2528                     IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
2529                 final int status = intent.getIntExtra(
2530                         PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
2531                 if (status == PackageInstaller.STATUS_SUCCESS) {
2532                     Slogf.i(LOG_TAG, "Package %s uninstalled for user %d", packageName, userId);
2533                 } else {
2534                     Slogf.e(LOG_TAG, "Failed to uninstall %s; status: %d", packageName, status);
2535                 }
2536             }
2537         };
2538 
2539         final PackageInstaller pi = mInjector.getPackageManager(userId).getPackageInstaller();
2540         pi.uninstall(packageName, /* flags= */ 0, new IntentSender((IIntentSender) mLocalSender));
2541     }
2542 
2543     @GuardedBy("getLockObject()")
moveDoPoliciesToProfileParentAdminLocked( ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2544     private void moveDoPoliciesToProfileParentAdminLocked(
2545             ActiveAdmin doAdmin, ActiveAdmin parentAdmin) {
2546         // The following policies can be already controlled via parent instance, skip if so.
2547         if (parentAdmin.mPasswordPolicy.quality == PASSWORD_QUALITY_UNSPECIFIED) {
2548             parentAdmin.mPasswordPolicy = doAdmin.mPasswordPolicy;
2549         }
2550         if (parentAdmin.passwordHistoryLength == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) {
2551             parentAdmin.passwordHistoryLength = doAdmin.passwordHistoryLength;
2552         }
2553         if (parentAdmin.passwordExpirationTimeout == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) {
2554             parentAdmin.passwordExpirationTimeout = doAdmin.passwordExpirationTimeout;
2555         }
2556         if (parentAdmin.maximumFailedPasswordsForWipe
2557                 == ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
2558             parentAdmin.maximumFailedPasswordsForWipe = doAdmin.maximumFailedPasswordsForWipe;
2559         }
2560         if (parentAdmin.maximumTimeToUnlock == ActiveAdmin.DEF_MAXIMUM_TIME_TO_UNLOCK) {
2561             parentAdmin.maximumTimeToUnlock = doAdmin.maximumTimeToUnlock;
2562         }
2563         if (parentAdmin.strongAuthUnlockTimeout
2564                 == DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
2565             parentAdmin.strongAuthUnlockTimeout = doAdmin.strongAuthUnlockTimeout;
2566         }
2567         parentAdmin.disabledKeyguardFeatures |=
2568                 doAdmin.disabledKeyguardFeatures & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
2569 
2570         parentAdmin.trustAgentInfos.putAll(doAdmin.trustAgentInfos);
2571 
2572         // The following policies weren't available to PO, but will be available after migration.
2573         parentAdmin.disableCamera = doAdmin.disableCamera;
2574         parentAdmin.disableScreenCapture = doAdmin.disableScreenCapture;
2575         parentAdmin.accountTypesWithManagementDisabled.addAll(
2576                 doAdmin.accountTypesWithManagementDisabled);
2577 
2578         moveDoUserRestrictionsToCopeParent(doAdmin, parentAdmin);
2579 
2580         // From Android 11, {@link setAutoTimeRequired} is no longer used. The user restriction
2581         // {@link UserManager#DISALLOW_CONFIG_DATE_TIME} should be used to enforce auto time
2582         // settings instead.
2583         if (doAdmin.requireAutoTime) {
2584             parentAdmin.ensureUserRestrictions().putBoolean(
2585                     UserManager.DISALLOW_CONFIG_DATE_TIME, true);
2586         }
2587     }
2588 
moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2589     private void moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin) {
2590         if (doAdmin.userRestrictions == null) {
2591             return;
2592         }
2593         for (final String restriction : doAdmin.userRestrictions.keySet()) {
2594             if (UserRestrictionsUtils.canParentOfProfileOwnerOfOrganizationOwnedDeviceChange(
2595                     restriction)) {
2596                 parentAdmin.ensureUserRestrictions().putBoolean(
2597                         restriction, doAdmin.userRestrictions.getBoolean(restriction));
2598             }
2599         }
2600     }
2601 
2602     /**
2603      * If the device is in Device Owner mode, apply the restriction on adding
2604      * a managed profile.
2605      */
2606     @GuardedBy("getLockObject()")
applyProfileRestrictionsIfDeviceOwnerLocked()2607     private void applyProfileRestrictionsIfDeviceOwnerLocked() {
2608         final int doUserId = mOwners.getDeviceOwnerUserId();
2609         if (doUserId == UserHandle.USER_NULL) {
2610             if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping application of restriction.");
2611             return;
2612         }
2613 
2614         for (UserInfo userInfo : mUserManager.getUsers()) {
2615             UserHandle userHandle = userInfo.getUserHandle();
2616             // Based on  CDD : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support,
2617             // creation of clone profile is not allowed in case device owner is set.
2618             // Enforcing this restriction on setting up of device owner.
2619             if (!mUserManager.hasUserRestriction(
2620                     UserManager.DISALLOW_ADD_CLONE_PROFILE, userHandle)) {
2621                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, true,
2622                         userHandle);
2623             }
2624             // Enforcing the restriction of private profile creation in case device owner is set.
2625             if (!mUserManager.hasUserRestriction(
2626                     UserManager.DISALLOW_ADD_PRIVATE_PROFILE, userHandle)) {
2627                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE, true,
2628                         userHandle);
2629             }
2630             // Creation of managed profile is restricted in case device owner is set, enforcing this
2631             // restriction by setting user level restriction at time of device owner setup.
2632             if (!mUserManager.hasUserRestriction(
2633                     UserManager.DISALLOW_ADD_MANAGED_PROFILE, userHandle)) {
2634                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
2635                         userHandle);
2636             }
2637         }
2638     }
2639 
2640     /** Apply default restrictions that haven't been applied to profile owners yet. */
maybeSetDefaultProfileOwnerUserRestrictions()2641     private void maybeSetDefaultProfileOwnerUserRestrictions() {
2642         synchronized (getLockObject()) {
2643             for (final int userId : mOwners.getProfileOwnerKeys()) {
2644                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
2645                 // The following restrictions used to be applied to managed profiles by different
2646                 // means (via Settings or by disabling components). Now they are proper user
2647                 // restrictions so we apply them to managed profile owners. Non-managed secondary
2648                 // users didn't have those restrictions so we skip them to keep existing behavior.
2649                 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
2650                     continue;
2651                 }
2652                 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner);
2653                 ensureUnknownSourcesRestrictionForProfileOwnerLocked(
2654                         userId, profileOwner, false /* newOwner */);
2655             }
2656         }
2657     }
2658 
2659     /**
2660      * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
2661      * set of restrictions for this profile owner.
2662      */
ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, ActiveAdmin profileOwner, boolean newOwner)2663     private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
2664             ActiveAdmin profileOwner, boolean newOwner) {
2665         if (newOwner || mInjector.settingsSecureGetIntForUser(
2666                 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
2667             mDevicePolicyEngine.setLocalPolicy(
2668                     PolicyDefinition.getPolicyDefinitionForUserRestriction(
2669                             UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
2670                     EnforcingAdmin.createEnterpriseEnforcingAdmin(
2671                             profileOwner.info.getComponent(),
2672                             profileOwner.getUserHandle().getIdentifier()),
2673                     new BooleanPolicyValue(true),
2674                     userId);
2675             mInjector.settingsSecurePutIntForUser(
2676                     Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
2677         }
2678     }
2679 
2680     /**
2681      * Apply default restrictions that haven't been applied to a given admin yet.
2682      */
maybeSetDefaultRestrictionsForAdminLocked(int userId, ActiveAdmin admin)2683     private void maybeSetDefaultRestrictionsForAdminLocked(int userId, ActiveAdmin admin) {
2684         Set<String> defaultRestrictions =
2685                 UserRestrictionsUtils.getDefaultEnabledForManagedProfiles();
2686         if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
2687             return; // The same set of default restrictions has been already applied.
2688         }
2689         for (String restriction : defaultRestrictions) {
2690             mDevicePolicyEngine.setLocalPolicy(
2691                     PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction),
2692                     EnforcingAdmin.createEnterpriseEnforcingAdmin(
2693                             admin.info.getComponent(),
2694                             admin.getUserHandle().getIdentifier()),
2695                     new BooleanPolicyValue(true),
2696                     userId);
2697         }
2698         admin.defaultEnabledRestrictionsAlreadySet.addAll(defaultRestrictions);
2699         Slogf.i(LOG_TAG, "Enabled the following restrictions by default: "
2700                 + defaultRestrictions);
2701     }
2702 
maybeStartSecurityLogMonitorOnActivityManagerReady()2703     private void maybeStartSecurityLogMonitorOnActivityManagerReady() {
2704         if (!mInjector.securityLogIsLoggingEnabled()) {
2705             return;
2706         }
2707 
2708         if (Flags.securityLogV2Enabled()) {
2709             boolean auditLoggingEnabled = Boolean.TRUE.equals(
2710                     mDevicePolicyEngine.getResolvedPolicy(
2711                             PolicyDefinition.AUDIT_LOGGING, UserHandle.USER_ALL));
2712             boolean securityLoggingEnabled = Boolean.TRUE.equals(
2713                     mDevicePolicyEngine.getResolvedPolicy(
2714                             PolicyDefinition.SECURITY_LOGGING, UserHandle.USER_ALL));
2715             setLoggingConfiguration(securityLoggingEnabled, auditLoggingEnabled);
2716             mInjector.runCryptoSelfTest();
2717         } else {
2718             synchronized (getLockObject()) {
2719                 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
2720                 mInjector.runCryptoSelfTest();
2721                 maybePauseDeviceWideLoggingLocked();
2722             }
2723         }
2724     }
2725 
2726     /**
2727      * Fix left-over restrictions and auto-time policy during COMP -> COPE migration.
2728      *
2729      * When a COMP device with requireAutoTime policy set was migrated to an
2730      * organization-owned profile, a DISALLOW_CONFIG_DATE_TIME restriction is set
2731      * on user 0 from the DO user, which becomes unremovable by the organization-owned
2732      * profile owner. Fix this by force removing that restriction. Also revert the
2733      * parentAdmin.requireAutoTime bit (since the COPE PO cannot unset this bit)
2734      * and replace it with DISALLOW_CONFIG_DATE_TIME on the correct
2735      * admin, in line with the deprecation recommendation of setAutoTimeRequired().
2736      */
fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration()2737     private void fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration() {
2738         for (UserInfo ui : mUserManager.getUsers()) {
2739             final int userId = ui.id;
2740             if (isProfileOwnerOfOrganizationOwnedDevice(userId)) {
2741                 final ActiveAdmin parent = getProfileOwnerAdminLocked(userId).parentAdmin;
2742                 if (parent != null && parent.requireAutoTime) {
2743                     // Remove deprecated requireAutoTime
2744                     parent.requireAutoTime = false;
2745                     saveSettingsLocked(userId);
2746 
2747                     // Remove user restrictions set by the device owner before the upgrade to
2748                     // Android 11.
2749                     mUserManagerInternal.setDevicePolicyUserRestrictions(UserHandle.USER_SYSTEM,
2750                             new Bundle(), new RestrictionsSet(), /* isDeviceOwner */ false);
2751 
2752                     // Apply user restriction to parent active admin instead
2753                     parent.ensureUserRestrictions().putBoolean(
2754                             UserManager.DISALLOW_CONFIG_DATE_TIME, true);
2755                 }
2756             }
2757         }
2758     }
2759 
2760     /**
2761      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2762      * reminders.  Clears alarm if no expirations are configured.
2763      */
setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent)2764     private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2765         final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2766         final long now = System.currentTimeMillis();
2767         final long timeToExpire = expiration - now;
2768         final long alarmTime;
2769         if (expiration == 0) {
2770             // No expirations are currently configured:  Cancel alarm.
2771             alarmTime = 0;
2772         } else if (timeToExpire <= 0) {
2773             // The password has already expired:  Repeat every 24 hours.
2774             alarmTime = now + MS_PER_DAY;
2775         } else {
2776             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2777             // the expiration time.
2778             long alarmInterval = timeToExpire % MS_PER_DAY;
2779             if (alarmInterval == 0) {
2780                 alarmInterval = MS_PER_DAY;
2781             }
2782             alarmTime = now + alarmInterval;
2783         }
2784 
2785         mInjector.binderWithCleanCallingIdentity(() -> {
2786             int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2787             AlarmManager am = mInjector.getAlarmManager();
2788             // Broadcast alarms sent by system are immutable
2789             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2790                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2791                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
2792                             | PendingIntent.FLAG_IMMUTABLE,
2793                     UserHandle.of(affectedUserHandle));
2794             am.cancel(pi);
2795             if (alarmTime != 0) {
2796                 am.set(AlarmManager.RTC, alarmTime, pi);
2797             }
2798         });
2799     }
2800 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle)2801     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2802         ensureLocked();
2803         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2804         if (admin != null
2805                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2806                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2807             return admin;
2808         }
2809         return null;
2810     }
2811 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent)2812     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2813         ensureLocked();
2814         if (parent) {
2815             Preconditions.checkCallAuthorization(isManagedProfile(userHandle),
2816                     "You can not call APIs on the parent profile outside a managed profile, "
2817                             + "userId = %d", userHandle);
2818         }
2819         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2820         if (admin != null && parent) {
2821             admin = admin.getParentActiveAdmin();
2822         }
2823         return admin;
2824     }
2825 
getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)2826     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2827             throws SecurityException {
2828         return getActiveAdminOrCheckPermissionForCallerLocked(who,
2829                 reqPolicy, /* permission= */ null);
2830     }
2831 
getDeviceOwnerLocked(@serIdInt int userId)2832     ActiveAdmin getDeviceOwnerLocked(@UserIdInt int userId) {
2833         ensureLocked();
2834         ComponentName doComponent = mOwners.getDeviceOwnerComponent();
2835         ActiveAdmin doAdmin = getUserData(userId).mAdminMap.get(doComponent);
2836         return doAdmin;
2837     }
2838 
getDefaultDeviceOwnerLocked(@serIdInt int userId)2839     ActiveAdmin getDefaultDeviceOwnerLocked(@UserIdInt int userId) {
2840         ensureLocked();
2841         ComponentName doComponent = mOwners.getDeviceOwnerComponent();
2842         if (mOwners.getDeviceOwnerType(doComponent.getPackageName()) == DEFAULT_DEVICE_OWNER) {
2843             ActiveAdmin doAdmin = getUserData(userId).mAdminMap.get(doComponent);
2844             return doAdmin;
2845         }
2846         return null;
2847     }
2848 
getProfileOwnerLocked(@serIdInt int userId)2849     ActiveAdmin getProfileOwnerLocked(@UserIdInt int userId) {
2850         ensureLocked();
2851         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(userId);
2852         ActiveAdmin poAdmin = getUserData(userId).mAdminMap.get(poAdminComponent);
2853         return poAdmin;
2854     }
2855 
getProfileOwnerOrDeviceOwnerLocked(@serIdInt int userId)2856     ActiveAdmin getProfileOwnerOrDeviceOwnerLocked(@UserIdInt int userId) {
2857         ensureLocked();
2858         // Try to find an admin which can use reqPolicy
2859         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(userId);
2860 
2861         if (poAdminComponent != null) {
2862             return getProfileOwnerLocked(userId);
2863         }
2864 
2865         return getDeviceOwnerLocked(userId);
2866     }
2867 
getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent)2868     @NonNull ActiveAdmin getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent) {
2869         Objects.requireNonNull(admin);
2870         return parent ? admin.getParentActiveAdmin() : admin;
2871     }
2872 
2873     /**
2874      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2875      *
2876      * @return an active admin or {@code null} if there is no active admin but
2877      * {@code permission} is granted
2878      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2879      */
2880     @Nullable
getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, @Nullable String permission)2881     ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
2882             ComponentName who,
2883             int reqPolicy,
2884             @Nullable String permission) throws SecurityException {
2885         return getActiveAdminOrCheckPermissionsForCallerLocked(
2886                 who, reqPolicy, permission == null ? Set.of() : Set.of(permission));
2887     }
2888 
2889     /**
2890      * Finds an active admin for the caller then checks {@code permissions} if admin check failed.
2891      *
2892      * @return an active admin or {@code null} if there is no active admin but
2893      * one of {@code permissions} is granted
2894      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2895      */
2896     @Nullable
getActiveAdminOrCheckPermissionsForCallerLocked( ComponentName who, int reqPolicy, Set<String> permissions)2897     ActiveAdmin getActiveAdminOrCheckPermissionsForCallerLocked(
2898             ComponentName who,
2899             int reqPolicy,
2900             Set<String> permissions) throws SecurityException {
2901         ensureLocked();
2902         final CallerIdentity caller = getCallerIdentity();
2903 
2904         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, caller.getUid());
2905         if (result != null) {
2906             return result;
2907         } else {
2908             for (String permission : permissions) {
2909                 if (hasCallingPermission(permission)) {
2910                     return null;
2911                 }
2912             }
2913         }
2914 
2915         // Code for handling failure from getActiveAdminWithPolicyForUidLocked to find an admin
2916         // that satisfies the required policy.
2917         // Throws a security exception with the right error message.
2918         if (who != null) {
2919             final DevicePolicyData policy = getUserData(caller.getUserId());
2920             ActiveAdmin admin = policy.mAdminMap.get(who);
2921             final boolean isDeviceOwner = isDeviceOwner(admin.info.getComponent(),
2922                     caller.getUserId());
2923             final boolean isProfileOwner = isProfileOwner(admin.info.getComponent(),
2924                     caller.getUserId());
2925 
2926             if (DA_DISALLOWED_POLICIES.contains(reqPolicy) && !isDeviceOwner && !isProfileOwner) {
2927                 throw new SecurityException("Admin " + admin.info.getComponent()
2928                         + " is not a device owner or profile owner, so may not use policy: "
2929                         + admin.info.getTagForPolicy(reqPolicy));
2930             }
2931             throw new SecurityException("Admin " + admin.info.getComponent()
2932                     + " did not specify uses-policy for: "
2933                     + admin.info.getTagForPolicy(reqPolicy));
2934         } else {
2935             throw new SecurityException("No active admin owned by uid "
2936                     + caller.getUid() + " for policy #" + reqPolicy + (permissions.isEmpty() ? ""
2937                     : ", which doesn't have " + permissions));
2938         }
2939     }
2940 
getActiveAdminForCallerLocked(@ullable ComponentName who, int reqPolicy, boolean parent)2941     ActiveAdmin getActiveAdminForCallerLocked(@Nullable ComponentName who, int reqPolicy,
2942             boolean parent) throws SecurityException {
2943         return getActiveAdminOrCheckPermissionForCallerLocked(
2944                 who, reqPolicy, parent, /* permission= */ null);
2945     }
2946 
2947     /**
2948      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2949      *
2950      * @return an active admin or {@code null} if there is no active admin but
2951      * {@code permission} is granted
2952      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2953      */
2954     @Nullable
getActiveAdminOrCheckPermissionForCallerLocked( @ullable ComponentName who, int reqPolicy, boolean parent, @Nullable String permission)2955     ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
2956             @Nullable ComponentName who,
2957             int reqPolicy,
2958             boolean parent,
2959             @Nullable String permission) throws SecurityException {
2960         return getActiveAdminOrCheckPermissionsForCallerLocked(
2961                 who, reqPolicy, parent, permission == null ? Set.of() : Set.of(permission));
2962     }
2963 
2964     /**
2965      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2966      *
2967      * @return an active admin or {@code null} if there is no active admin but
2968      * {@code permission} is granted
2969      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2970      */
2971     @Nullable
getActiveAdminOrCheckPermissionsForCallerLocked( @ullable ComponentName who, int reqPolicy, boolean parent, Set<String> permissions)2972     ActiveAdmin getActiveAdminOrCheckPermissionsForCallerLocked(
2973             @Nullable ComponentName who,
2974             int reqPolicy,
2975             boolean parent,
2976             Set<String> permissions) throws SecurityException {
2977         ensureLocked();
2978         if (parent) {
2979             Preconditions.checkCallingUser(isManagedProfile(getCallerIdentity().getUserId()));
2980         }
2981         ActiveAdmin admin = getActiveAdminOrCheckPermissionsForCallerLocked(
2982                 who, reqPolicy, permissions);
2983         return parent ? admin.getParentActiveAdmin() : admin;
2984     }
2985 
2986     /**
2987      * Find the admin for the component and userId bit of the uid, then check
2988      * the admin's uid matches the uid.
2989      */
getActiveAdminForUidLocked(ComponentName who, int uid)2990     private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2991         ensureLocked();
2992         final int userId = UserHandle.getUserId(uid);
2993         final DevicePolicyData policy = getUserData(userId);
2994         ActiveAdmin admin = policy.mAdminMap.get(who);
2995         if (admin == null) {
2996             throw new SecurityException("No active admin " + who + " for UID " + uid);
2997         }
2998         if (admin.getUid() != uid) {
2999             throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
3000         }
3001         return admin;
3002     }
3003 
3004     /**
3005      * Returns the active admin for the user of the caller as denoted by uid, which implements
3006      * the {@code reqPolicy}.
3007      *
3008      * The {@code who} parameter is used as a hint:
3009      * If provided, it must be the component name of the active admin for that user and the caller
3010      * uid must match the uid of the admin.
3011      * If not provided, iterate over all of the active admins in the DevicePolicyData for that user
3012      * and return the one with the uid specified as parameter, and has the policy specified.
3013      */
3014     @Nullable
getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, int uid)3015     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
3016             int uid) {
3017         ensureLocked();
3018         // Try to find an admin which can use reqPolicy
3019         final int userId = UserHandle.getUserId(uid);
3020         final DevicePolicyData policy = getUserData(userId);
3021         if (who != null) {
3022             ActiveAdmin admin = policy.mAdminMap.get(who);
3023             if (admin == null || admin.getUid() != uid) {
3024                 throw new SecurityException(
3025                         "Admin " + who + " is not active or not owned by uid " + uid);
3026             }
3027             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
3028                 return admin;
3029             }
3030         } else {
3031             for (ActiveAdmin admin : policy.mAdminList) {
3032                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
3033                         userId)) {
3034                     return admin;
3035                 }
3036             }
3037         }
3038 
3039         return null;
3040     }
3041 
3042     @VisibleForTesting
isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, int userId)3043     boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
3044             int userId) {
3045         ensureLocked();
3046         final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
3047         final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
3048 
3049         boolean allowedToUsePolicy = ownsDevice || ownsProfile
3050                 || !DA_DISALLOWED_POLICIES.contains(reqPolicy)
3051                 || getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.Q;
3052         return allowedToUsePolicy && admin.info.usesPolicy(reqPolicy);
3053     }
3054 
3055     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
3056         sendAdminCommandLocked(admin, action, null);
3057     }
3058 
3059     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
3060         sendAdminCommandLocked(admin, action, null, result);
3061     }
3062 
3063     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
3064             BroadcastReceiver result) {
3065         sendAdminCommandLocked(admin, action, adminExtras, result, false);
3066     }
3067 
3068     /**
3069      * Send an update to one specific admin, get notified when that admin returns a result.
3070      *
3071      * @return whether the broadcast was successfully sent
3072      */
3073     boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
3074             BroadcastReceiver result, boolean inForeground) {
3075         Intent intent = new Intent(action);
3076         intent.setComponent(admin.info.getComponent());
3077         if (UserManager.isDeviceInDemoMode(mContext)) {
3078             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3079         }
3080         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
3081             intent.putExtra("expiration", admin.passwordExpirationDate);
3082         }
3083         if (inForeground) {
3084             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3085         }
3086         if (adminExtras != null) {
3087             intent.putExtras(adminExtras);
3088         }
3089         if (mInjector.getPackageManager().queryBroadcastReceiversAsUser(
3090                 intent,
3091                 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
3092                 admin.getUserHandle()).isEmpty()) {
3093             return false;
3094         }
3095 
3096         final BroadcastOptions options = BroadcastOptions.makeBasic();
3097         options.setBackgroundActivityStartsAllowed(true);
3098 
3099         if (result != null) {
3100             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
3101                     null, AppOpsManager.OP_NONE, options.toBundle(),
3102                     result, mHandler, Activity.RESULT_OK, null, null);
3103         } else {
3104             mContext.sendBroadcastAsUser(intent, admin.getUserHandle(), null, options.toBundle());
3105         }
3106 
3107         return true;
3108     }
3109 
3110     /**
3111      * Send an update to all admins of a user that enforce a specified policy.
3112      */
3113     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
3114         final DevicePolicyData policy = getUserData(userHandle);
3115         final int count = policy.mAdminList.size();
3116         for (int i = 0; i < count; i++) {
3117             final ActiveAdmin admin = policy.mAdminList.get(i);
3118             if (admin.info.usesPolicy(reqPolicy)) {
3119                 sendAdminCommandLocked(admin, action, adminExtras, null);
3120             }
3121         }
3122     }
3123 
3124     /**
3125      * Send an update intent to all admins of a user and its profiles. Only send to admins that
3126      * enforce a specified policy.
3127      */
3128     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
3129             int userHandle, Bundle adminExtras) {
3130         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
3131         for (int profileId : profileIds) {
3132             sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
3133         }
3134     }
3135 
3136     /**
3137      * Sends a broadcast to each profile that share the password unlock with the given user id.
3138      */
3139     private void sendAdminCommandForLockscreenPoliciesLocked(
3140             String action, int reqPolicy, int userHandle) {
3141         final Bundle extras = new Bundle();
3142         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3143         if (isSeparateProfileChallengeEnabled(userHandle)) {
3144             sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
3145         } else {
3146             sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
3147         }
3148     }
3149 
3150     void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
3151         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3152         DevicePolicyData policy = getUserData(userHandle);
3153         if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
3154             Slogf.d(LOG_TAG, "Adding " + adminReceiver + " for user " + userHandle
3155                     + " to list of removing admins.");
3156             logStackTrace("removeActiveAdminLocked");
3157 
3158             policy.mRemovingAdmins.add(adminReceiver);
3159             sendAdminCommandLocked(admin,
3160                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
3161                     new BroadcastReceiver() {
3162                         @Override
3163                         public void onReceive(Context context, Intent intent) {
3164                             removeAdminArtifacts(adminReceiver, userHandle);
3165                             removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
3166                         }
3167                     });
3168         }
3169     }
3170 
3171     private DeviceAdminInfo findAdmin(final ComponentName adminName, final int userHandle,
3172             boolean throwForMissingPermission) {
3173         final ActivityInfo ai = mInjector.binderWithCleanCallingIdentity(() -> {
3174             try {
3175                 return mIPackageManager.getReceiverInfo(adminName,
3176                         GET_META_DATA
3177                         | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS
3178                         | PackageManager.MATCH_DIRECT_BOOT_AWARE
3179                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
3180             } catch (RemoteException e) {
3181                 // shouldn't happen.
3182                 Slogf.wtf(LOG_TAG, "Error getting receiver info", e);
3183                 return null;
3184             }
3185         });
3186         if (ai == null) {
3187             throw new IllegalArgumentException("Unknown admin: " + adminName);
3188         }
3189 
3190         if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
3191             final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
3192                     + permission.BIND_DEVICE_ADMIN;
3193             Slogf.w(LOG_TAG, message);
3194             if (throwForMissingPermission &&
3195                     ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
3196                 throw new IllegalArgumentException(message);
3197             }
3198         }
3199 
3200         try {
3201             return new DeviceAdminInfo(mContext, ai);
3202         } catch (XmlPullParserException | IOException e) {
3203             Slogf.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
3204                     e);
3205             return null;
3206         }
3207     }
3208 
3209     private File getPolicyFileDirectory(@UserIdInt int userId) {
3210         return userId == UserHandle.USER_SYSTEM
3211                 ? mPathProvider.getDataSystemDirectory()
3212                 : mPathProvider.getUserSystemDirectory(userId);
3213     }
3214 
3215     private JournaledFile makeJournaledFile(@UserIdInt int userId, String fileName) {
3216         final String base = new File(getPolicyFileDirectory(userId), fileName)
3217                 .getAbsolutePath();
3218         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Opening %s", base);
3219         return new JournaledFile(new File(base), new File(base + ".tmp"));
3220     }
3221 
3222     private JournaledFile makeJournaledFile(@UserIdInt int userId) {
3223         return makeJournaledFile(userId, DEVICE_POLICIES_XML);
3224     }
3225 
3226     /**
3227      * Persist modified values to disk by calling {@link #saveSettingsLocked} for each
3228      * affected user ID.
3229      */
3230     @GuardedBy("getLockObject()")
3231     private void saveSettingsForUsersLocked(Set<Integer> affectedUserIds) {
3232         for (int userId : affectedUserIds) {
3233             saveSettingsLocked(userId);
3234         }
3235     }
3236 
3237     private void saveSettingsLocked(int userHandle) {
3238         if (DevicePolicyData.store(getUserData(userHandle), makeJournaledFile(userHandle))) {
3239             sendChangedNotification(userHandle);
3240         }
3241         invalidateBinderCaches();
3242     }
3243 
3244     private void sendChangedNotification(int userHandle) {
3245         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
3246         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3247         Bundle options = new BroadcastOptions()
3248                 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
3249                 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
3250                 .toBundle();
3251         mInjector.binderWithCleanCallingIdentity(() ->
3252                 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle), null, options));
3253     }
3254 
3255     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
3256         DevicePolicyData.load(policy,
3257                 makeJournaledFile(userHandle),
3258                 component -> findAdmin(
3259                         component, userHandle, /* throwForMissingPermission= */ false),
3260                 getOwnerComponent(userHandle));
3261 
3262         policy.validatePasswordOwner();
3263         updateMaximumTimeToLockLocked(userHandle);
3264         if (policy.mStatusBarDisabled) {
3265             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
3266         }
3267     }
3268 
3269     static void updateLockTaskPackagesLocked(Context context, List<String> packages, int userId) {
3270         Binder.withCleanCallingIdentity(() -> {
3271 
3272             String[] packagesArray = null;
3273             if (!packages.isEmpty()) {
3274                 // When adding packages, we need to include the exempt apps so they can still be
3275                 // launched (ideally we should use a different AM API as these apps don't need to
3276                 // use lock-task mode).
3277                 // They're not added when the packages is empty though, as in that case we're
3278                 // disabling lock-task mode.
3279                 List<String> exemptApps = listPolicyExemptAppsUnchecked(context);
3280                 if (!exemptApps.isEmpty()) {
3281                     // TODO(b/175377361): add unit test to verify it (cannot be CTS because the
3282                     //  policy-exempt apps are provided by OEM and the test would have no control
3283                     //  over it) once tests are migrated to the new infra-structure
3284                     HashSet<String> updatedPackages = new HashSet<>(packages);
3285                     updatedPackages.addAll(exemptApps);
3286                     if (VERBOSE_LOG) {
3287                         Slogf.v(LOG_TAG, "added %d policy-exempt apps to %d lock task "
3288                                 + "packages. Final list: %s",
3289                                 exemptApps.size(), packages.size(), updatedPackages);
3290                     }
3291                     packagesArray = updatedPackages.toArray(new String[updatedPackages.size()]);
3292                 }
3293             }
3294 
3295             if (packagesArray == null) {
3296                 packagesArray = packages.toArray(new String[packages.size()]);
3297             }
3298             try {
3299                 ActivityManager.getService().updateLockTaskPackages(userId, packagesArray);
3300             } catch (RemoteException e) {
3301                 // Shouldn't happen.
3302                 Slog.wtf(LOG_TAG, "Remote Exception: ", e);
3303             }
3304         });
3305     }
3306 
3307     static void updateLockTaskFeaturesLocked(int flags, int userId) {
3308         Binder.withCleanCallingIdentity(() -> {
3309             try {
3310                 ActivityTaskManager.getService().updateLockTaskFeatures(userId, flags);
3311             } catch (RemoteException e) {
3312                 // Shouldn't happen.
3313                 Slog.wtf(LOG_TAG, "Remote Exception: ", e);
3314             }
3315         });
3316     }
3317 
3318     static void validateQualityConstant(int quality) {
3319         switch (quality) {
3320             case PASSWORD_QUALITY_UNSPECIFIED:
3321             case PASSWORD_QUALITY_BIOMETRIC_WEAK:
3322             case PASSWORD_QUALITY_SOMETHING:
3323             case PASSWORD_QUALITY_NUMERIC:
3324             case PASSWORD_QUALITY_NUMERIC_COMPLEX:
3325             case PASSWORD_QUALITY_ALPHABETIC:
3326             case PASSWORD_QUALITY_ALPHANUMERIC:
3327             case PASSWORD_QUALITY_COMPLEX:
3328             case PASSWORD_QUALITY_MANAGED:
3329                 return;
3330         }
3331         throw new IllegalArgumentException("Invalid quality constant: 0x"
3332                 + Integer.toHexString(quality));
3333     }
3334 
3335     @VisibleForTesting
3336     void systemReady(int phase) {
3337         if (!mHasFeature) {
3338             return;
3339         }
3340         switch (phase) {
3341             case SystemService.PHASE_LOCK_SETTINGS_READY:
3342                 onLockSettingsReady();
3343                 loadAdminDataAsync();
3344                 mOwners.systemReady();
3345                 applyManagedSubscriptionsPolicyIfRequired();
3346                 break;
3347             case SystemService.PHASE_SYSTEM_SERVICES_READY:
3348                 synchronized (getLockObject()) {
3349                     mDevicePolicyEngine.reapplyAllPoliciesOnBootLocked();
3350                 }
3351                 break;
3352             case SystemService.PHASE_ACTIVITY_MANAGER_READY:
3353                 synchronized (getLockObject()) {
3354                     migrateToProfileOnOrganizationOwnedDeviceIfCompLocked();
3355                     applyProfileRestrictionsIfDeviceOwnerLocked();
3356 
3357                     // TODO: Is this the right place to trigger the migration?
3358                     if (shouldMigrateV1ToDevicePolicyEngine()) {
3359                         migrateV1PoliciesToDevicePolicyEngine();
3360                     }
3361                     maybeMigratePoliciesPostUpgradeToDevicePolicyEngineLocked();
3362                     migratePoliciesToPolicyEngineLocked();
3363                 }
3364                 maybeStartSecurityLogMonitorOnActivityManagerReady();
3365                 break;
3366             case SystemService.PHASE_BOOT_COMPLETED:
3367                 // Ideally it should be done earlier, but currently it relies on RecoverySystem,
3368                 // which would hang on earlier phases
3369                 factoryResetIfDelayedEarlier();
3370 
3371                 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
3372                 break;
3373         }
3374     }
3375 
3376     @GuardedBy("getLockObject()")
3377     private void maybeMigrateSecurityLoggingPolicyLocked() {
3378         if (!Flags.securityLogV2Enabled() || mOwners.isSecurityLoggingMigrated()) {
3379             return;
3380         }
3381 
3382         try {
3383             migrateSecurityLoggingPolicyInternalLocked();
3384         } catch (Exception e) {
3385             Slog.e(LOG_TAG, "Failed to properly migrate security logging to policy engine", e);
3386         }
3387 
3388         Slog.i(LOG_TAG, "Marking security logging policy migration complete");
3389         mOwners.markSecurityLoggingMigrated();
3390     }
3391 
3392     @GuardedBy("getLockObject()")
3393     private void migrateSecurityLoggingPolicyInternalLocked() {
3394         Slog.i(LOG_TAG, "Migrating security logging policy to policy engine");
3395         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
3396             Slog.i(LOG_TAG, "Security logs not enabled, exiting");
3397             return;
3398         }
3399 
3400         // Security logging can be enabled either by DO or by COPE PO.
3401         final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
3402         if (admin == null) {
3403             Slog.wtf(LOG_TAG, "Security logging is enabled, but no appropriate admin found");
3404             return;
3405         }
3406 
3407         EnforcingAdmin enforcingAdmin =
3408                 EnforcingAdmin.createEnterpriseEnforcingAdmin(
3409                         admin.info.getComponent(),
3410                         admin.getUserHandle().getIdentifier(),
3411                         admin);
3412         mDevicePolicyEngine.setGlobalPolicy(
3413                 PolicyDefinition.SECURITY_LOGGING,
3414                 enforcingAdmin,
3415                 new BooleanPolicyValue(true));
3416     }
3417 
3418     @GuardedBy("getLockObject()")
3419     private boolean maybeMigrateRequiredPasswordComplexityLocked(String backupId) {
3420         Slog.i(LOG_TAG, "Migrating password complexity to policy engine");
3421         if (!Flags.unmanagedModeMigration()) {
3422             return false;
3423         }
3424         if (mOwners.isRequiredPasswordComplexityMigrated()) {
3425             return false;
3426         }
3427         // Create backup if none exists
3428         mDevicePolicyEngine.createBackup(backupId);
3429         try {
3430             iterateThroughDpcAdminsLocked((admin, enforcingAdmin) -> {
3431                 int userId = enforcingAdmin.getUserId();
3432                 if (admin.mPasswordComplexity != PASSWORD_COMPLEXITY_NONE) {
3433                     mDevicePolicyEngine.setLocalPolicy(
3434                             PolicyDefinition.PASSWORD_COMPLEXITY,
3435                             enforcingAdmin,
3436                             new IntegerPolicyValue(admin.mPasswordComplexity),
3437                             userId);
3438                 }
3439                 ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
3440                 if (parentAdmin != null
3441                         && parentAdmin.mPasswordComplexity != PASSWORD_COMPLEXITY_NONE) {
3442                     mDevicePolicyEngine.setLocalPolicy(
3443                             PolicyDefinition.PASSWORD_COMPLEXITY,
3444                             enforcingAdmin,
3445                             new IntegerPolicyValue(parentAdmin.mPasswordComplexity),
3446                             getProfileParentId(userId));
3447                 }
3448             });
3449         } catch (Exception e) {
3450             Slog.wtf(LOG_TAG, "Failed to migrate password complexity to policy engine", e);
3451         }
3452 
3453         Slog.i(LOG_TAG, "Marking password complexity migration complete");
3454         mOwners.markRequiredPasswordComplexityMigrated();
3455         return true;
3456     }
3457 
3458     @GuardedBy("getLockObject()")
3459     private boolean maybeMigrateSuspendedPackagesLocked(String backupId) {
3460         Slog.i(LOG_TAG, "Migrating suspended packages to policy engine");
3461         if (!Flags.unmanagedModeMigration()) {
3462             return false;
3463         }
3464         if (mOwners.isSuspendedPackagesMigrated()) {
3465             return false;
3466         }
3467         // Create backup if none exists
3468         mDevicePolicyEngine.createBackup(backupId);
3469         try {
3470             iterateThroughDpcAdminsLocked((admin, enforcingAdmin) -> {
3471                 if (admin.suspendedPackages == null || admin.suspendedPackages.size() == 0) {
3472                     return;
3473                 }
3474                 int userId = enforcingAdmin.getUserId();
3475                 mDevicePolicyEngine.setLocalPolicy(
3476                         PolicyDefinition.PACKAGES_SUSPENDED,
3477                         enforcingAdmin,
3478                         new PackageSetPolicyValue(new ArraySet<>(admin.suspendedPackages)),
3479                         userId);
3480             });
3481         } catch (Exception e) {
3482             Slog.wtf(LOG_TAG, "Failed to migrate suspended packages to policy engine", e);
3483         }
3484 
3485         Slog.i(LOG_TAG, "Marking suspended packages migration complete");
3486         mOwners.markSuspendedPackagesMigrated();
3487         return true;
3488     }
3489 
3490 
3491     private void applyManagedSubscriptionsPolicyIfRequired() {
3492         int copeProfileUserId = getOrganizationOwnedProfileUserId();
3493         // This policy is relevant only for COPE devices.
3494         if (copeProfileUserId != UserHandle.USER_NULL) {
3495             unregisterOnSubscriptionsChangedListener();
3496             int policyType = getManagedSubscriptionsPolicy().getPolicyType();
3497             if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS) {
3498                 clearManagedSubscriptionsPolicy();
3499             } else if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
3500                 // Add listener to assign all current and future subs to managed profile.
3501                 registerListenerToAssignSubscriptionsToUser(copeProfileUserId);
3502             }
3503         }
3504     }
3505 
3506     private void updatePersonalAppsSuspensionOnUserStart(int userHandle) {
3507         final int profileUserHandle = getManagedUserId(userHandle);
3508         if (profileUserHandle >= 0) {
3509             // Given that the parent user has just started, profile should be locked.
3510             updatePersonalAppsSuspension(profileUserHandle);
3511         } else {
3512             suspendPersonalAppsInternal(userHandle, profileUserHandle, false);
3513         }
3514     }
3515 
3516     private void onLockSettingsReady() {
3517         synchronized (getLockObject()) {
3518             fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration();
3519         }
3520         getUserData(UserHandle.USER_SYSTEM);
3521         cleanUpOldUsers();
3522         maybeSetDefaultProfileOwnerUserRestrictions();
3523         handleStartUser(UserHandle.USER_SYSTEM);
3524         maybeLogStart();
3525 
3526         // Register an observer for watching for user setup complete and settings changes.
3527         mSetupContentObserver.register();
3528         // Initialize the user setup state, to handle the upgrade case.
3529         updateUserSetupCompleteAndPaired();
3530 
3531         List<String> packageList;
3532         synchronized (getLockObject()) {
3533             packageList = getKeepUninstalledPackagesLocked();
3534         }
3535         if (packageList != null) {
3536             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3537         }
3538 
3539         synchronized (getLockObject()) {
3540             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3541             if (deviceOwner != null) {
3542                 // Push the force-ephemeral-users policy to the user manager.
3543                 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3544 
3545                 // Update user switcher message to activity manager.
3546                 ActivityManagerInternal activityManagerInternal =
3547                         mInjector.getActivityManagerInternal();
3548                 activityManagerInternal.setSwitchingFromSystemUserMessage(
3549                         deviceOwner.startUserSessionMessage);
3550                 activityManagerInternal.setSwitchingToSystemUserMessage(
3551                         deviceOwner.endUserSessionMessage);
3552             }
3553 
3554             revertTransferOwnershipIfNecessaryLocked();
3555             if (!Flags.policyEngineMigrationV2Enabled()) {
3556                 updateUsbDataSignal(mContext, isUsbDataSignalingEnabledInternalLocked());
3557             }
3558         }
3559 
3560         // Check whether work apps were paused via suspension and unsuspend if necessary.
3561         // TODO: move it into PolicyVersionUpgrader so that it is executed only once.
3562         unsuspendWorkAppsIfNecessary();
3563     }
3564 
3565     // TODO(b/230841522) Make it static.
3566     private class DpmsUpgradeDataProvider implements PolicyUpgraderDataProvider {
3567         @Override
3568         public JournaledFile makeDevicePoliciesJournaledFile(int userId) {
3569             return DevicePolicyManagerService.this.makeJournaledFile(userId, DEVICE_POLICIES_XML);
3570         }
3571 
3572         @Override
3573         public JournaledFile makePoliciesVersionJournaledFile(int userId) {
3574             return DevicePolicyManagerService.this.makeJournaledFile(userId, POLICIES_VERSION_XML);
3575         }
3576 
3577         @Override
3578         public Function<ComponentName, DeviceAdminInfo> getAdminInfoSupplier(int userId) {
3579             return component ->
3580                     findAdmin(component, userId, /* throwForMissingPermission= */ false);
3581         }
3582 
3583         @Override
3584         public int[] getUsersForUpgrade() {
3585             List<UserInfo> allUsers = mUserManager.getUsers();
3586             return allUsers.stream().mapToInt(u -> u.id).toArray();
3587         }
3588 
3589         @Override
3590         public List<String> getPlatformSuspendedPackages(int userId) {
3591             PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
3592             return mInjector.getPackageManager(userId)
3593                     .getInstalledPackages(PackageManager.PackageInfoFlags.of(
3594                             MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE))
3595                     .stream()
3596                     .map(packageInfo -> packageInfo.packageName)
3597                     .filter(pkg ->
3598                             PLATFORM_PACKAGE_NAME.equals(pmi.getSuspendingPackage(pkg, userId))
3599                     )
3600                     .collect(Collectors.toList());
3601         }
3602     }
3603 
3604     private void performPolicyVersionUpgrade() {
3605         PolicyVersionUpgrader upgrader = new PolicyVersionUpgrader(
3606                 new DpmsUpgradeDataProvider(), mPathProvider);
3607         upgrader.upgradePolicy(DPMS_VERSION);
3608     }
3609 
3610     private void revertTransferOwnershipIfNecessaryLocked() {
3611         if (!mTransferOwnershipMetadataManager.metadataFileExists()) {
3612             return;
3613         }
3614         Slogf.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer.");
3615         final TransferOwnershipMetadataManager.Metadata metadata =
3616                 mTransferOwnershipMetadataManager.loadMetadataFile();
3617         // Revert transfer
3618         if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) {
3619             transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3620                     metadata.userId);
3621             deleteTransferOwnershipMetadataFileLocked();
3622             deleteTransferOwnershipBundleLocked(metadata.userId);
3623         } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) {
3624             transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3625                     metadata.userId);
3626             deleteTransferOwnershipMetadataFileLocked();
3627             deleteTransferOwnershipBundleLocked(metadata.userId);
3628         }
3629         updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
3630     }
3631 
3632     private void maybeLogStart() {
3633         if (!SecurityLog.isLoggingEnabled()) {
3634             return;
3635         }
3636         final String verifiedBootState =
3637                 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate");
3638         final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode");
3639         SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode);
3640     }
3641 
3642     private void ensureDeviceOwnerUserStarted() {
3643         final int userId;
3644         synchronized (getLockObject()) {
3645             if (!mOwners.hasDeviceOwner()) {
3646                 return;
3647             }
3648             userId = mOwners.getDeviceOwnerUserId();
3649         }
3650         if (VERBOSE_LOG) {
3651             Slogf.v(LOG_TAG, "Starting non-system DO user: " + userId);
3652         }
3653         if (userId != UserHandle.USER_SYSTEM) {
3654             try {
3655                 mInjector.getIActivityManager().startUserInBackground(userId);
3656 
3657                 // STOPSHIP Prevent the DO user from being killed.
3658 
3659             } catch (RemoteException e) {
3660                 Slogf.w(LOG_TAG, "Exception starting user", e);
3661             }
3662         }
3663     }
3664 
3665     void handleStartUser(int userId) {
3666         // When system user is started (device boot), load cache for all users.
3667         // This is to mitigate the potential race between loading the cache and keyguard
3668         // reading the value during user switch, due to onStartUser() being asynchronous.
3669         updatePasswordQualityCacheForUserGroup(
3670                 userId == UserHandle.USER_SYSTEM ? UserHandle.USER_ALL : userId);
3671         updatePermissionPolicyCache(userId);
3672         updateAdminCanGrantSensorsPermissionCache(userId);
3673         updateContentProtectionPolicyCache(userId);
3674 
3675         final List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs;
3676         synchronized (getLockObject()) {
3677             ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
3678             preferentialNetworkServiceConfigs = owner != null
3679                     ? owner.mPreferentialNetworkServiceConfigs
3680                     : List.of(PreferentialNetworkServiceConfig.DEFAULT);
3681         }
3682         updateNetworkPreferenceForUser(userId, preferentialNetworkServiceConfigs);
3683 
3684         if (isProfileOwnerOfOrganizationOwnedDevice(userId)
3685                 && getManagedSubscriptionsPolicy().getPolicyType()
3686                 == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
3687             updateDialerAndSmsManagedShortcutsOverrideCache();
3688         }
3689 
3690         startOwnerService(userId, "start-user");
3691         mDevicePolicyEngine.handleStartUser(userId);
3692     }
3693 
3694     void handleUnlockUser(int userId) {
3695         startOwnerService(userId, "unlock-user");
3696         mDevicePolicyEngine.handleUnlockUser(userId);
3697     }
3698 
3699     void handleOnUserUnlocked(int userId) {
3700         showNewUserDisclaimerIfNecessary(userId);
3701     }
3702 
3703     void handleStopUser(int userId) {
3704         updateNetworkPreferenceForUser(userId, List.of(PreferentialNetworkServiceConfig.DEFAULT));
3705         mDeviceAdminServiceController.stopServicesForUser(userId, /* actionForLog= */ "stop-user");
3706         mDevicePolicyEngine.handleStopUser(userId);
3707     }
3708 
3709     private void startOwnerService(int userId, String actionForLog) {
3710         final ComponentName owner = getOwnerComponent(userId);
3711         if (owner != null) {
3712             mDeviceAdminServiceController.startServiceForAdmin(
3713                     owner.getPackageName(), userId, actionForLog);
3714             invalidateBinderCaches();
3715         }
3716     }
3717 
3718     private void cleanUpOldUsers() {
3719         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3720         // before reboot
3721         Set<Integer> usersWithProfileOwners;
3722         Set<Integer> usersWithData;
3723         synchronized (getLockObject()) {
3724             usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3725             usersWithData = new ArraySet<>();
3726             for (int i = 0; i < mUserData.size(); i++) {
3727                 usersWithData.add(mUserData.keyAt(i));
3728             }
3729         }
3730         List<UserInfo> allUsers = mUserManager.getUsers();
3731 
3732         Set<Integer> deletedUsers = new ArraySet<>();
3733         deletedUsers.addAll(usersWithProfileOwners);
3734         deletedUsers.addAll(usersWithData);
3735         for (UserInfo userInfo : allUsers) {
3736             deletedUsers.remove(userInfo.id);
3737         }
3738         for (Integer userId : deletedUsers) {
3739             removeUserData(userId);
3740             mDevicePolicyEngine.handleUserRemoved(userId);
3741         }
3742     }
3743 
3744     private void handlePasswordExpirationNotification(int userHandle) {
3745         final Bundle adminExtras = new Bundle();
3746         adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3747 
3748         synchronized (getLockObject()) {
3749             final long now = System.currentTimeMillis();
3750 
3751             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
3752             final int N = admins.size();
3753             for (int i = 0; i < N; i++) {
3754                 ActiveAdmin admin = admins.get(i);
3755                 if ((admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD))
3756                         && admin.passwordExpirationTimeout > 0L
3757                         && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3758                         && admin.passwordExpirationDate > 0L) {
3759                     sendAdminCommandLocked(admin,
3760                             DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3761                 }
3762             }
3763             setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3764         }
3765     }
3766 
3767     /**
3768      * Clean up internal state when the set of installed trusted CA certificates changes.
3769      *
3770      * @param userHandle user to check for. This must be a real user and not, for example,
3771      *        {@link UserHandle#ALL}.
3772      * @param installedCertificates the full set of certificate authorities currently installed for
3773      *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3774      *        correspond to some subset of this.
3775      */
3776     protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3777             final @NonNull Collection<String> installedCertificates) {
3778         if (!mHasFeature) {
3779             return;
3780         }
3781         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
3782 
3783         synchronized (getLockObject()) {
3784             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3785 
3786             boolean changed = false;
3787             changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3788             changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3789             if (changed) {
3790                 saveSettingsLocked(userHandle.getIdentifier());
3791             }
3792         }
3793     }
3794 
3795     /**
3796      * Internal method used by {@link CertificateMonitor}.
3797      */
3798     protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3799         if (!mHasFeature) {
3800             return Collections.<String> emptySet();
3801         }
3802         synchronized (getLockObject()) {
3803             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3804             return policy.mAcceptedCaCertificates;
3805         }
3806     }
3807 
3808     /**
3809      * @param adminReceiver The admin to add
3810      * @param refreshing true = update an active admin, no error
3811      */
3812     @Override
3813     public void setActiveAdmin(
3814             ComponentName adminReceiver, boolean refreshing, int userHandle) {
3815         if (!mHasFeature) {
3816             return;
3817         }
3818         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3819 
3820         final CallerIdentity caller = getCallerIdentity();
3821         Preconditions.checkCallAuthorization(
3822                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
3823         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3824 
3825         DevicePolicyData policy = getUserData(userHandle);
3826         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3827                 /* throwForMissingPermission= */ true);
3828         synchronized (getLockObject()) {
3829             checkActiveAdminPrecondition(adminReceiver, info, policy);
3830             mInjector.binderWithCleanCallingIdentity(() -> {
3831                 final ActiveAdmin existingAdmin
3832                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3833                 if (!refreshing && existingAdmin != null) {
3834                     throw new IllegalArgumentException("Admin is already added");
3835                 }
3836                 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3837                 newAdmin.testOnlyAdmin =
3838                         (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3839                                 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3840                 policy.mAdminMap.put(adminReceiver, newAdmin);
3841                 int replaceIndex = -1;
3842                 final int N = policy.mAdminList.size();
3843                 for (int i=0; i < N; i++) {
3844                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3845                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3846                         replaceIndex = i;
3847                         break;
3848                     }
3849                 }
3850                 if (replaceIndex == -1) {
3851                     policy.mAdminList.add(newAdmin);
3852                     enableIfNecessary(info.getPackageName(), userHandle);
3853                     mUsageStatsManagerInternal.onActiveAdminAdded(
3854                             adminReceiver.getPackageName(), userHandle);
3855                 } else {
3856                     policy.mAdminList.set(replaceIndex, newAdmin);
3857                 }
3858                 saveSettingsLocked(userHandle);
3859                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3860                         /* adminExtras= */ null, /* result= */ null);
3861             });
3862         }
3863     }
3864 
3865     private void loadAdminDataAsync() {
3866         mInjector.postOnSystemServerInitThreadPool(() -> {
3867             pushActiveAdminPackages();
3868             mUsageStatsManagerInternal.onAdminDataAvailable();
3869             pushAllMeteredRestrictedPackages();
3870             mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable();
3871         });
3872     }
3873 
3874     private void pushActiveAdminPackages() {
3875         synchronized (getLockObject()) {
3876             final List<UserInfo> users = mUserManager.getUsers();
3877             for (int i = users.size() - 1; i >= 0; --i) {
3878                 final int userId = users.get(i).id;
3879                 mUsageStatsManagerInternal.setActiveAdminApps(
3880                         getActiveAdminPackagesLocked(userId), userId);
3881             }
3882         }
3883     }
3884 
3885     private void pushAllMeteredRestrictedPackages() {
3886         synchronized (getLockObject()) {
3887             final List<UserInfo> users = mUserManager.getUsers();
3888             for (int i = users.size() - 1; i >= 0; --i) {
3889                 final int userId = users.get(i).id;
3890                 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync(
3891                         getMeteredDisabledPackages(userId), userId);
3892             }
3893         }
3894     }
3895 
3896     private void pushActiveAdminPackagesLocked(int userId) {
3897         mUsageStatsManagerInternal.setActiveAdminApps(
3898                 getActiveAdminPackagesLocked(userId), userId);
3899     }
3900 
3901     private Set<String> getActiveAdminPackagesLocked(int userId) {
3902         final DevicePolicyData policy = getUserData(userId);
3903         Set<String> adminPkgs = null;
3904         for (int i = policy.mAdminList.size() - 1; i >= 0; --i) {
3905             final String pkgName = policy.mAdminList.get(i).info.getPackageName();
3906             if (adminPkgs == null) {
3907                 adminPkgs = new ArraySet<>();
3908             }
3909             adminPkgs.add(pkgName);
3910         }
3911         return adminPkgs;
3912     }
3913 
3914     private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver,
3915             ComponentName outgoingReceiver, int userHandle) {
3916         final DevicePolicyData policy = getUserData(userHandle);
3917         if (!policy.mAdminMap.containsKey(outgoingReceiver)
3918                 && policy.mAdminMap.containsKey(incomingReceiver)) {
3919             // Nothing to transfer - the incoming receiver is already the active admin.
3920             return;
3921         }
3922         final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle,
3923             /* throwForMissingPermission= */ true);
3924         final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver);
3925         final int oldAdminUid = adminToTransfer.getUid();
3926 
3927         EnforcingAdmin oldAdmin =
3928                 EnforcingAdmin.createEnterpriseEnforcingAdmin(
3929                         outgoingReceiver, userHandle, adminToTransfer);
3930         EnforcingAdmin newAdmin =
3931                 EnforcingAdmin.createEnterpriseEnforcingAdmin(
3932                         incomingReceiver, userHandle, adminToTransfer);
3933 
3934         mDevicePolicyEngine.transferPolicies(oldAdmin, newAdmin);
3935 
3936         adminToTransfer.transfer(incomingDeviceInfo);
3937         policy.mAdminMap.remove(outgoingReceiver);
3938         policy.mAdminMap.put(incomingReceiver, adminToTransfer);
3939         if (policy.mPasswordOwner == oldAdminUid) {
3940             policy.mPasswordOwner = adminToTransfer.getUid();
3941         }
3942         transferSubscriptionOwnership(outgoingReceiver, incomingReceiver);
3943         saveSettingsLocked(userHandle);
3944         sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3945                 null, null);
3946     }
3947 
3948     private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info,
3949             DevicePolicyData policy) {
3950         if (info == null) {
3951             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3952         }
3953         if (!info.getActivityInfo().applicationInfo.isInternal()) {
3954             throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3955                     + adminReceiver);
3956         }
3957         if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3958             throw new IllegalArgumentException("Instant apps cannot be device admins: "
3959                     + adminReceiver);
3960         }
3961         if (policy.mRemovingAdmins.contains(adminReceiver)) {
3962             throw new IllegalArgumentException(
3963                     "Trying to set an admin which is being removed");
3964         }
3965     }
3966 
3967     private void checkAllUsersAreAffiliatedWithDevice() {
3968         Preconditions.checkCallAuthorization(areAllUsersAffiliatedWithDeviceLocked(),
3969                 "operation not allowed when device has unaffiliated users");
3970     }
3971 
3972     @Override
3973     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3974         if (!mHasFeature) {
3975             return false;
3976         }
3977         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3978 
3979         final CallerIdentity caller = getCallerIdentity();
3980         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3981 
3982         synchronized (getLockObject()) {
3983             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3984         }
3985     }
3986 
3987     @Override
3988     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3989         if (!mHasFeature) {
3990             return false;
3991         }
3992         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3993 
3994         final CallerIdentity caller = getCallerIdentity();
3995         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3996 
3997         synchronized (getLockObject()) {
3998             DevicePolicyData policyData = getUserData(userHandle);
3999             return policyData.mRemovingAdmins.contains(adminReceiver);
4000         }
4001     }
4002 
4003     @Override
4004     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
4005         if (!mHasFeature) {
4006             return false;
4007         }
4008         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4009 
4010         final CallerIdentity caller = getCallerIdentity();
4011         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4012         Preconditions.checkCallAuthorization(
4013                 isCallingFromPackage(adminReceiver.getPackageName(), caller.getUid())
4014                         || isSystemUid(caller));
4015 
4016         synchronized (getLockObject()) {
4017             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
4018             if (administrator == null) {
4019                 throw new SecurityException("No active admin " + adminReceiver);
4020             }
4021             return administrator.info.usesPolicy(policyId);
4022         }
4023     }
4024 
4025     @Override
4026     @SuppressWarnings("unchecked")
4027     public List<ComponentName> getActiveAdmins(int userHandle) {
4028         if (!mHasFeature) {
4029             return Collections.EMPTY_LIST;
4030         }
4031         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4032 
4033         final CallerIdentity caller = getCallerIdentity();
4034         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4035 
4036         synchronized (getLockObject()) {
4037             DevicePolicyData policy = getUserData(userHandle);
4038             final int N = policy.mAdminList.size();
4039             if (N <= 0) {
4040                 return null;
4041             }
4042             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
4043             for (int i=0; i<N; i++) {
4044                 res.add(policy.mAdminList.get(i).info.getComponent());
4045             }
4046             return res;
4047         }
4048     }
4049 
4050     @Override
4051     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
4052         if (!mHasFeature) {
4053             return false;
4054         }
4055         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4056 
4057         final CallerIdentity caller = getCallerIdentity();
4058         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4059 
4060         synchronized (getLockObject()) {
4061             DevicePolicyData policy = getUserData(userHandle);
4062             final int N = policy.mAdminList.size();
4063             for (int i=0; i<N; i++) {
4064                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
4065                     return true;
4066                 }
4067             }
4068             return false;
4069         }
4070     }
4071 
4072     @Override
4073     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
4074         if (!mHasFeature) {
4075             return;
4076         }
4077         Objects.requireNonNull(adminReceiver, "ComponentName is null");
4078         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
4079                         || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS),
4080                 "Caller must be shell or hold MANAGE_PROFILE_AND_DEVICE_OWNERS to call "
4081                         + "forceRemoveActiveAdmin");
4082         mInjector.binderWithCleanCallingIdentity(() -> {
4083             boolean isOrgOwnedProfile = false;
4084             synchronized (getLockObject()) {
4085                 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
4086                     throw new SecurityException("Attempt to remove non-test admin "
4087                             + adminReceiver + " " + userHandle);
4088                 }
4089 
4090                 // If admin is a device or profile owner tidy that up first.
4091                 if (isDeviceOwner(adminReceiver, userHandle)) {
4092                     clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
4093                 }
4094                 if (isProfileOwner(adminReceiver, userHandle)) {
4095                     isOrgOwnedProfile = isProfileOwnerOfOrganizationOwnedDevice(userHandle);
4096                     final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
4097                             userHandle, /* parent */ false);
4098                     clearProfileOwnerLocked(admin, userHandle);
4099                 }
4100             }
4101             // Remove the admin skipping sending the broadcast.
4102             removeAdminArtifacts(adminReceiver, userHandle);
4103 
4104             // In case of PO on org owned device, clean device-wide policies and restrictions.
4105             if (isOrgOwnedProfile) {
4106                 final UserHandle parentUser = UserHandle.of(getProfileParentId(userHandle));
4107                 clearOrgOwnedProfileOwnerUserRestrictions(parentUser);
4108                 clearOrgOwnedProfileOwnerDeviceWidePolicies(parentUser.getIdentifier());
4109             }
4110 
4111             Slogf.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
4112         });
4113     }
4114 
4115     private void clearOrgOwnedProfileOwnerUserRestrictions(UserHandle parentUserHandle) {
4116         mUserManager.setUserRestriction(
4117                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, false, parentUserHandle);
4118         mUserManager.setUserRestriction(
4119                 UserManager.DISALLOW_ADD_USER, false, parentUserHandle);
4120     }
4121 
4122     private void clearDeviceOwnerUserRestriction(UserHandle userHandle) {
4123         for (int userId : mUserManagerInternal.getUserIds()) {
4124             UserHandle user = UserHandle.of(userId);
4125             // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the
4126             // original state
4127             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, user)) {
4128                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER,
4129                         false, user);
4130             }
4131             // When a device owner is set, the system automatically restricts adding a
4132             // managed profile.
4133             // Remove this restriction when the device owner is cleared.
4134             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
4135                     user)) {
4136                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
4137                         false,
4138                         user);
4139             }
4140             // When a device owner is set, the system automatically restricts adding a
4141             // clone profile.
4142             // Remove this restriction when the device owner is cleared.
4143             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE, user)) {
4144                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
4145                         false, user);
4146             }
4147 
4148             // When a device owner is set, the system automatically restricts adding a
4149             // private profile.
4150             // Remove this restriction when the device owner is cleared.
4151             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE,
4152                     user)) {
4153                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE,
4154                         false, user);
4155             }
4156         }
4157 
4158     }
4159 
4160     /**
4161      * Return if a given package has testOnly="true", in which case we'll relax certain rules
4162      * for CTS.
4163      *
4164      * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
4165      * to check wehter an active admin is test-only or not.
4166      *
4167      * The system allows this flag to be changed when an app is updated, which is not good
4168      * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
4169      * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
4170      */
4171     private boolean isPackageTestOnly(String packageName, int userHandle) {
4172         final ApplicationInfo ai;
4173         try {
4174             ai = mInjector.getIPackageManager().getApplicationInfo(packageName,
4175                     (PackageManager.MATCH_DIRECT_BOOT_AWARE
4176                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
4177         } catch (RemoteException e) {
4178             throw new IllegalStateException(e);
4179         }
4180         if (ai == null) {
4181             throw new IllegalStateException("Couldn't find package: "
4182                     + packageName + " on user " + userHandle);
4183         }
4184         return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
4185     }
4186 
4187     /**
4188      * See {@link #isPackageTestOnly}.
4189      */
4190     private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
4191         final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4192         return (admin != null) && admin.testOnlyAdmin;
4193     }
4194 
4195     @Override
4196     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
4197         if (!mHasFeature) {
4198             return;
4199         }
4200         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4201 
4202         final CallerIdentity caller = hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)
4203                 ? getCallerIdentity() : getCallerIdentity(adminReceiver);
4204         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4205         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_ACTIVE_ADMIN);
4206         enforceUserUnlocked(userHandle);
4207 
4208         ActiveAdmin admin;
4209         synchronized (getLockObject()) {
4210             admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
4211             if (admin == null) {
4212                 return;
4213             }
4214             // Active device/profile owners must remain active admins.
4215             if (isDeviceOwner(adminReceiver, userHandle)
4216                     || isProfileOwner(adminReceiver, userHandle)) {
4217                 Slogf.e(LOG_TAG, "Device/profile owner cannot be removed: component="
4218                         + adminReceiver);
4219                 return;
4220             }
4221             mInjector.binderWithCleanCallingIdentity(() ->
4222                     removeActiveAdminLocked(adminReceiver, userHandle));
4223         }
4224         mDevicePolicyEngine.removePoliciesForAdmin(
4225                 EnforcingAdmin.createEnterpriseEnforcingAdmin(
4226                         adminReceiver, userHandle, admin));
4227     }
4228 
4229     private boolean canSetPasswordQualityOnParent(String packageName, final CallerIdentity caller) {
4230         return !mInjector.isChangeEnabled(
4231                 PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT, packageName, caller.getUserId())
4232             || isProfileOwnerOfOrganizationOwnedDevice(caller);
4233     }
4234 
4235     private boolean isPasswordLimitingAdminTargetingP(CallerIdentity caller) {
4236         if (!caller.hasAdminComponent()) {
4237             return false;
4238         }
4239 
4240         synchronized (getLockObject()) {
4241             return getActiveAdminWithPolicyForUidLocked(
4242                     caller.getComponentName(), DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD,
4243                     caller.getUid()) != null;
4244         }
4245     }
4246 
4247     private boolean notSupportedOnAutomotive(String method) {
4248         if (mIsAutomotive) {
4249             Slogf.i(LOG_TAG, "%s is not supported on automotive builds", method);
4250             return true;
4251         }
4252         return false;
4253     }
4254 
4255     @Override
4256     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
4257         if (!mHasFeature || notSupportedOnAutomotive("setPasswordQuality")) {
4258             return;
4259         }
4260         Objects.requireNonNull(who, "ComponentName is null");
4261         validateQualityConstant(quality);
4262 
4263         final CallerIdentity caller = getCallerIdentity(who);
4264         Preconditions.checkCallAuthorization(
4265                 isProfileOwner(caller) || isDefaultDeviceOwner(caller)
4266                         || isSystemUid(caller) || isPasswordLimitingAdminTargetingP(caller));
4267 
4268         if (parent) {
4269             Preconditions.checkCallAuthorization(
4270                     canSetPasswordQualityOnParent(who.getPackageName(), caller),
4271                     "Profile Owner may not apply password quality requirements device-wide");
4272         }
4273 
4274         final int userId = caller.getUserId();
4275         EnforcingAdmin enforcingAdmin = null;
4276         synchronized (getLockObject()) {
4277             ActiveAdmin ap = getActiveAdminForCallerLocked(
4278                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4279 
4280             if (Flags.unmanagedModeMigration()) {
4281                 enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(who,
4282                         userId,
4283                         getActiveAdminForCallerLocked(who,
4284                                 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD));
4285             }
4286             // If setPasswordQuality is called on the parent, ensure that
4287             // the primary admin does not have password complexity state (this is an
4288             // unsupported state).
4289             if (parent) {
4290                 final boolean hasComplexitySet;
4291                 if (Flags.unmanagedModeMigration()) {
4292                     Integer complexity = mDevicePolicyEngine.getLocalPolicySetByAdmin(
4293                             PolicyDefinition.PASSWORD_COMPLEXITY,
4294                             enforcingAdmin,
4295                             userId);
4296                     hasComplexitySet = complexity != null && complexity != PASSWORD_COMPLEXITY_NONE;
4297                 } else {
4298                     final ActiveAdmin primaryAdmin = getActiveAdminForCallerLocked(
4299                             who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, false);
4300                     hasComplexitySet = primaryAdmin.mPasswordComplexity != PASSWORD_COMPLEXITY_NONE;
4301                 }
4302 
4303                 Preconditions.checkState(!hasComplexitySet,
4304                         "Cannot set password quality when complexity is set on the primary admin."
4305                         + " Set the primary admin's complexity to NONE first.");
4306             }
4307             final EnforcingAdmin enforcingAdminFinal = enforcingAdmin;
4308             mInjector.binderWithCleanCallingIdentity(() -> {
4309                 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4310                 if (passwordPolicy.quality != quality) {
4311                     passwordPolicy.quality = quality;
4312                     if (Flags.unmanagedModeMigration()) {
4313                         int affectedUser = parent ? getProfileParentId(userId) : userId;
4314                         mDevicePolicyEngine.removeLocalPolicy(PolicyDefinition.PASSWORD_COMPLEXITY,
4315                                 enforcingAdminFinal, affectedUser);
4316                     } else {
4317                         ap.mPasswordComplexity = PASSWORD_COMPLEXITY_NONE;
4318                     }
4319                     resetInactivePasswordRequirementsIfRPlus(userId, ap);
4320                     updatePasswordValidityCheckpointLocked(userId, parent);
4321                     updatePasswordQualityCacheForUserGroup(userId);
4322                     saveSettingsLocked(userId);
4323                 }
4324                 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4325             });
4326         }
4327         DevicePolicyEventLogger
4328                 .createEvent(DevicePolicyEnums.SET_PASSWORD_QUALITY)
4329                 .setAdmin(who)
4330                 .setInt(quality)
4331                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
4332                 .write();
4333     }
4334 
4335     private boolean passwordQualityInvocationOrderCheckEnabled(String packageName, int userId) {
4336         return mInjector.isChangeEnabled(ADMIN_APP_PASSWORD_COMPLEXITY, packageName, userId);
4337     }
4338 
4339     /**
4340      * For admins targeting R+ reset various password constraints to default values when quality is
4341      * set to a value that makes those constraints that have no effect.
4342      */
4343     private void resetInactivePasswordRequirementsIfRPlus(int userId, ActiveAdmin admin) {
4344         if (passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(), userId)) {
4345             final PasswordPolicy policy = admin.mPasswordPolicy;
4346             if (policy.quality < PASSWORD_QUALITY_NUMERIC) {
4347                 policy.length = PasswordPolicy.DEF_MINIMUM_LENGTH;
4348             }
4349             if (policy.quality < PASSWORD_QUALITY_COMPLEX) {
4350                 policy.letters = PasswordPolicy.DEF_MINIMUM_LETTERS;
4351                 policy.upperCase = PasswordPolicy.DEF_MINIMUM_UPPER_CASE;
4352                 policy.lowerCase = PasswordPolicy.DEF_MINIMUM_LOWER_CASE;
4353                 policy.numeric = PasswordPolicy.DEF_MINIMUM_NUMERIC;
4354                 policy.symbols = PasswordPolicy.DEF_MINIMUM_SYMBOLS;
4355                 policy.nonLetter = PasswordPolicy.DEF_MINIMUM_NON_LETTER;
4356             }
4357         }
4358     }
4359 
4360     /**
4361      * Updates a flag that tells us whether the user's password currently satisfies the
4362      * requirements set by all of the user's active admins.
4363      * This should be called whenever the password or the admin policies have changed. The caller
4364      * is responsible for calling {@link #saveSettingsLocked} to persist the change.
4365      *
4366      * @return the set of user IDs that have been affected
4367      */
4368     @GuardedBy("getLockObject()")
4369     private Set<Integer> updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) {
4370         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
4371         final int credentialOwner = getCredentialOwner(userHandle, parent);
4372         DevicePolicyData policy = getUserData(credentialOwner);
4373         PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
4374         // Update the checkpoint only if the user's password metrics is known
4375         if (metrics != null) {
4376             final int userToCheck = getProfileParentUserIfRequested(userHandle, parent);
4377             final boolean newCheckpoint = isPasswordSufficientForUserWithoutCheckpointLocked(
4378                     metrics, userToCheck);
4379             if (newCheckpoint != policy.mPasswordValidAtLastCheckpoint) {
4380                 policy.mPasswordValidAtLastCheckpoint = newCheckpoint;
4381                 affectedUserIds.add(credentialOwner);
4382             }
4383         }
4384         return affectedUserIds;
4385     }
4386 
4387     /**
4388      * Update password quality values in policy cache for all users in the same user group as
4389      * the given user. The cached password quality for user X is the aggregated quality among all
4390      * admins who have influence of user X's screenlock, i.e. it's equivalent to the return value of
4391      * getPasswordQuality(null, user X, false).
4392      *
4393      * Caches for all users in the same user group often need to be updated alltogether because a
4394      * user's admin policy can affect another's aggregated password quality in some situation.
4395      * For example a managed profile's policy will affect the parent user if the profile has unified
4396      * challenge. A profile can also explicitly set a parent password quality which will affect the
4397      * aggregated password quality of the parent user.
4398      */
4399     private void updatePasswordQualityCacheForUserGroup(@UserIdInt int userId) {
4400         final List<UserInfo> users;
4401         if (userId == UserHandle.USER_ALL) {
4402             users = mUserManager.getUsers();
4403         } else {
4404             users = mUserManager.getProfiles(userId);
4405         }
4406         for (UserInfo userInfo : users) {
4407             final int currentUserId = userInfo.id;
4408             mPolicyCache.setPasswordQuality(currentUserId,
4409                     getPasswordQuality(null, currentUserId, false));
4410         }
4411     }
4412 
4413     @Override
4414     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
4415         if (!mHasFeature) {
4416             return PASSWORD_QUALITY_UNSPECIFIED;
4417         }
4418         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4419 
4420         final CallerIdentity caller = getCallerIdentity();
4421         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4422         // System caller can query policy for a particular admin.
4423         Preconditions.checkCallAuthorization(
4424                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
4425                         || canQueryAdminPolicy(caller));
4426 
4427         synchronized (getLockObject()) {
4428             int mode = PASSWORD_QUALITY_UNSPECIFIED;
4429 
4430             if (who != null) {
4431                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4432                 return admin != null ? admin.mPasswordPolicy.quality : mode;
4433             }
4434 
4435             // Return the strictest policy across all participating admins.
4436             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4437                     getProfileParentUserIfRequested(userHandle, parent));
4438             final int N = admins.size();
4439             for (int i = 0; i < N; i++) {
4440                 ActiveAdmin admin = admins.get(i);
4441                 if (mode < admin.mPasswordPolicy.quality) {
4442                     mode = admin.mPasswordPolicy.quality;
4443                 }
4444             }
4445             return mode;
4446         }
4447     }
4448 
4449     /**
4450      * @deprecated  use {@link #getResolvedLockscreenPolicy(PolicyDefinition, int)} for
4451      * coexistable policies
4452      */
4453     @GuardedBy("getLockObject()")
4454     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(int userHandle) {
4455         if (isSeparateProfileChallengeEnabled(userHandle)) {
4456 
4457             if (isPermissionCheckFlagEnabled()) {
4458                 return getActiveAdminsForAffectedUserInclPermissionBasedAdminLocked(userHandle);
4459             }
4460             // If this user has a separate challenge, only return its restrictions.
4461             return getUserDataUnchecked(userHandle).mAdminList;
4462         }
4463         // If isSeparateProfileChallengeEnabled is false and userHandle points to a managed profile
4464         // we need to query the parent user who owns the credential.
4465         if (isPermissionCheckFlagEnabled()) {
4466             return getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(getProfileParentId(userHandle),
4467                     (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
4468         } else {
4469             return getActiveAdminsForUserAndItsManagedProfilesLocked(getProfileParentId(userHandle),
4470                     (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
4471         }
4472 
4473     }
4474 
4475     /**
4476      * Returns a user's resolved lockscreen policy from all admins. This is different from normal
4477      * policy resolution because if the specified user has a work profile with unified challenge,
4478      * all policies set on the profile will also affect that user.
4479      */
4480     private <V> V getResolvedLockscreenPolicy(PolicyDefinition<V> policyDefinition, int userId) {
4481         if (isSeparateProfileChallengeEnabled(userId)) {
4482             // If this profile has a separate challenge, only return policies targeting itself.
4483             return mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
4484         }
4485         // Otherwise, this user is either a full user, or it's a profile with unified challenge.
4486         // In both cases we query the parent user who owns the credential (the parent user of a full
4487         // user is itself), plus any profile of the parent user who has unified challenge since
4488         // the policy of a unified challenge profile is enforced on the parent.
4489         return getResolvedPolicyForUserAndItsManagedProfiles(policyDefinition,
4490                 getProfileParentId(userId),
4491                 (user) -> mLockPatternUtils.isProfileWithUnifiedChallenge(user.id));
4492 
4493     }
4494     /**
4495      * Get the list of active admins for an affected user:
4496      * <ul>
4497      * <li>The active admins associated with the userHandle itself</li>
4498      * <li>The parent active admins for each managed profile associated with the userHandle</li>
4499      * <li>The permission based admin associated with the userHandle itself</li>
4500      * </ul>
4501      *
4502      * @param userHandle the affected user for whom to get the active admins
4503      * @return the list of active admins for the affected user
4504      */
4505     @GuardedBy("getLockObject()")
4506     private List<ActiveAdmin> getActiveAdminsForAffectedUserInclPermissionBasedAdminLocked(
4507             int userHandle) {
4508         List<ActiveAdmin> list;
4509 
4510         if (isManagedProfile(userHandle)) {
4511             list = getUserDataUnchecked(userHandle).mAdminList;
4512         }
4513         list = getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(userHandle,
4514                 /* shouldIncludeProfileAdmins */ (user) -> false);
4515 
4516         if (getUserData(userHandle).mPermissionBasedAdmin != null) {
4517             list.add(getUserData(userHandle).mPermissionBasedAdmin);
4518         }
4519         return list;
4520     }
4521 
4522     /**
4523      * Returns the list of admins on the given user, as well as parent admins for each managed
4524      * profile associated with the given user. Optionally also include the admin of each managed
4525      * profile.
4526      * <p> Should not be called on a profile user.
4527      *
4528      * For coexistable policy, please use
4529      * {@link #getResolvedPolicyForUserAndItsManagedProfiles(PolicyDefinition, int, Predicate)}
4530      */
4531     @GuardedBy("getLockObject()")
4532     private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesLocked(int userHandle,
4533             Predicate<UserInfo> shouldIncludeProfileAdmins) {
4534         ArrayList<ActiveAdmin> admins = new ArrayList<>();
4535         mInjector.binderWithCleanCallingIdentity(() -> {
4536             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4537                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4538                 if (userInfo.id == userHandle) {
4539                     admins.addAll(policy.mAdminList);
4540                 } else if (userInfo.isManagedProfile()) {
4541                     for (int i = 0; i < policy.mAdminList.size(); i++) {
4542                         ActiveAdmin admin = policy.mAdminList.get(i);
4543                         if (admin.hasParentActiveAdmin()) {
4544                             admins.add(admin.getParentActiveAdmin());
4545                         }
4546                         if (shouldIncludeProfileAdmins.test(userInfo)) {
4547                             admins.add(admin);
4548                         }
4549                     }
4550                 }
4551             }
4552         });
4553         return admins;
4554     }
4555 
4556     private <V> V getResolvedPolicyForUserAndItsManagedProfiles(
4557             PolicyDefinition<V> policyDefinition, int userHandle,
4558             Predicate<UserInfo> shouldIncludeProfile) {
4559         List<Integer> users = new ArrayList<>();
4560 
4561         mInjector.binderWithCleanCallingIdentity(() -> {
4562             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4563                 if (userInfo.id == userHandle) {
4564                     users.add(userInfo.id);
4565                 } else if (userInfo.isManagedProfile() && shouldIncludeProfile.test(userInfo)) {
4566                     users.add(userInfo.id);
4567                 }
4568             }
4569         });
4570         return mDevicePolicyEngine.getResolvedPolicyAcrossUsers(policyDefinition, users);
4571     }
4572 
4573     /**
4574      * Returns the list of admins on the given user, as well as parent admins for each managed
4575      * profile associated with the given user. Optionally also include the admin of each managed
4576      * profile.
4577      * <p> Should not be called on a profile user.
4578      */
4579     @GuardedBy("getLockObject()")
4580     private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesInclPermissionBasedAdminLocked(int userHandle,
4581             Predicate<UserInfo> shouldIncludeProfileAdmins) {
4582         ArrayList<ActiveAdmin> admins = new ArrayList<>();
4583         mInjector.binderWithCleanCallingIdentity(() -> {
4584             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4585                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4586                 if (userInfo.id == userHandle) {
4587                     admins.addAll(policy.mAdminList);
4588                     if (policy.mPermissionBasedAdmin != null) {
4589                         admins.add(policy.mPermissionBasedAdmin);
4590                     }
4591                 } else if (userInfo.isManagedProfile()) {
4592                     for (int i = 0; i < policy.mAdminList.size(); i++) {
4593                         ActiveAdmin admin = policy.mAdminList.get(i);
4594                         if (admin.hasParentActiveAdmin()) {
4595                             admins.add(admin.getParentActiveAdmin());
4596                         }
4597                         if (shouldIncludeProfileAdmins.test(userInfo)) {
4598                             admins.add(admin);
4599                         }
4600                     }
4601                     if (policy.mPermissionBasedAdmin != null
4602                             && shouldIncludeProfileAdmins.test(userInfo)) {
4603                         admins.add(policy.mPermissionBasedAdmin);
4604                     }
4605                 }
4606             }
4607         });
4608         return admins;
4609     }
4610 
4611     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
4612         return mInjector.binderWithCleanCallingIdentity(() ->
4613                 mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle));
4614     }
4615 
4616     @Override
4617     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
4618         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLength")) {
4619             return;
4620         }
4621         Objects.requireNonNull(who, "ComponentName is null");
4622         final int userId = mInjector.userHandleGetCallingUserId();
4623         synchronized (getLockObject()) {
4624             ActiveAdmin ap = getActiveAdminForCallerLocked(
4625                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4626             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_NUMERIC, "setPasswordMinimumLength");
4627             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4628             if (passwordPolicy.length != length) {
4629                 passwordPolicy.length = length;
4630                 updatePasswordValidityCheckpointLocked(userId, parent);
4631                 saveSettingsLocked(userId);
4632             }
4633             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4634         }
4635         DevicePolicyEventLogger
4636                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LENGTH)
4637                 .setAdmin(who)
4638                 .setInt(length)
4639                 .write();
4640     }
4641 
4642     private void ensureMinimumQuality(
4643             int userId, ActiveAdmin admin, int minimumQuality, String operation) {
4644         mInjector.binderWithCleanCallingIdentity(() -> {
4645             // This check will also take care of the case where the password requirements
4646             // are specified as complexity rather than quality: When a password complexity
4647             // is set, the quality is reset to "unspecified" which will be below any value
4648             // of minimumQuality.
4649             if (admin.mPasswordPolicy.quality < minimumQuality
4650                     && passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(),
4651                     userId)) {
4652                 throw new IllegalStateException(String.format(
4653                         "password quality should be at least %d for %s",
4654                         minimumQuality, operation));
4655             }
4656         });
4657     }
4658 
4659     @Override
4660     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
4661         return getStrictestPasswordRequirement(who, userHandle, parent,
4662                 admin -> admin.mPasswordPolicy.length, PASSWORD_QUALITY_NUMERIC);
4663     }
4664 
4665     @Override
4666     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
4667         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4668             return;
4669         }
4670         Objects.requireNonNull(who, "ComponentName is null");
4671         final int userId = mInjector.userHandleGetCallingUserId();
4672         synchronized (getLockObject()) {
4673             ActiveAdmin ap = getActiveAdminForCallerLocked(
4674                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4675             if (ap.passwordHistoryLength != length) {
4676                 ap.passwordHistoryLength = length;
4677                 updatePasswordValidityCheckpointLocked(userId, parent);
4678                 saveSettingsLocked(userId);
4679             }
4680         }
4681         if (SecurityLog.isLoggingEnabled()) {
4682             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4683             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET,
4684                     who.getPackageName(), userId, affectedUserId, length);
4685         }
4686     }
4687 
4688     @Override
4689     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
4690         if (!mLockPatternUtils.hasSecureLockScreen()) {
4691             return 0;
4692         }
4693         return getStrictestPasswordRequirement(who, userHandle, parent,
4694                 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
4695     }
4696 
4697     @Override
4698     public void setPasswordExpirationTimeout(ComponentName who, String callerPackageName,
4699             long timeout, boolean parent) {
4700         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4701             return;
4702         }
4703         if (!isPermissionCheckFlagEnabled()) {
4704             Objects.requireNonNull(who, "ComponentName is null");
4705         }
4706 
4707         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
4708         int userHandle = mInjector.userHandleGetCallingUserId();
4709         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
4710         synchronized (getLockObject()) {
4711             ActiveAdmin ap;
4712             if (isPermissionCheckFlagEnabled()) {
4713                 CallerIdentity caller = getCallerIdentity(who, callerPackageName);
4714                 ap = enforcePermissionAndGetEnforcingAdmin(
4715                         who, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
4716                         caller.getPackageName(), affectedUserId)
4717                         .getActiveAdmin();
4718             } else {
4719                 ap = getActiveAdminForCallerLocked(
4720                         who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
4721             }
4722             // Calling this API automatically bumps the expiration date
4723             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4724             ap.passwordExpirationDate = expiration;
4725             ap.passwordExpirationTimeout = timeout;
4726             if (timeout > 0L) {
4727                 Slogf.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
4728                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
4729                         .format(new Date(expiration)));
4730             }
4731             saveSettingsLocked(userHandle);
4732 
4733             // in case this is the first one, set the alarm on the appropriate user.
4734             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
4735         }
4736         if (SecurityLog.isLoggingEnabled()) {
4737             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, callerPackageName,
4738                     userHandle, affectedUserId, timeout);
4739         }
4740     }
4741 
4742     /**
4743      * Return a single admin's expiration cycle time, or the min of all cycle times.
4744      * Returns 0 if not configured.
4745      */
4746     @Override
4747     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
4748         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4749             return 0L;
4750         }
4751         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4752 
4753         final CallerIdentity caller = getCallerIdentity(who);
4754         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4755 
4756         synchronized (getLockObject()) {
4757             long timeout = 0L;
4758 
4759             if (who != null) {
4760                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4761                 return admin != null ? admin.passwordExpirationTimeout : timeout;
4762             }
4763 
4764             // Return the strictest policy across all participating admins.
4765             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4766                     getProfileParentUserIfRequested(userHandle, parent));
4767             final int N = admins.size();
4768             for (int i = 0; i < N; i++) {
4769                 ActiveAdmin admin = admins.get(i);
4770                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
4771                         && timeout > admin.passwordExpirationTimeout)) {
4772                     timeout = admin.passwordExpirationTimeout;
4773                 }
4774             }
4775             return timeout;
4776         }
4777     }
4778 
4779     @Override
4780     public boolean addCrossProfileWidgetProvider(ComponentName admin, String callerPackageName,
4781             String packageName) {
4782         CallerIdentity caller;
4783 
4784         if (isPermissionCheckFlagEnabled()) {
4785             caller = getCallerIdentity(admin, callerPackageName);
4786         } else {
4787             caller = getCallerIdentity(admin);
4788         }
4789         ActiveAdmin activeAdmin;
4790 
4791         if (isPermissionCheckFlagEnabled()) {
4792             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
4793                     admin,
4794                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
4795                     caller.getPackageName(),
4796                     caller.getUserId());
4797             activeAdmin = enforcingAdmin.getActiveAdmin();
4798         } else {
4799             Objects.requireNonNull(admin, "ComponentName is null");
4800             Preconditions.checkCallAuthorization(isProfileOwner(caller));
4801             synchronized (getLockObject()) {
4802                 activeAdmin = getProfileOwnerLocked(caller.getUserId());
4803             }
4804         }
4805         List<String> changedProviders = null;
4806 
4807         synchronized (getLockObject()) {
4808             if (activeAdmin.crossProfileWidgetProviders == null) {
4809                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
4810             }
4811             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4812             if (!providers.contains(packageName)) {
4813                 providers.add(packageName);
4814                 changedProviders = new ArrayList<>(providers);
4815                 saveSettingsLocked(caller.getUserId());
4816             }
4817         }
4818 
4819         DevicePolicyEventLogger
4820                 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_WIDGET_PROVIDER)
4821                 .setAdmin(caller.getPackageName())
4822                 .write();
4823 
4824         if (changedProviders != null) {
4825             mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(),
4826                     changedProviders);
4827             return true;
4828         }
4829 
4830         return false;
4831     }
4832 
4833     @Override
4834     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String callerPackageName,
4835             String packageName) {
4836         CallerIdentity caller;
4837         if (isPermissionCheckFlagEnabled()) {
4838             caller = getCallerIdentity(admin, callerPackageName);
4839         } else {
4840             caller = getCallerIdentity(admin);
4841         }
4842 
4843         ActiveAdmin activeAdmin;
4844 
4845         if (isPermissionCheckFlagEnabled()) {
4846             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
4847                     admin,
4848                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
4849                     caller.getPackageName(),
4850                     caller.getUserId());
4851             activeAdmin = enforcingAdmin.getActiveAdmin();
4852         } else {
4853             Objects.requireNonNull(admin, "ComponentName is null");
4854             Preconditions.checkCallAuthorization(isProfileOwner(caller));
4855             synchronized (getLockObject()) {
4856                 activeAdmin = getProfileOwnerLocked(caller.getUserId());
4857             }
4858         }
4859         List<String> changedProviders = null;
4860 
4861         synchronized (getLockObject()) {
4862             if (activeAdmin.crossProfileWidgetProviders == null
4863                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4864                 return false;
4865             }
4866             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4867             if (providers.remove(packageName)) {
4868                 changedProviders = new ArrayList<>(providers);
4869                 saveSettingsLocked(caller.getUserId());
4870             }
4871         }
4872 
4873         DevicePolicyEventLogger
4874                 .createEvent(DevicePolicyEnums.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER)
4875                 .setAdmin(caller.getPackageName())
4876                 .write();
4877 
4878         if (changedProviders != null) {
4879             mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(),
4880                     changedProviders);
4881             return true;
4882         }
4883 
4884         return false;
4885     }
4886 
4887     @Override
4888     public List<String> getCrossProfileWidgetProviders(ComponentName admin,
4889             String callerPackageName) {
4890         CallerIdentity caller;
4891         if (isPermissionCheckFlagEnabled()) {
4892             caller = getCallerIdentity(admin, callerPackageName);
4893         } else {
4894             caller = getCallerIdentity(admin);
4895         }
4896         ActiveAdmin activeAdmin;
4897 
4898         if (isPermissionCheckFlagEnabled()) {
4899             EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
4900                     admin,
4901                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
4902                     caller.getPackageName(),
4903                     caller.getUserId());
4904             activeAdmin = enforcingAdmin.getActiveAdmin();
4905         } else {
4906             Objects.requireNonNull(admin, "ComponentName is null");
4907             Preconditions.checkCallAuthorization(isProfileOwner(caller));
4908             synchronized (getLockObject()) {
4909                 activeAdmin = getProfileOwnerLocked(caller.getUserId());
4910             }
4911         }
4912 
4913         synchronized (getLockObject()) {
4914             if (activeAdmin.crossProfileWidgetProviders == null
4915                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4916                 return null;
4917             }
4918             if (mInjector.binderIsCallingUidMyUid()) {
4919                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
4920             } else {
4921                 return activeAdmin.crossProfileWidgetProviders;
4922             }
4923         }
4924     }
4925 
4926     /**
4927      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
4928      * Returns 0 if not configured.
4929      */
4930     @GuardedBy("getLockObject()")
4931     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
4932         long timeout = 0L;
4933 
4934         if (who != null) {
4935             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4936             return admin != null ? admin.passwordExpirationDate : timeout;
4937         }
4938 
4939         // Return the strictest policy across all participating admins.
4940         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4941                 getProfileParentUserIfRequested(userHandle, parent));
4942         final int N = admins.size();
4943         for (int i = 0; i < N; i++) {
4944             ActiveAdmin admin = admins.get(i);
4945             if (timeout == 0L || (admin.passwordExpirationDate != 0
4946                     && timeout > admin.passwordExpirationDate)) {
4947                 timeout = admin.passwordExpirationDate;
4948             }
4949         }
4950         return timeout;
4951     }
4952 
4953     @Override
4954     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
4955         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4956             return 0L;
4957         }
4958         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4959 
4960         final CallerIdentity caller = getCallerIdentity(who);
4961         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4962 
4963         synchronized (getLockObject()) {
4964             return getPasswordExpirationLocked(who, userHandle, parent);
4965         }
4966     }
4967 
4968     @Override
4969     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
4970         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumUpperCase")) {
4971             return;
4972         }
4973         Objects.requireNonNull(who, "ComponentName is null");
4974         final int userId = mInjector.userHandleGetCallingUserId();
4975         synchronized (getLockObject()) {
4976             final ActiveAdmin ap = getActiveAdminForCallerLocked(
4977                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4978             ensureMinimumQuality(
4979                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumUpperCase");
4980             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4981             if (passwordPolicy.upperCase != length) {
4982                 passwordPolicy.upperCase = length;
4983                 updatePasswordValidityCheckpointLocked(userId, parent);
4984                 saveSettingsLocked(userId);
4985             }
4986             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4987         }
4988         DevicePolicyEventLogger
4989                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_UPPER_CASE)
4990                 .setAdmin(who)
4991                 .setInt(length)
4992                 .write();
4993     }
4994 
4995     @Override
4996     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
4997         return getStrictestPasswordRequirement(who, userHandle, parent,
4998                 admin -> admin.mPasswordPolicy.upperCase, PASSWORD_QUALITY_COMPLEX);
4999     }
5000 
5001     @Override
5002     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
5003         if (notSupportedOnAutomotive("setPasswordMinimumLowerCase")) {
5004             return;
5005         }
5006         Objects.requireNonNull(who, "ComponentName is null");
5007         final int userId = mInjector.userHandleGetCallingUserId();
5008         synchronized (getLockObject()) {
5009             ActiveAdmin ap = getActiveAdminForCallerLocked(
5010                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5011             ensureMinimumQuality(
5012                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLowerCase");
5013             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
5014             if (passwordPolicy.lowerCase != length) {
5015                 passwordPolicy.lowerCase = length;
5016                 updatePasswordValidityCheckpointLocked(userId, parent);
5017                 saveSettingsLocked(userId);
5018             }
5019             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
5020         }
5021         DevicePolicyEventLogger
5022                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LOWER_CASE)
5023                 .setAdmin(who)
5024                 .setInt(length)
5025                 .write();
5026     }
5027 
5028     @Override
5029     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
5030         return getStrictestPasswordRequirement(who, userHandle, parent,
5031                 admin -> admin.mPasswordPolicy.lowerCase, PASSWORD_QUALITY_COMPLEX);
5032     }
5033 
5034     @Override
5035     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
5036         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLetters")) {
5037             return;
5038         }
5039         Objects.requireNonNull(who, "ComponentName is null");
5040         final int userId = mInjector.userHandleGetCallingUserId();
5041         synchronized (getLockObject()) {
5042             ActiveAdmin ap = getActiveAdminForCallerLocked(
5043                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5044             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLetters");
5045             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
5046             if (passwordPolicy.letters != length) {
5047                 passwordPolicy.letters = length;
5048                 updatePasswordValidityCheckpointLocked(userId, parent);
5049                 saveSettingsLocked(userId);
5050             }
5051             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
5052         }
5053         DevicePolicyEventLogger
5054                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LETTERS)
5055                 .setAdmin(who)
5056                 .setInt(length)
5057                 .write();
5058     }
5059 
5060     @Override
5061     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
5062         return getStrictestPasswordRequirement(who, userHandle, parent,
5063                 admin -> admin.mPasswordPolicy.letters, PASSWORD_QUALITY_COMPLEX);
5064     }
5065 
5066     @Override
5067     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
5068         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNumeric")) {
5069             return;
5070         }
5071         Objects.requireNonNull(who, "ComponentName is null");
5072         final int userId = mInjector.userHandleGetCallingUserId();
5073         synchronized (getLockObject()) {
5074             ActiveAdmin ap = getActiveAdminForCallerLocked(
5075                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5076             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNumeric");
5077             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
5078             if (passwordPolicy.numeric != length) {
5079                 passwordPolicy.numeric = length;
5080                 updatePasswordValidityCheckpointLocked(userId, parent);
5081                 saveSettingsLocked(userId);
5082             }
5083             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
5084         }
5085         DevicePolicyEventLogger
5086                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NUMERIC)
5087                 .setAdmin(who)
5088                 .setInt(length)
5089                 .write();
5090     }
5091 
5092     @Override
5093     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
5094         return getStrictestPasswordRequirement(who, userHandle, parent,
5095                 admin -> admin.mPasswordPolicy.numeric, PASSWORD_QUALITY_COMPLEX);
5096     }
5097 
5098     @Override
5099     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
5100         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumSymbols")) {
5101             return;
5102         }
5103         Objects.requireNonNull(who, "ComponentName is null");
5104         final int userId = mInjector.userHandleGetCallingUserId();
5105         synchronized (getLockObject()) {
5106             ActiveAdmin ap = getActiveAdminForCallerLocked(
5107                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5108             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumSymbols");
5109             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
5110             if (passwordPolicy.symbols != length) {
5111                 ap.mPasswordPolicy.symbols = length;
5112                 updatePasswordValidityCheckpointLocked(userId, parent);
5113                 saveSettingsLocked(userId);
5114             }
5115             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
5116         }
5117         DevicePolicyEventLogger
5118                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_SYMBOLS)
5119                 .setAdmin(who)
5120                 .setInt(length)
5121                 .write();
5122     }
5123 
5124     @Override
5125     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
5126         return getStrictestPasswordRequirement(who, userHandle, parent,
5127                 admin -> admin.mPasswordPolicy.symbols, PASSWORD_QUALITY_COMPLEX);
5128     }
5129 
5130     @Override
5131     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
5132         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNonLetter")) {
5133             return;
5134         }
5135         Objects.requireNonNull(who, "ComponentName is null");
5136         final int userId = mInjector.userHandleGetCallingUserId();
5137         synchronized (getLockObject()) {
5138             ActiveAdmin ap = getActiveAdminForCallerLocked(
5139                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5140             ensureMinimumQuality(
5141                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNonLetter");
5142             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
5143             if (passwordPolicy.nonLetter != length) {
5144                 ap.mPasswordPolicy.nonLetter = length;
5145                 updatePasswordValidityCheckpointLocked(userId, parent);
5146                 saveSettingsLocked(userId);
5147             }
5148             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
5149         }
5150         DevicePolicyEventLogger
5151                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NON_LETTER)
5152                 .setAdmin(who)
5153                 .setInt(length)
5154                 .write();
5155     }
5156 
5157     @Override
5158     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
5159         return getStrictestPasswordRequirement(who, userHandle, parent,
5160                 admin -> admin.mPasswordPolicy.nonLetter, PASSWORD_QUALITY_COMPLEX);
5161     }
5162 
5163     /**
5164      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
5165      */
5166     private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
5167             boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
5168         if (!mHasFeature) {
5169             return 0;
5170         }
5171         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5172 
5173         final CallerIdentity caller = getCallerIdentity(who);
5174         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5175 
5176         synchronized (getLockObject()) {
5177             if (who != null) {
5178                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5179                 return admin != null ? getter.apply(admin) : 0;
5180             }
5181 
5182             int maxValue = 0;
5183             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5184                     getProfileParentUserIfRequested(userHandle, parent));
5185             final int N = admins.size();
5186             for (int i = 0; i < N; i++) {
5187                 final ActiveAdmin admin = admins.get(i);
5188                 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
5189                     continue;
5190                 }
5191                 final Integer adminValue = getter.apply(admin);
5192                 if (adminValue > maxValue) {
5193                     maxValue = adminValue;
5194                 }
5195             }
5196             return maxValue;
5197         }
5198     }
5199 
5200     /**
5201      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
5202      */
5203     @Override
5204     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
5205             boolean deviceWideOnly) {
5206         final CallerIdentity caller = getCallerIdentity();
5207         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle)
5208                 && (isSystemUid(caller)
5209                     // Accept any permission that ILockSettings#setLockCredential() accepts.
5210                     || hasCallingOrSelfPermission(permission.SET_INITIAL_LOCK)
5211                     || hasCallingOrSelfPermission(permission.SET_AND_VERIFY_LOCKSCREEN_CREDENTIALS)
5212                     || hasCallingOrSelfPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)));
5213         return getPasswordMinimumMetricsUnchecked(userHandle, deviceWideOnly);
5214     }
5215 
5216     private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId) {
5217         return getPasswordMinimumMetricsUnchecked(userId, false);
5218     }
5219 
5220     private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId,
5221             boolean deviceWideOnly) {
5222         if (!mHasFeature) {
5223             new PasswordMetrics(CREDENTIAL_TYPE_NONE);
5224         }
5225         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
5226         if (deviceWideOnly) {
5227             Preconditions.checkArgument(!isManagedProfile(userId));
5228         }
5229 
5230         ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>();
5231         final List<ActiveAdmin> admins;
5232         synchronized (getLockObject()) {
5233             if (deviceWideOnly) {
5234                 admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userId,
5235                         /* shouldIncludeProfileAdmins */ (user) -> false);
5236             } else {
5237                 admins = getActiveAdminsForLockscreenPoliciesLocked(userId);
5238             }
5239             for (ActiveAdmin admin : admins) {
5240                 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
5241             }
5242         }
5243         return PasswordMetrics.merge(adminMetrics);
5244     }
5245 
5246     @Override
5247     public boolean isActivePasswordSufficient(
5248             String callerPackageName, int userHandle, boolean parent) {
5249         if (!mHasFeature) {
5250             return true;
5251         }
5252         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5253 
5254         final CallerIdentity caller = getCallerIdentity();
5255         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5256         enforceUserUnlocked(userHandle, parent);
5257 
5258         synchronized (getLockObject()) {
5259             if (isPermissionCheckFlagEnabled()) {
5260                 int affectedUser = parent ? getProfileParentId(userHandle) : userHandle;
5261                 enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5262                         callerPackageName, affectedUser);
5263             } else {
5264                 // This API can only be called by an active device admin,
5265                 // so try to retrieve it to check that the caller is one.
5266                 getActiveAdminForCallerLocked(
5267                         null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
5268             }
5269 
5270             int credentialOwner = getCredentialOwner(userHandle, parent);
5271             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
5272             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
5273             final int userToCheck = getProfileParentUserIfRequested(userHandle, parent);
5274             boolean activePasswordSufficientForUserLocked = isActivePasswordSufficientForUserLocked(
5275                     policy.mPasswordValidAtLastCheckpoint, metrics, userToCheck);
5276             return activePasswordSufficientForUserLocked;
5277         }
5278     }
5279 
5280     @Override
5281     public boolean isActivePasswordSufficientForDeviceRequirement() {
5282         if (!mHasFeature) {
5283             return true;
5284         }
5285         final CallerIdentity caller = getCallerIdentity();
5286         Preconditions.checkCallAuthorization(isProfileOwner(caller));
5287 
5288         final int profileUserId = caller.getUserId();
5289         Preconditions.checkCallingUser(isManagedProfile(profileUserId));
5290 
5291         // This method is always called on the parent DPM instance to check if its password (i.e.
5292         // the device password) is sufficient for all explicit password requirement set on it
5293         // So retrieve the parent user Id to which the device password belongs.
5294         final int parentUser = getProfileParentId(profileUserId);
5295         enforceUserUnlocked(parentUser);
5296 
5297         final boolean isSufficient;
5298         synchronized (getLockObject()) {
5299 
5300             int complexity = getAggregatedPasswordComplexityLocked(parentUser, true);
5301             PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(parentUser, true);
5302 
5303             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(parentUser);
5304             final List<PasswordValidationError> passwordValidationErrors =
5305                     PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics);
5306             isSufficient = passwordValidationErrors.isEmpty();
5307         }
5308         DevicePolicyEventLogger
5309                 .createEvent(DevicePolicyEnums.IS_ACTIVE_PASSWORD_SUFFICIENT_FOR_DEVICE)
5310                 .setStrings(mOwners.getProfileOwnerComponent(caller.getUserId()).getPackageName())
5311                 .write();
5312         return isSufficient;
5313     }
5314 
5315     @Override
5316     public boolean isUsingUnifiedPassword(ComponentName admin) {
5317         if (!mHasFeature) {
5318             return true;
5319         }
5320         Objects.requireNonNull(admin, "ComponentName is null");
5321 
5322         final CallerIdentity caller = getCallerIdentity(admin);
5323         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
5324                 || isProfileOwner(caller));
5325         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
5326 
5327         return !isSeparateProfileChallengeEnabled(caller.getUserId());
5328     }
5329 
5330     @Override
5331     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
5332         if (!mHasFeature) {
5333             return true;
5334         }
5335         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5336 
5337         final CallerIdentity caller = getCallerIdentity();
5338         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5339         Preconditions.checkCallAuthorization(!isManagedProfile(userHandle),
5340                 "You can not check password sufficiency for a managed profile, userId = %d",
5341                 userHandle);
5342         enforceUserUnlocked(userHandle);
5343 
5344         synchronized (getLockObject()) {
5345             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(userHandle);
5346 
5347             // Combine password policies across the user and its profiles. Profile admins are
5348             // included if the profile is to be unified or currently has unified challenge
5349             List<ActiveAdmin> admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
5350                     /* shouldIncludeProfileAdmins */ (user) -> user.id == profileUser
5351                     || !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
5352             ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>(admins.size());
5353             if (Flags.unmanagedModeMigration()) {
5354                 for (ActiveAdmin admin: admins) {
5355                     adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
5356                 }
5357                 Integer maxRequiredComplexity = getResolvedPolicyForUserAndItsManagedProfiles(
5358                         PolicyDefinition.PASSWORD_COMPLEXITY,
5359                         userHandle,
5360                         /* shouldIncludeProfileAdmins */ (user) -> user.id == profileUser
5361                                 || !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
5362                 return PasswordMetrics.validatePasswordMetrics(
5363                         PasswordMetrics.merge(adminMetrics),
5364                         maxRequiredComplexity != null
5365                                 ? maxRequiredComplexity : PASSWORD_COMPLEXITY_NONE,
5366                         metrics).isEmpty();
5367             } else {
5368                 int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE;
5369                 for (ActiveAdmin admin : admins) {
5370                     adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
5371                     maxRequiredComplexity = Math.max(maxRequiredComplexity,
5372                             admin.mPasswordComplexity);
5373                 }
5374                 return PasswordMetrics.validatePasswordMetrics(PasswordMetrics.merge(adminMetrics),
5375                         maxRequiredComplexity, metrics).isEmpty();
5376             }
5377         }
5378     }
5379 
5380     private boolean isActivePasswordSufficientForUserLocked(
5381             boolean passwordValidAtLastCheckpoint, @Nullable PasswordMetrics metrics,
5382             int userHandle) {
5383         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) {
5384             // Before user enters their password for the first time after a reboot, return the
5385             // value of this flag, which tells us whether the password was valid the last time
5386             // settings were saved.  If DPC changes password requirements on boot so that the
5387             // current password no longer meets the requirements, this value will be stale until
5388             // the next time the password is entered.
5389             return passwordValidAtLastCheckpoint;
5390         }
5391 
5392         if (metrics == null) {
5393             // Called on a FBE device when the user password exists but its metrics is unknown.
5394             // This shouldn't happen since we enforce the user to be unlocked (which would result
5395             // in the metrics known to the framework on a FBE device) at all call sites.
5396             throw new IllegalStateException("isActivePasswordSufficient called on FBE-locked user");
5397         }
5398 
5399         return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle);
5400     }
5401 
5402     /**
5403      * Returns {@code true} if the password represented by the {@code metrics} argument
5404      * sufficiently fulfills the password requirements for the user corresponding to
5405      * {@code userId}.
5406      */
5407     private boolean isPasswordSufficientForUserWithoutCheckpointLocked(
5408             @NonNull PasswordMetrics metrics, @UserIdInt int userId) {
5409         final int complexity = getAggregatedPasswordComplexityLocked(userId);
5410         PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userId);
5411         final List<PasswordValidationError> passwordValidationErrors =
5412                 PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics);
5413         return passwordValidationErrors.isEmpty();
5414     }
5415 
5416     @Override
5417     @PasswordComplexity
5418     public int getPasswordComplexity(boolean parent) {
5419         final CallerIdentity caller = getCallerIdentity();
5420         DevicePolicyEventLogger
5421                 .createEvent(DevicePolicyEnums.GET_USER_PASSWORD_COMPLEXITY_LEVEL)
5422                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT,
5423                         mInjector.getPackageManager().getPackagesForUid(caller.getUid()))
5424                 .write();
5425 
5426         enforceUserUnlocked(caller.getUserId());
5427         if (parent) {
5428             Preconditions.checkCallAuthorization(
5429                     isDefaultDeviceOwner(caller) || isProfileOwner(caller) || isSystemUid(caller),
5430                     "Only profile owner, device owner and system may call this method on parent.");
5431         } else {
5432             if (isPermissionCheckFlagEnabled()) {
5433                 Preconditions.checkCallAuthorization(
5434                         hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY)
5435                                 || hasCallingOrSelfPermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS)
5436                                 || isDefaultDeviceOwner(caller) || isProfileOwner(caller),
5437                         "Must have " + REQUEST_PASSWORD_COMPLEXITY + " or " +
5438                                 MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS
5439                                 + " permissions, or be a profile owner or device owner.");
5440             } else {
5441                 Preconditions.checkCallAuthorization(
5442                         hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY)
5443                                 || isDefaultDeviceOwner(caller) || isProfileOwner(caller),
5444                         "Must have " + REQUEST_PASSWORD_COMPLEXITY
5445                                 + " permission, or be a profile owner or device owner.");
5446             }
5447         }
5448 
5449         synchronized (getLockObject()) {
5450             final int credentialOwner = getCredentialOwner(caller.getUserId(), parent);
5451             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
5452             return metrics == null ? PASSWORD_COMPLEXITY_NONE : metrics.determineComplexity();
5453         }
5454     }
5455 
5456     @Override
5457     public void setRequiredPasswordComplexity(
5458             String callerPackageName, int passwordComplexity, boolean calledOnParent) {
5459         if (!mHasFeature) {
5460             return;
5461         }
5462         final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW,
5463                 PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH);
5464         Preconditions.checkArgument(allowedModes.contains(passwordComplexity),
5465                 "Provided complexity is not one of the allowed values.");
5466 
5467         if (!Flags.unmanagedModeMigration()) {
5468             setRequiredPasswordComplexityPreCoexistence(callerPackageName, passwordComplexity,
5469                     calledOnParent);
5470             return;
5471         }
5472 
5473         CallerIdentity caller = getCallerIdentity(callerPackageName);
5474         int affectedUser = calledOnParent
5475                 ? getProfileParentId(caller.getUserId()) : caller.getUserId();
5476         EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(null,
5477                 MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS, caller.getPackageName(),
5478                 caller.getUserId());
5479         Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
5480 
5481         ActiveAdmin activeAdmin = admin.getActiveAdmin();
5482 
5483         // We require the caller to explicitly clear any password quality requirements set
5484         // on the parent DPM instance, to avoid the case where password requirements are
5485         // specified in the form of quality on the parent but complexity on the profile
5486         // itself.
5487         if (!calledOnParent) {
5488             final boolean hasQualityRequirementsOnParent = activeAdmin.hasParentActiveAdmin()
5489                     && activeAdmin.getParentActiveAdmin().mPasswordPolicy.quality
5490                     != PASSWORD_QUALITY_UNSPECIFIED;
5491             Preconditions.checkState(!hasQualityRequirementsOnParent,
5492                     "Password quality is set on the parent when attempting to set password"
5493                             + "complexity. Clear the quality by setting the password quality "
5494                             + "on the parent to PASSWORD_QUALITY_UNSPECIFIED first");
5495         }
5496 
5497         if (passwordComplexity != PASSWORD_COMPLEXITY_NONE) {
5498             mDevicePolicyEngine.setLocalPolicy(
5499                     PolicyDefinition.PASSWORD_COMPLEXITY,
5500                     admin,
5501                     new IntegerPolicyValue(passwordComplexity),
5502                     affectedUser);
5503         } else {
5504             mDevicePolicyEngine.removeLocalPolicy(
5505                     PolicyDefinition.PASSWORD_COMPLEXITY,
5506                     admin,
5507                     affectedUser);
5508         }
5509 
5510         mInjector.binderWithCleanCallingIdentity(() -> {
5511             // Reset the password policy.
5512             if (calledOnParent) {
5513                 activeAdmin.getParentActiveAdmin().mPasswordPolicy = new PasswordPolicy();
5514             } else {
5515                 activeAdmin.mPasswordPolicy = new PasswordPolicy();
5516             }
5517             synchronized (getLockObject()) {
5518                 updatePasswordValidityCheckpointLocked(caller.getUserId(), calledOnParent);
5519             }
5520             updatePasswordQualityCacheForUserGroup(caller.getUserId());
5521             saveSettingsLocked(caller.getUserId());
5522         });
5523 
5524 
5525         DevicePolicyEventLogger
5526                 .createEvent(DevicePolicyEnums.SET_PASSWORD_COMPLEXITY)
5527                 .setAdmin(caller.getPackageName())
5528                 .setInt(passwordComplexity)
5529                 .setBoolean(calledOnParent)
5530                 .write();
5531         logPasswordComplexityRequiredIfSecurityLogEnabled(caller.getPackageName(),
5532                 caller.getUserId(), calledOnParent, passwordComplexity);
5533     }
5534 
5535     private void setRequiredPasswordComplexityPreCoexistence(
5536             String callerPackageName, int passwordComplexity, boolean calledOnParent) {
5537         CallerIdentity caller = getCallerIdentity(callerPackageName);
5538         if (!isPermissionCheckFlagEnabled()) {
5539             Preconditions.checkCallAuthorization(
5540                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
5541             Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
5542         }
5543 
5544         synchronized (getLockObject()) {
5545             ActiveAdmin admin;
5546             if (isPermissionCheckFlagEnabled()) {
5547                 // TODO: Make sure this returns the parent of the fake admin
5548                 // TODO: Deal with null componentname
5549                 int affectedUser = calledOnParent
5550                         ? getProfileParentId(caller.getUserId()) : caller.getUserId();
5551                 admin = enforcePermissionAndGetEnforcingAdmin(
5552                         null, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5553                         caller.getPackageName(), affectedUser).getActiveAdmin();
5554             } else {
5555                 admin = getParentOfAdminIfRequired(
5556                         getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), calledOnParent);
5557             }
5558 
5559             if (admin.mPasswordComplexity != passwordComplexity) {
5560                 // We require the caller to explicitly clear any password quality requirements set
5561                 // on the parent DPM instance, to avoid the case where password requirements are
5562                 // specified in the form of quality on the parent but complexity on the profile
5563                 // itself.
5564                 if (!calledOnParent) {
5565                     final boolean hasQualityRequirementsOnParent = admin.hasParentActiveAdmin()
5566                             && admin.getParentActiveAdmin().mPasswordPolicy.quality
5567                             != PASSWORD_QUALITY_UNSPECIFIED;
5568                     Preconditions.checkState(!hasQualityRequirementsOnParent,
5569                             "Password quality is set on the parent when attempting to set password"
5570                             + "complexity. Clear the quality by setting the password quality "
5571                             + "on the parent to PASSWORD_QUALITY_UNSPECIFIED first");
5572                 }
5573 
5574                 mInjector.binderWithCleanCallingIdentity(() -> {
5575                     admin.mPasswordComplexity = passwordComplexity;
5576                     // Reset the password policy.
5577                     admin.mPasswordPolicy = new PasswordPolicy();
5578                     updatePasswordValidityCheckpointLocked(caller.getUserId(), calledOnParent);
5579                     updatePasswordQualityCacheForUserGroup(caller.getUserId());
5580                     saveSettingsLocked(caller.getUserId());
5581                 });
5582 
5583 
5584                 //TODO(b/276855301): caller.getPackageName() will be null when the coexistence flags are
5585                 // turned off. Change back to caller.getPackageName once this API is unflagged.
5586                 DevicePolicyEventLogger
5587                         .createEvent(DevicePolicyEnums.SET_PASSWORD_COMPLEXITY)
5588                         .setAdmin(admin.info.getPackageName())
5589                         .setInt(passwordComplexity)
5590                         .setBoolean(calledOnParent)
5591                         .write();
5592             }
5593             logPasswordComplexityRequiredIfSecurityLogEnabled(caller.getPackageName(),
5594                     caller.getUserId(), calledOnParent, passwordComplexity);
5595         }
5596     }
5597 
5598     private void logPasswordComplexityRequiredIfSecurityLogEnabled(String adminPackageName,
5599             int userId,
5600             boolean parent, int complexity) {
5601         if (SecurityLog.isLoggingEnabled()) {
5602             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
5603             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_REQUIRED,
5604                     adminPackageName, userId, affectedUserId, complexity);
5605         }
5606     }
5607     @GuardedBy("getLockObject()")
5608     private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle) {
5609         return getAggregatedPasswordComplexityLocked(userHandle, false);
5610     }
5611 
5612     @GuardedBy("getLockObject()")
5613     private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle,
5614             boolean deviceWideOnly) {
5615         if (Flags.unmanagedModeMigration()) {
5616             return getAggregatedPasswordComplexity(userHandle, deviceWideOnly);
5617         } else {
5618             return getAggregatedPasswordComplexityPreCoexistenceLocked(userHandle, deviceWideOnly);
5619         }
5620     }
5621 
5622     private int getAggregatedPasswordComplexity(@UserIdInt int userHandle, boolean deviceWideOnly) {
5623         ensureLocked();
5624         Integer result;
5625         if (deviceWideOnly) {
5626             result = getResolvedPolicyForUserAndItsManagedProfiles(
5627                     PolicyDefinition.PASSWORD_COMPLEXITY,
5628                     userHandle,
5629                     /* shouldIncludeProfile */ (user) -> false);
5630         } else {
5631             result = getResolvedLockscreenPolicy(PolicyDefinition.PASSWORD_COMPLEXITY, userHandle);
5632         }
5633         return result != null ? result : PASSWORD_COMPLEXITY_NONE;
5634     }
5635 
5636     @GuardedBy("getLockObject()")
5637     private int getAggregatedPasswordComplexityPreCoexistenceLocked(@UserIdInt int userHandle,
5638             boolean deviceWideOnly) {
5639         ensureLocked();
5640         final List<ActiveAdmin> admins;
5641         if (deviceWideOnly) {
5642             admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
5643                     /* shouldIncludeProfileAdmins */ (user) -> false);
5644         } else {
5645             admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
5646         }
5647         int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE;
5648         for (ActiveAdmin admin : admins) {
5649             maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity);
5650         }
5651         return maxRequiredComplexity;
5652     }
5653 
5654     @Override
5655     public int getRequiredPasswordComplexity(String callerPackageName, boolean calledOnParent) {
5656         if (!mHasFeature) {
5657             return PASSWORD_COMPLEXITY_NONE;
5658         }
5659 
5660         if (Flags.unmanagedModeMigration()) {
5661             final CallerIdentity caller = getCallerIdentity(callerPackageName);
5662             int affectedUser = calledOnParent ? getProfileParentId(caller.getUserId())
5663                     : caller.getUserId();
5664             enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5665                     callerPackageName, affectedUser);
5666 
5667             Integer complexity = mDevicePolicyEngine.getResolvedPolicy(
5668                     PolicyDefinition.PASSWORD_COMPLEXITY,
5669                     affectedUser);
5670             return complexity != null ? complexity : PASSWORD_COMPLEXITY_NONE;
5671         } else {
5672             final CallerIdentity caller = getCallerIdentity();
5673 
5674             Preconditions.checkCallAuthorization(
5675                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
5676 
5677             Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
5678 
5679             synchronized (getLockObject()) {
5680                 final ActiveAdmin requiredAdmin = getParentOfAdminIfRequired(
5681                         getDeviceOrProfileOwnerAdminLocked(caller.getUserId()), calledOnParent);
5682                 return requiredAdmin.mPasswordComplexity;
5683             }
5684         }
5685     }
5686 
5687     @Override
5688     public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
5689         if (!mHasFeature) {
5690             return PASSWORD_COMPLEXITY_NONE;
5691         }
5692 
5693         final CallerIdentity caller = getCallerIdentity();
5694         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
5695 
5696         synchronized (getLockObject()) {
5697             return getAggregatedPasswordComplexityLocked(userId, deviceWideOnly);
5698         }
5699     }
5700 
5701 
5702     @Override
5703     public int getCurrentFailedPasswordAttempts(
5704             String callerPackageName, int userHandle, boolean parent) {
5705         if (!mLockPatternUtils.hasSecureLockScreen()) {
5706             return 0;
5707         }
5708         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5709 
5710         final CallerIdentity caller = getCallerIdentity();
5711         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5712 
5713         synchronized (getLockObject()) {
5714             if (!isSystemUid(caller)) {
5715                 // This API can be called by an active device admin or by keyguard code.
5716                 if (!hasCallingPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)) {
5717                     if (isPermissionCheckFlagEnabled()) {
5718                         int affectedUser = parent ? getProfileParentId(userHandle) : userHandle;
5719                         enforcePermission(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
5720                                 callerPackageName, affectedUser);
5721                     } else {
5722                         getActiveAdminForCallerLocked(
5723                                 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
5724                     }
5725                 }
5726             }
5727 
5728             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
5729 
5730             return policy.mFailedPasswordAttempts;
5731         }
5732     }
5733 
5734     @Override
5735     public void setMaximumFailedPasswordsForWipe(
5736             ComponentName who, String callerPackageName, int num, boolean parent) {
5737         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5738             return;
5739         }
5740 
5741         if (!isPermissionCheckFlagEnabled()) {
5742             Objects.requireNonNull(who, "ComponentName is null");
5743         }
5744 
5745 
5746         int userId = mInjector.userHandleGetCallingUserId();
5747         int affectedUserId = parent ? getProfileParentId(userId) : userId;
5748 
5749         synchronized (getLockObject()) {
5750             ActiveAdmin ap;
5751             if (isPermissionCheckFlagEnabled()) {
5752                 CallerIdentity caller = getCallerIdentity(who, callerPackageName);
5753                 ap = enforcePermissionAndGetEnforcingAdmin(
5754                         who,
5755                         /*permission=*/ MANAGE_DEVICE_POLICY_WIPE_DATA,
5756                         /* adminPolicy=*/ DeviceAdminInfo.USES_POLICY_WIPE_DATA,
5757                         caller.getPackageName(), affectedUserId).getActiveAdmin();
5758             } else {
5759                 // This API can only be called by an active device admin,
5760                 // so try to retrieve it to check that the caller is one.
5761                 getActiveAdminForCallerLocked(
5762                         who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
5763                 ap = getActiveAdminForCallerLocked(
5764                         who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
5765             }
5766 
5767             if (ap.maximumFailedPasswordsForWipe != num) {
5768                 ap.maximumFailedPasswordsForWipe = num;
5769                 saveSettingsLocked(userId);
5770             }
5771         }
5772         if (SecurityLog.isLoggingEnabled()) {
5773             SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, callerPackageName,
5774                     userId, affectedUserId, num);
5775         }
5776     }
5777 
5778     @Override
5779     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
5780         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5781             return 0;
5782         }
5783         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5784 
5785         final CallerIdentity caller = getCallerIdentity();
5786         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5787         // System caller can query policy for a particular admin.
5788         Preconditions.checkCallAuthorization(
5789                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
5790                         || canQueryAdminPolicy(caller));
5791 
5792         synchronized (getLockObject()) {
5793             ActiveAdmin admin = (who != null)
5794                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
5795                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
5796             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
5797         }
5798     }
5799 
5800     @Override
5801     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
5802         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5803             return UserHandle.USER_NULL;
5804         }
5805         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5806 
5807         final CallerIdentity caller = getCallerIdentity();
5808         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5809 
5810         synchronized (getLockObject()) {
5811             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5812                     userHandle, parent);
5813             return admin != null ? getUserIdToWipeForFailedPasswords(admin) : UserHandle.USER_NULL;
5814         }
5815     }
5816 
5817     /**
5818      * Returns the admin with the strictest policy on maximum failed passwords for:
5819      * <ul>
5820      *   <li>this user if it has a separate profile challenge, or
5821      *   <li>this user and all profiles that don't have their own challenge otherwise.
5822      * </ul>
5823      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
5824      * the primary profile. Policy of a PO on an organization-owned device applies to the primary
5825      * profile.
5826      * Returns {@code null} if no participating admin has that policy set.
5827      */
5828     @GuardedBy("getLockObject()")
5829     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
5830             int userHandle, boolean parent) {
5831         int count = 0;
5832         ActiveAdmin strictestAdmin = null;
5833 
5834         // Return the strictest policy across all participating admins.
5835         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5836                 getProfileParentUserIfRequested(userHandle, parent));
5837         final int N = admins.size();
5838         for (int i = 0; i < N; i++) {
5839             ActiveAdmin admin = admins.get(i);
5840             if (admin.maximumFailedPasswordsForWipe ==
5841                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
5842                 continue;  // No max number of failed passwords policy set for this profile.
5843             }
5844 
5845             // We always favor the primary profile if several profiles have the same value set.
5846             final int userId = getUserIdToWipeForFailedPasswords(admin);
5847             if (count == 0 ||
5848                     count > admin.maximumFailedPasswordsForWipe ||
5849                     (count == admin.maximumFailedPasswordsForWipe &&
5850                             getUserInfo(userId).isPrimary())) {
5851                 count = admin.maximumFailedPasswordsForWipe;
5852                 strictestAdmin = admin;
5853             }
5854         }
5855         return strictestAdmin;
5856     }
5857 
5858     private UserInfo getUserInfo(@UserIdInt int userId) {
5859         return mInjector.binderWithCleanCallingIdentity(() -> mUserManager.getUserInfo(userId));
5860     }
5861 
5862     private boolean setPasswordPrivileged(@NonNull String password, int flags,
5863             CallerIdentity caller) {
5864         // Only allow setting password on an unsecured user
5865         if (isLockScreenSecureUnchecked(caller.getUserId())) {
5866             throw new SecurityException("Cannot change current password");
5867         }
5868         return resetPasswordInternal(password, 0, null, flags, caller);
5869     }
5870 
5871     @Override
5872     public boolean resetPassword(@Nullable String password, int flags) throws RemoteException {
5873         if (!mLockPatternUtils.hasSecureLockScreen()) {
5874             Slogf.w(LOG_TAG, "Cannot reset password when the device has no lock screen");
5875             return false;
5876         }
5877         if (password == null) password = "";
5878         final CallerIdentity caller = getCallerIdentity();
5879         final int userHandle = caller.getUserId();
5880 
5881         // As of R, only privileged caller holding RESET_PASSWORD can call resetPassword() to
5882         // set password to an unsecured user.
5883         if (hasCallingPermission(permission.RESET_PASSWORD)) {
5884             final boolean result = setPasswordPrivileged(password, flags, caller);
5885             if (result) {
5886                 DevicePolicyEventLogger
5887                         .createEvent(DevicePolicyEnums.RESET_PASSWORD)
5888                         .write();
5889             }
5890             return result;
5891         }
5892 
5893         // If caller has PO (or DO) throw or fail silently depending on its target SDK level.
5894         if (isDefaultDeviceOwner(caller) || isProfileOwner(caller)) {
5895             synchronized (getLockObject()) {
5896                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
5897                 if (getTargetSdk(admin.info.getPackageName(), userHandle) < Build.VERSION_CODES.O) {
5898                     Slogf.e(LOG_TAG, "DPC can no longer call resetPassword()");
5899                     return false;
5900                 }
5901                 throw new SecurityException("Device admin can no longer call resetPassword()");
5902             }
5903         }
5904 
5905         // Caller is not DO or PO, could either be unauthorized or Device Admin.
5906         synchronized (getLockObject()) {
5907             // Legacy device admin cannot call resetPassword either
5908             ActiveAdmin admin = getActiveAdminForCallerLocked(
5909                     null, DeviceAdminInfo.USES_POLICY_RESET_PASSWORD, false);
5910             Preconditions.checkCallAuthorization(admin != null,
5911                     "Unauthorized caller cannot call resetPassword.");
5912             if (getTargetSdk(admin.info.getPackageName(),
5913                     userHandle) <= android.os.Build.VERSION_CODES.M) {
5914                 Slogf.e(LOG_TAG, "Device admin can no longer call resetPassword()");
5915                 return false;
5916             }
5917             throw new SecurityException("Device admin can no longer call resetPassword()");
5918         }
5919     }
5920 
5921     private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
5922             int flags, CallerIdentity caller) {
5923         final int callingUid = caller.getUid();
5924         final int userHandle = UserHandle.getUserId(callingUid);
5925         final boolean isPin = PasswordMetrics.isNumericOnly(password);
5926         final LockscreenCredential newCredential;
5927         if (isPin) {
5928             newCredential = LockscreenCredential.createPin(password);
5929         } else {
5930             newCredential = LockscreenCredential.createPasswordOrNone(password);
5931         }
5932         synchronized (getLockObject()) {
5933             final PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userHandle);
5934             final int complexity = getAggregatedPasswordComplexityLocked(userHandle);
5935             final List<PasswordValidationError> validationErrors =
5936                     PasswordMetrics.validateCredential(minMetrics, complexity, newCredential);
5937             if (!validationErrors.isEmpty()) {
5938                 Slogf.w(LOG_TAG, "Failed to reset password due to constraint violation: %s",
5939                         validationErrors.get(0));
5940                 return false;
5941             }
5942         }
5943 
5944         DevicePolicyData policy = getUserData(userHandle);
5945         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
5946             Slogf.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
5947             return false;
5948         }
5949 
5950         boolean callerIsDeviceOwnerAdmin = isDefaultDeviceOwner(caller);
5951         boolean doNotAskCredentialsOnBoot =
5952                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
5953         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
5954             setDoNotAskCredentialsOnBoot();
5955         }
5956 
5957         // Don't do this with the lock held, because it is going to call
5958         // back in to the service.
5959         final long ident = mInjector.binderClearCallingIdentity();
5960         try {
5961             if (tokenHandle == 0 || token == null) {
5962                 if (!mLockPatternUtils.setLockCredential(newCredential,
5963                         LockscreenCredential.createNone(), userHandle)) {
5964                     return false;
5965                 }
5966             } else {
5967                 if (!mLockPatternUtils.setLockCredentialWithToken(newCredential, tokenHandle,
5968                         token, userHandle)) {
5969                     return false;
5970                 }
5971             }
5972             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
5973             if (requireEntry) {
5974                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
5975                         UserHandle.USER_ALL);
5976             }
5977             synchronized (getLockObject()) {
5978                 int newOwner = requireEntry ? callingUid : -1;
5979                 if (policy.mPasswordOwner != newOwner) {
5980                     policy.mPasswordOwner = newOwner;
5981                     saveSettingsLocked(userHandle);
5982                 }
5983             }
5984         } finally {
5985             mInjector.binderRestoreCallingIdentity(ident);
5986         }
5987         return true;
5988     }
5989 
5990     private boolean isLockScreenSecureUnchecked(int userId) {
5991         return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.isSecure(userId));
5992     }
5993 
5994     private void setDoNotAskCredentialsOnBoot() {
5995         synchronized (getLockObject()) {
5996             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
5997             if (!policyData.mDoNotAskCredentialsOnBoot) {
5998                 policyData.mDoNotAskCredentialsOnBoot = true;
5999                 saveSettingsLocked(UserHandle.USER_SYSTEM);
6000             }
6001         }
6002     }
6003 
6004     @Override
6005     public boolean getDoNotAskCredentialsOnBoot() {
6006         Preconditions.checkCallAuthorization(
6007                 hasCallingOrSelfPermission(permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT));
6008         synchronized (getLockObject()) {
6009             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6010             return policyData.mDoNotAskCredentialsOnBoot;
6011         }
6012     }
6013 
6014     @Override
6015     public void setMaximumTimeToLock(ComponentName who, String callerPackageName,
6016             long timeMs, boolean parent) {
6017         if (!mHasFeature) {
6018             return;
6019         }
6020         if (!isPermissionCheckFlagEnabled()) {
6021             Objects.requireNonNull(who, "ComponentName is null");
6022         }
6023         int userHandle = mInjector.userHandleGetCallingUserId();
6024         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
6025         synchronized (getLockObject()) {
6026             ActiveAdmin ap;
6027             if (isPermissionCheckFlagEnabled()) {
6028                 CallerIdentity caller = getCallerIdentity(who, callerPackageName);
6029                 ap = enforcePermissionAndGetEnforcingAdmin(
6030                         who,
6031                         /*permission=*/ MANAGE_DEVICE_POLICY_LOCK,
6032                         /*AdminPolicy=*/DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
6033                         caller.getPackageName(),
6034                         affectedUserId).getActiveAdmin();
6035             } else {
6036                 ap = getActiveAdminForCallerLocked(
6037                         who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
6038             }
6039 
6040             if (ap.maximumTimeToUnlock != timeMs) {
6041                 ap.maximumTimeToUnlock = timeMs;
6042                 saveSettingsLocked(userHandle);
6043                 updateMaximumTimeToLockLocked(userHandle);
6044             }
6045         }
6046         if (SecurityLog.isLoggingEnabled()) {
6047             SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
6048                     callerPackageName, userHandle, affectedUserId, timeMs);
6049         }
6050     }
6051 
6052     @GuardedBy("getLockObject()")
6053     private void updateMaximumTimeToLockLocked(@UserIdInt int userId) {
6054         // Update the profile's timeout
6055         if (isManagedProfile(userId)) {
6056             updateProfileLockTimeoutLocked(userId);
6057         }
6058 
6059         mInjector.binderWithCleanCallingIdentity(() -> {
6060             // Update the device timeout
6061             final int parentId = getProfileParentId(userId);
6062             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(
6063                     getActiveAdminsForLockscreenPoliciesLocked(parentId));
6064 
6065             final DevicePolicyData policy = getUserDataUnchecked(parentId);
6066             if (policy.mLastMaximumTimeToLock == timeMs) {
6067                 return;
6068             }
6069             policy.mLastMaximumTimeToLock = timeMs;
6070 
6071             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
6072                 // Make sure KEEP_SCREEN_ON is disabled, since that
6073                 // would allow bypassing of the maximum time to lock.
6074                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
6075             }
6076             getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(parentId, timeMs);
6077         });
6078     }
6079 
6080     @GuardedBy("getLockObject()")
6081     private void updateProfileLockTimeoutLocked(@UserIdInt int userId) {
6082         final long timeMs;
6083         if (isSeparateProfileChallengeEnabled(userId)) {
6084             timeMs = getMaximumTimeToLockPolicyFromAdmins(
6085                     getActiveAdminsForLockscreenPoliciesLocked(userId));
6086         } else {
6087             timeMs = Long.MAX_VALUE;
6088         }
6089 
6090         final DevicePolicyData policy = getUserDataUnchecked(userId);
6091         if (policy.mLastMaximumTimeToLock == timeMs) {
6092             return;
6093         }
6094         policy.mLastMaximumTimeToLock = timeMs;
6095 
6096         mInjector.binderWithCleanCallingIdentity(() ->
6097                 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
6098                         userId, policy.mLastMaximumTimeToLock));
6099     }
6100 
6101     @Override
6102     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
6103         if (!mHasFeature) {
6104             return 0;
6105         }
6106         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
6107 
6108         final CallerIdentity caller = getCallerIdentity();
6109         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
6110         // System caller can query policy for a particular admin.
6111         Preconditions.checkCallAuthorization(
6112                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
6113                         || canQueryAdminPolicy(caller));
6114 
6115         synchronized (getLockObject()) {
6116             if (who != null) {
6117                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
6118                 return admin != null ? admin.maximumTimeToUnlock : 0;
6119             }
6120             // Return the strictest policy across all participating admins.
6121             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
6122                     getProfileParentUserIfRequested(userHandle, parent));
6123             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins);
6124             return timeMs == Long.MAX_VALUE ? 0 : timeMs;
6125         }
6126     }
6127 
6128     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
6129         long time = Long.MAX_VALUE;
6130         for (final ActiveAdmin admin : admins) {
6131             if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) {
6132                 time = admin.maximumTimeToUnlock;
6133             }
6134         }
6135         return time;
6136     }
6137 
6138     @Override
6139     public void setRequiredStrongAuthTimeout(ComponentName who, String callerPackageName, long timeoutMs,
6140             boolean parent) {
6141         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
6142             return;
6143         }
6144         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
6145         CallerIdentity caller;
6146         if (isPermissionCheckFlagEnabled()) {
6147             caller = getCallerIdentity(who, callerPackageName);
6148         } else {
6149             caller = getCallerIdentity(who);
6150             Objects.requireNonNull(who, "ComponentName is null");
6151             Preconditions.checkCallAuthorization(
6152                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
6153         }
6154         // timeoutMs with value 0 means that the admin doesn't participate
6155         // timeoutMs is clamped to the interval in case the internal constants change in the future
6156         final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
6157         if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
6158             timeoutMs = minimumStrongAuthTimeout;
6159         }
6160         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
6161             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6162         }
6163 
6164         final int userHandle = caller.getUserId();
6165         boolean changed = false;
6166         synchronized (getLockObject()) {
6167             ActiveAdmin ap;
6168             if (isPermissionCheckFlagEnabled()) {
6169                 int affectedUser = parent
6170                         ? getProfileParentId(caller.getUserId()) : caller.getUserId();
6171                 ap = enforcePermissionAndGetEnforcingAdmin(
6172                         who, MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
6173                         caller.getPackageName(), affectedUser).getActiveAdmin();
6174             } else {
6175                 ap = getParentOfAdminIfRequired(
6176                         getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
6177             }
6178             if (ap.strongAuthUnlockTimeout != timeoutMs) {
6179                 ap.strongAuthUnlockTimeout = timeoutMs;
6180                 saveSettingsLocked(userHandle);
6181                 changed = true;
6182             }
6183         }
6184         if (changed) {
6185             mLockSettingsInternal.refreshStrongAuthTimeout(userHandle);
6186             // Refreshes the parent if profile has unified challenge, since the timeout would
6187             // also affect the parent user in this case.
6188             if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
6189                 mLockSettingsInternal.refreshStrongAuthTimeout(getProfileParentId(userHandle));
6190             }
6191         }
6192     }
6193 
6194     /**
6195      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
6196      * admins if who is null.
6197      * Returns 0 if not configured for the provided admin.
6198      */
6199     @Override
6200     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
6201         if (!mHasFeature) {
6202             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6203         }
6204         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
6205 
6206         final CallerIdentity caller = getCallerIdentity(who);
6207         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
6208 
6209         if (!mLockPatternUtils.hasSecureLockScreen()) {
6210             // No strong auth timeout on devices not supporting the
6211             // {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature
6212             return 0;
6213         }
6214         synchronized (getLockObject()) {
6215             if (who != null) {
6216                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
6217                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
6218             }
6219 
6220             // Return the strictest policy across all participating admins.
6221             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
6222                     getProfileParentUserIfRequested(userId, parent));
6223 
6224             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
6225             for (int i = 0; i < admins.size(); i++) {
6226                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
6227                 if (timeout != 0) { // take only participating admins into account
6228                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
6229                 }
6230             }
6231             return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
6232         }
6233     }
6234 
6235     private long getMinimumStrongAuthTimeoutMs() {
6236         if (!mInjector.isBuildDebuggable()) {
6237             return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
6238         }
6239         // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
6240         // name cannot be longer than 31 characters
6241         return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
6242                 MINIMUM_STRONG_AUTH_TIMEOUT_MS),
6243                 MINIMUM_STRONG_AUTH_TIMEOUT_MS);
6244     }
6245 
6246     @Override
6247     public void lockNow(int flags, String callerPackageName, boolean parent) {
6248         CallerIdentity caller;
6249         if (isUnicornFlagEnabled()) {
6250             caller = getCallerIdentity(callerPackageName);
6251         } else {
6252             caller = getCallerIdentity();
6253         }
6254 
6255         final int callingUserId = caller.getUserId();
6256         ComponentName adminComponent = null;
6257         synchronized (getLockObject()) {
6258             ActiveAdmin admin;
6259             // Make sure the caller has any active admin with the right policy or
6260             // the required permission.
6261             if (isUnicornFlagEnabled()) {
6262                 admin = enforcePermissionsAndGetEnforcingAdmin(
6263                         /* admin= */ null,
6264                         /* permissions= */ new String[]{MANAGE_DEVICE_POLICY_LOCK, LOCK_DEVICE},
6265                         /* deviceAdminPolicy= */ USES_POLICY_FORCE_LOCK,
6266                         caller.getPackageName(),
6267                         getAffectedUser(parent)
6268                  ).getActiveAdmin();
6269             } else {
6270                 admin = getActiveAdminOrCheckPermissionForCallerLocked(
6271                         null,
6272                         DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
6273                         parent,
6274                         LOCK_DEVICE);
6275             }
6276             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOCK_NOW);
6277             final long ident = mInjector.binderClearCallingIdentity();
6278             try {
6279                 adminComponent = admin == null ? null : admin.info.getComponent();
6280                 if (adminComponent != null) {
6281                     // For Profile Owners only, callers with only permission not allowed.
6282                     if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
6283                         // Evict key
6284                         Preconditions.checkCallingUser(isManagedProfile(callingUserId));
6285                         Preconditions.checkArgument(!parent,
6286                                 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
6287                         if (!isProfileOwner(adminComponent, callingUserId)) {
6288                             throw new SecurityException("Only profile owner admins can set "
6289                                     + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
6290                         }
6291                         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
6292                             throw new UnsupportedOperationException(
6293                                     "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE"
6294                                         + " devices");
6295                         }
6296                         mUserManager.evictCredentialEncryptionKey(callingUserId);
6297                     }
6298                 }
6299 
6300                 // Lock all users unless this is a managed profile with a separate challenge
6301                 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
6302                         ? UserHandle.USER_ALL : callingUserId);
6303                 mLockPatternUtils.requireStrongAuth(
6304                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
6305 
6306                 // Require authentication for the device or profile
6307                 if (userToLock == UserHandle.USER_ALL) {
6308                     if (mIsAutomotive) {
6309                         if (VERBOSE_LOG) {
6310                             Slogf.v(LOG_TAG, "lockNow(): not powering off display on automotive"
6311                                     + " build");
6312                         }
6313                     } else {
6314                         // Power off the display
6315                         mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
6316                                 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
6317                     }
6318                     mInjector.getIWindowManager().lockNow(null);
6319                 } else {
6320                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
6321                 }
6322 
6323                 if (SecurityLog.isLoggingEnabled() && adminComponent != null) {
6324                     final int affectedUserId =
6325                             parent ? getProfileParentId(callingUserId) : callingUserId;
6326                     SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK,
6327                             adminComponent.getPackageName(), callingUserId, affectedUserId);
6328                 }
6329             } catch (RemoteException e) {
6330             } finally {
6331                 mInjector.binderRestoreCallingIdentity(ident);
6332             }
6333         }
6334         DevicePolicyEventLogger
6335                 .createEvent(DevicePolicyEnums.LOCK_NOW)
6336                 .setAdmin(adminComponent)
6337                 .setInt(flags)
6338                 .write();
6339     }
6340 
6341     @Override
6342     public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
6343         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6344         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
6345     }
6346 
6347     private boolean canManageCaCerts(CallerIdentity caller) {
6348         return (caller.hasAdminComponent() && (isDefaultDeviceOwner(caller)
6349                 || isProfileOwner(caller)))
6350                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_INSTALL))
6351                 || hasCallingOrSelfPermission(MANAGE_CA_CERTIFICATES);
6352     }
6353 
6354     @Override
6355     public boolean approveCaCert(String alias, int userId, boolean approval) {
6356         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
6357 
6358         synchronized (getLockObject()) {
6359             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
6360             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
6361             if (!changed) {
6362                 return false;
6363             }
6364             saveSettingsLocked(userId);
6365         }
6366         mCertificateMonitor.onCertificateApprovalsChanged(userId);
6367         return true;
6368     }
6369 
6370     @Override
6371     public boolean isCaCertApproved(String alias, int userId) {
6372         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
6373 
6374         synchronized (getLockObject()) {
6375             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
6376         }
6377     }
6378 
6379     private Set<Integer> removeCaApprovalsIfNeeded(int userId) {
6380         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
6381         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
6382             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
6383             if (userInfo.isManagedProfile()){
6384                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
6385             }
6386             if (!isSecure) {
6387                 synchronized (getLockObject()) {
6388                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
6389                     affectedUserIds.add(userInfo.id);
6390                 }
6391                 mCertificateMonitor.onCertificateApprovalsChanged(userId);
6392             }
6393         }
6394         return affectedUserIds;
6395     }
6396 
6397     @Override
6398     public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) {
6399         if (!mHasFeature) {
6400             return false;
6401         }
6402         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
6403         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
6404         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_CA_CERT);
6405 
6406         final String alias = mInjector.binderWithCleanCallingIdentity(() -> {
6407             String installedAlias = mCertificateMonitor.installCaCert(
6408                     caller.getUserHandle(), certBuffer);
6409             DevicePolicyEventLogger
6410                     .createEvent(DevicePolicyEnums.INSTALL_CA_CERT)
6411                     .setAdmin(caller.getPackageName())
6412                     .setBoolean(/* isDelegate */ admin == null)
6413                     .write();
6414 
6415             if (mInjector.isAdminInstalledCaCertAutoApproved()
6416                     && installedAlias != null
6417                     && admin != null) {
6418                 // If device admin called this, approve cert to avoid notifications
6419                 Slogf.i(LOG_TAG, "Approving admin installed cert");
6420                 approveCaCert(
6421                         installedAlias,
6422                         caller.getUserId(),
6423                         /* approved */ true);
6424             }
6425 
6426             return installedAlias;
6427         });
6428 
6429         if (alias == null) {
6430             Slogf.w(LOG_TAG, "Problem installing cert");
6431             return false;
6432         }
6433 
6434         synchronized (getLockObject()) {
6435             getUserData(caller.getUserId()).mOwnerInstalledCaCerts.add(alias);
6436             saveSettingsLocked(caller.getUserId());
6437         }
6438         return true;
6439     }
6440 
6441     @Override
6442     public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
6443         if (!mHasFeature) {
6444             return;
6445         }
6446         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
6447         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
6448         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_UNINSTALL_CA_CERT);
6449 
6450         mInjector.binderWithCleanCallingIdentity(() -> {
6451             mCertificateMonitor.uninstallCaCerts(caller.getUserHandle(), aliases);
6452             DevicePolicyEventLogger
6453                     .createEvent(DevicePolicyEnums.UNINSTALL_CA_CERTS)
6454                     .setAdmin(caller.getPackageName())
6455                     .setBoolean(/* isDelegate */ admin == null)
6456                     .write();
6457         });
6458 
6459         synchronized (getLockObject()) {
6460             if (getUserData(caller.getUserId()).mOwnerInstalledCaCerts.removeAll(
6461                     Arrays.asList(aliases))) {
6462                 saveSettingsLocked(caller.getUserId());
6463             }
6464         }
6465     }
6466 
6467     @Override
6468     public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
6469             byte[] cert, byte[] chain, String alias, boolean requestAccess,
6470             boolean isUserSelectable) {
6471         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6472         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6473         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6474         if (isPermissionCheckFlagEnabled()) {
6475             Preconditions.checkCallAuthorization(
6476                     hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6477                             caller.getPackageName(), caller.getUserId())
6478                             || isCredentialManagementApp);
6479         }  else {
6480             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6481                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
6482                     || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
6483         }
6484         if (isCredentialManagementApp) {
6485             Preconditions.checkCallAuthorization(!isUserSelectable, "The credential "
6486                     + "management app is not allowed to install a user selectable key pair");
6487             Preconditions.checkCallAuthorization(
6488                     isAliasInCredentialManagementAppPolicy(caller, alias),
6489                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6490         }
6491         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_KEY_PAIR);
6492 
6493         final long id = mInjector.binderClearCallingIdentity();
6494         try {
6495             try (KeyChainConnection keyChainConnection =
6496                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6497                 IKeyChainService keyChain = keyChainConnection.getService();
6498                 if (!keyChain.installKeyPair(privKey, cert, chain, alias, KeyProperties.UID_SELF)) {
6499                     logInstallKeyPairFailure(caller, isCredentialManagementApp);
6500                     return false;
6501                 }
6502                 if (requestAccess) {
6503                     keyChain.setGrant(caller.getUid(), alias, true);
6504                 }
6505                 keyChain.setUserSelectable(alias, isUserSelectable);
6506                 DevicePolicyEventLogger
6507                         .createEvent(DevicePolicyEnums.INSTALL_KEY_PAIR)
6508                         .setAdmin(caller.getPackageName())
6509                         .setBoolean(/* isDelegate */ isCallerDelegate)
6510                         .setStrings(isCredentialManagementApp
6511                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6512                         .write();
6513                 return true;
6514             } catch (RemoteException | AssertionError e) {
6515                 Slogf.e(LOG_TAG, "Installing certificate", e);
6516             }
6517         } catch (InterruptedException e) {
6518             Slogf.w(LOG_TAG, "Interrupted while installing certificate", e);
6519             Thread.currentThread().interrupt();
6520         } finally {
6521             mInjector.binderRestoreCallingIdentity(id);
6522         }
6523         logInstallKeyPairFailure(caller, isCredentialManagementApp);
6524         return false;
6525     }
6526 
6527     private void logInstallKeyPairFailure(CallerIdentity caller,
6528             boolean isCredentialManagementApp) {
6529         if (!isCredentialManagementApp) {
6530             return;
6531         }
6532         DevicePolicyEventLogger
6533                 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_INSTALL_KEY_PAIR_FAILED)
6534                 .setStrings(caller.getPackageName())
6535                 .write();
6536     }
6537 
6538     @Override
6539     public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
6540         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6541         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6542         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6543         if (isPermissionCheckFlagEnabled()) {
6544             Preconditions.checkCallAuthorization(
6545                     hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6546                             caller.getPackageName(), caller.getUserId())
6547                             || isCredentialManagementApp);
6548         }  else {
6549             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6550                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
6551                     || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
6552         }
6553         if (isCredentialManagementApp) {
6554             Preconditions.checkCallAuthorization(
6555                     isAliasInCredentialManagementAppPolicy(caller, alias),
6556                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6557         }
6558         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_KEY_PAIR);
6559 
6560         final long id = Binder.clearCallingIdentity();
6561         try {
6562             try (KeyChainConnection keyChainConnection =
6563                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6564                 IKeyChainService keyChain = keyChainConnection.getService();
6565                 DevicePolicyEventLogger
6566                         .createEvent(DevicePolicyEnums.REMOVE_KEY_PAIR)
6567                         .setAdmin(caller.getPackageName())
6568                         .setBoolean(/* isDelegate */ isCallerDelegate)
6569                         .setStrings(isCredentialManagementApp
6570                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6571                         .write();
6572                 return keyChain.removeKeyPair(alias);
6573             } catch (RemoteException | AssertionError e) {
6574                 Slogf.e(LOG_TAG, "Removing keypair", e);
6575             }
6576         } catch (InterruptedException e) {
6577             Slogf.w(LOG_TAG, "Interrupted while removing keypair", e);
6578             Thread.currentThread().interrupt();
6579         } finally {
6580             Binder.restoreCallingIdentity(id);
6581         }
6582         return false;
6583     }
6584 
6585     @Override
6586     public boolean hasKeyPair(String callerPackage, String alias) {
6587         final CallerIdentity caller = getCallerIdentity(callerPackage);
6588         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6589         Preconditions.checkCallAuthorization(canInstallCertificates(caller)
6590                 || isCredentialManagementApp);
6591         if (isCredentialManagementApp) {
6592             Preconditions.checkCallAuthorization(
6593                     isAliasInCredentialManagementAppPolicy(caller, alias),
6594                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6595         }
6596 
6597         return mInjector.binderWithCleanCallingIdentity(() -> {
6598             try (KeyChainConnection keyChainConnection =
6599                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6600                 return keyChainConnection.getService().containsKeyPair(alias);
6601             } catch (RemoteException | AssertionError e) {
6602                 Slogf.e(LOG_TAG, "Querying keypair", e);
6603             } catch (InterruptedException e) {
6604                 Slogf.w(LOG_TAG, "Interrupted while querying keypair", e);
6605                 Thread.currentThread().interrupt();
6606             }
6607             return false;
6608         });
6609     }
6610 
6611     private boolean canInstallCertificates(CallerIdentity caller) {
6612         if (isPermissionCheckFlagEnabled()) {
6613             return hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6614                     caller.getPackageName(), caller.getUserId());
6615         }  else {
6616             return isProfileOwner(caller) || isDefaultDeviceOwner(caller)
6617                     || isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6618         }
6619     }
6620 
6621     private boolean canChooseCertificates(CallerIdentity caller) {
6622         return isProfileOwner(caller) || isDefaultDeviceOwner(caller)
6623                 || isCallerDelegate(caller, DELEGATION_CERT_SELECTION);
6624     }
6625 
6626     @Override
6627     public boolean setKeyGrantToWifiAuth(String callerPackage, String alias, boolean hasGrant) {
6628         Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty");
6629 
6630         final CallerIdentity caller = getCallerIdentity(callerPackage);
6631         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
6632         try {
6633             return setKeyChainGrantInternal(
6634                     alias, hasGrant, Process.WIFI_UID, caller.getUserHandle());
6635         } catch (IllegalArgumentException e) {
6636             if (mInjector.isChangeEnabled(THROW_EXCEPTION_WHEN_KEY_MISSING, caller.getPackageName(),
6637                     caller.getUserId())) {
6638                 throw e;
6639             }
6640             return false;
6641         }
6642     }
6643 
6644     @Override
6645     public boolean isKeyPairGrantedToWifiAuth(String callerPackage, String alias) {
6646         Preconditions.checkStringNotEmpty(alias, "Alias to check cannot be empty");
6647 
6648         final CallerIdentity caller = getCallerIdentity(callerPackage);
6649         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
6650 
6651         return mInjector.binderWithCleanCallingIdentity(() -> {
6652             try (KeyChainConnection keyChainConnection =
6653                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6654                 final List<String> result = new ArrayList<>();
6655                 final int[] granteeUids = keyChainConnection.getService().getGrants(alias);
6656 
6657                 for (final int uid : granteeUids) {
6658                     if (uid == Process.WIFI_UID) {
6659                         return true;
6660                     }
6661                 }
6662                 return false;
6663             } catch (RemoteException | AssertionError e) {
6664                 Slogf.e(LOG_TAG, "Querying grant to wifi auth.", e);
6665                 return false;
6666             }
6667         });
6668     }
6669 
6670     @Override
6671     public boolean setKeyGrantForApp(ComponentName who, String callerPackage, String alias,
6672             String packageName, boolean hasGrant) {
6673         Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty");
6674         Preconditions.checkStringNotEmpty(packageName, "Package to grant to cannot be empty");
6675 
6676         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6677         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6678                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
6679                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_SELECTION)));
6680 
6681         final int granteeUid;
6682         try {
6683             ApplicationInfo ai = mInjector.getIPackageManager().getApplicationInfo(
6684                     packageName, 0, caller.getUserId());
6685             Preconditions.checkArgument(ai != null,
6686                     "Provided package %s is not installed", packageName);
6687             granteeUid = ai.uid;
6688         } catch (RemoteException e) {
6689             throw new IllegalStateException("Failure getting grantee uid", e);
6690         }
6691         try {
6692             return setKeyChainGrantInternal(alias, hasGrant, granteeUid, caller.getUserHandle());
6693         } catch (IllegalArgumentException e) {
6694             if (mInjector.isChangeEnabled(THROW_EXCEPTION_WHEN_KEY_MISSING, callerPackage,
6695                     caller.getUserId())) {
6696                 throw e;
6697             }
6698             return false;
6699         }
6700     }
6701 
6702     private boolean setKeyChainGrantInternal(String alias, boolean hasGrant, int granteeUid,
6703             UserHandle userHandle) {
6704         final long id = mInjector.binderClearCallingIdentity();
6705         try {
6706             try (KeyChainConnection keyChainConnection =
6707                          KeyChain.bindAsUser(mContext, userHandle)) {
6708                 IKeyChainService keyChain = keyChainConnection.getService();
6709                 return keyChain.setGrant(granteeUid, alias, hasGrant);
6710             } catch (RemoteException | AssertionError e) {
6711                 Slogf.e(LOG_TAG, "Setting grant for package.", e);
6712                 return false;
6713             }
6714         } catch (InterruptedException e) {
6715             Slogf.w(LOG_TAG, "Interrupted while setting key grant", e);
6716             Thread.currentThread().interrupt();
6717         } finally {
6718             mInjector.binderRestoreCallingIdentity(id);
6719         }
6720         return false;
6721     }
6722 
6723     @Override
6724     public ParcelableGranteeMap getKeyPairGrants(String callerPackage, String alias) {
6725         final CallerIdentity caller = getCallerIdentity(callerPackage);
6726         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
6727 
6728         final ArrayMap<Integer, Set<String>> result = new ArrayMap<>();
6729         mInjector.binderWithCleanCallingIdentity(() -> {
6730             try (KeyChainConnection keyChainConnection =
6731                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6732                 final int[] granteeUids = keyChainConnection.getService().getGrants(alias);
6733                 final PackageManager pm = mInjector.getPackageManager(caller.getUserId());
6734 
6735                 for (final int uid : granteeUids) {
6736                     final String[] packages = pm.getPackagesForUid(uid);
6737                     if (packages == null) {
6738                         Slogf.wtf(LOG_TAG, "No packages found for uid " + uid);
6739                         continue;
6740                     }
6741                     result.put(uid, new ArraySet<String>(packages));
6742                 }
6743             } catch (RemoteException | AssertionError e) {
6744                 Slogf.e(LOG_TAG, "Querying keypair grants", e);
6745             } catch (InterruptedException e) {
6746                 Slogf.w(LOG_TAG, "Interrupted while querying keypair grants", e);
6747                 Thread.currentThread().interrupt();
6748             }
6749         });
6750         return new ParcelableGranteeMap(result);
6751     }
6752 
6753     @VisibleForTesting
6754     public static int[] translateIdAttestationFlags(
6755             int idAttestationFlags) {
6756         Map<Integer, Integer> idTypeToAttestationFlag = new HashMap();
6757         idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
6758         idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
6759         idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
6760         idTypeToAttestationFlag.put(
6761                 ID_TYPE_INDIVIDUAL_ATTESTATION, USE_INDIVIDUAL_ATTESTATION);
6762 
6763         int numFlagsSet = Integer.bitCount(idAttestationFlags);
6764         // No flags are set - return null to indicate no device ID attestation information should
6765         // be included in the attestation record.
6766         if (numFlagsSet == 0) {
6767             return null;
6768         }
6769 
6770         // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if
6771         // no other flag is set. That will lead to inclusion of general device make data in the
6772         // attestation record, but no specific device identifiers.
6773         if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) {
6774             numFlagsSet -= 1;
6775             idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO);
6776         }
6777 
6778         int[] attestationUtilsFlags = new int[numFlagsSet];
6779         int i = 0;
6780         for (Integer idType: idTypeToAttestationFlag.keySet()) {
6781             if ((idType & idAttestationFlags) != 0) {
6782                 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType);
6783             }
6784         }
6785 
6786         return attestationUtilsFlags;
6787     }
6788 
6789     @Override
6790     public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
6791             ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags,
6792             KeymasterCertificateChain attestationChain) {
6793         // Get attestation flags, if any.
6794         final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags);
6795         final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
6796         KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
6797         final String alias = keySpec.getKeystoreAlias();
6798         Preconditions.checkStringNotEmpty(alias, "Empty alias provided");
6799         Preconditions.checkArgument(
6800                 !deviceIdAttestationRequired || keySpec.getAttestationChallenge() != null,
6801                 "Requested Device ID attestation but challenge is empty");
6802 
6803         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6804         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6805         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6806         if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) {
6807             Preconditions.checkCallAuthorization(hasDeviceIdAccessUnchecked(
6808                     caller.getPackageName(), caller.getUid()));
6809             enforceIndividualAttestationSupportedIfRequested(attestationUtilsFlags);
6810         } else {
6811             if (isPermissionCheckFlagEnabled()) {
6812                 Preconditions.checkCallAuthorization(
6813                         hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6814                                 caller.getPackageName(), caller.getUserId())
6815                                 || isCredentialManagementApp);
6816             }  else {
6817                 Preconditions.checkCallAuthorization((caller.hasAdminComponent() && (isProfileOwner(
6818                         caller) || isDefaultDeviceOwner(caller))) || (caller.hasPackage() && (
6819                         isCallerDelegate || isCredentialManagementApp)));
6820             }
6821             if (isCredentialManagementApp) {
6822                 Preconditions.checkCallAuthorization(
6823                         isAliasInCredentialManagementAppPolicy(caller, alias),
6824                         CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6825             }
6826         }
6827 
6828         if (TextUtils.isEmpty(alias)) {
6829             throw new IllegalArgumentException("Empty alias provided.");
6830         }
6831         // As the caller will be granted access to the key, ensure no UID was specified, as
6832         // it will not have the desired effect.
6833         if (keySpec.getUid() != KeyProperties.UID_SELF) {
6834             Slogf.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
6835             logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6836             return false;
6837         }
6838 
6839         if (deviceIdAttestationRequired) {
6840             if (keySpec.getAttestationChallenge() == null) {
6841                 throw new IllegalArgumentException(
6842                         "Requested Device ID attestation but challenge is empty.");
6843             }
6844             KeyGenParameterSpec.Builder specBuilder = new KeyGenParameterSpec.Builder(keySpec);
6845             specBuilder.setAttestationIds(attestationUtilsFlags);
6846             specBuilder.setDevicePropertiesAttestationIncluded(true);
6847             keySpec = specBuilder.build();
6848         }
6849 
6850         final long id = mInjector.binderClearCallingIdentity();
6851         try {
6852             try (KeyChainConnection keyChainConnection =
6853                     KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6854                 IKeyChainService keyChain = keyChainConnection.getService();
6855 
6856                 final int generationResult = keyChain.generateKeyPair(algorithm,
6857                         new ParcelableKeyGenParameterSpec(keySpec));
6858                 if (generationResult != KeyChain.KEY_GEN_SUCCESS) {
6859                     Slogf.e(LOG_TAG, "KeyChain failed to generate a keypair, error %d.",
6860                             generationResult);
6861                     logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6862                     switch (generationResult) {
6863                         case KeyChain.KEY_GEN_STRONGBOX_UNAVAILABLE:
6864                             throw new ServiceSpecificException(
6865                                     DevicePolicyManager.KEY_GEN_STRONGBOX_UNAVAILABLE,
6866                                     String.format("KeyChain error: %d", generationResult));
6867                         case KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS:
6868                             throw new UnsupportedOperationException(
6869                                 "Device does not support Device ID attestation.");
6870                         default:
6871                             return false;
6872                     }
6873                 }
6874 
6875                 // Set a grant for the caller here so that when the client calls
6876                 // requestPrivateKey, it will be able to get the key from Keystore.
6877                 // Note the use of the calling  UID, since the request for the private
6878                 // key will come from the client's process, so the grant has to be for
6879                 // that UID.
6880                 keyChain.setGrant(caller.getUid(), alias, true);
6881 
6882                 try {
6883                     final List<byte[]> encodedCerts = new ArrayList();
6884                     final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
6885                     final byte[] certChainBytes = keyChain.getCaCertificates(alias);
6886                     encodedCerts.add(keyChain.getCertificate(alias));
6887                     if (certChainBytes != null) {
6888                         final Collection<X509Certificate> certs =
6889                                 (Collection<X509Certificate>) certFactory.generateCertificates(
6890                                     new ByteArrayInputStream(certChainBytes));
6891                         for (X509Certificate cert : certs) {
6892                             encodedCerts.add(cert.getEncoded());
6893                         }
6894                     }
6895 
6896                     attestationChain.shallowCopyFrom(new KeymasterCertificateChain(encodedCerts));
6897                 } catch (CertificateException e) {
6898                     logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6899                     Slogf.e(LOG_TAG, "While retrieving certificate chain.", e);
6900                     return false;
6901                 }
6902 
6903                 DevicePolicyEventLogger
6904                         .createEvent(DevicePolicyEnums.GENERATE_KEY_PAIR)
6905                         .setAdmin(caller.getPackageName())
6906                         .setBoolean(/* isDelegate */ isCallerDelegate)
6907                         .setInt(idAttestationFlags)
6908                         .setStrings(algorithm, isCredentialManagementApp
6909                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6910                         .write();
6911                 return true;
6912             }
6913         } catch (RemoteException | AssertionError e) {
6914             Slogf.e(LOG_TAG, "KeyChain error while generating a keypair", e);
6915         } catch (InterruptedException e) {
6916             Slogf.w(LOG_TAG, "Interrupted while generating keypair", e);
6917             Thread.currentThread().interrupt();
6918         } finally {
6919             mInjector.binderRestoreCallingIdentity(id);
6920         }
6921         logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6922         return false;
6923     }
6924 
6925     private void logGenerateKeyPairFailure(CallerIdentity caller,
6926             boolean isCredentialManagementApp) {
6927         if (!isCredentialManagementApp) {
6928             return;
6929         }
6930         DevicePolicyEventLogger
6931                 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_GENERATE_KEY_PAIR_FAILED)
6932                 .setStrings(caller.getPackageName())
6933                 .write();
6934     }
6935 
6936     private void enforceIndividualAttestationSupportedIfRequested(int[] attestationUtilsFlags) {
6937         for (int attestationFlag : attestationUtilsFlags) {
6938             if (attestationFlag == USE_INDIVIDUAL_ATTESTATION
6939                     && !mInjector.getPackageManager().hasSystemFeature(
6940                     PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION)) {
6941                 throw new UnsupportedOperationException("Device Individual attestation is not "
6942                         + "supported on this device.");
6943             }
6944         }
6945     }
6946 
6947     @Override
6948     public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias,
6949             byte[] cert, byte[] chain, boolean isUserSelectable) {
6950         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6951         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6952         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6953         if (isPermissionCheckFlagEnabled()) {
6954             Preconditions.checkCallAuthorization(
6955                     hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES,
6956                             caller.getPackageName(), caller.getUserId())
6957                             || isCredentialManagementApp);
6958         } else {
6959             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6960                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
6961                     || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
6962         }
6963         if (isCredentialManagementApp) {
6964             Preconditions.checkCallAuthorization(
6965                     isAliasInCredentialManagementAppPolicy(caller, alias),
6966                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6967         }
6968 
6969         final long id = mInjector.binderClearCallingIdentity();
6970         try (final KeyChainConnection keyChainConnection =
6971                 KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6972             IKeyChainService keyChain = keyChainConnection.getService();
6973             if (!keyChain.setKeyPairCertificate(alias, cert, chain)) {
6974                 return false;
6975             }
6976             keyChain.setUserSelectable(alias, isUserSelectable);
6977             DevicePolicyEventLogger
6978                     .createEvent(DevicePolicyEnums.SET_KEY_PAIR_CERTIFICATE)
6979                     .setAdmin(caller.getPackageName())
6980                     .setBoolean(/* isDelegate */ isCallerDelegate)
6981                     .setStrings(isCredentialManagementApp
6982                             ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6983                     .write();
6984             return true;
6985         } catch (InterruptedException e) {
6986             Slogf.w(LOG_TAG, "Interrupted while setting keypair certificate", e);
6987             Thread.currentThread().interrupt();
6988         } catch (RemoteException | AssertionError e) {
6989             Slogf.e(LOG_TAG, "Failed setting keypair certificate", e);
6990         } finally {
6991             mInjector.binderRestoreCallingIdentity(id);
6992         }
6993         return false;
6994     }
6995 
6996     @Override
6997     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
6998             final IBinder response) {
6999         final CallerIdentity caller = getCallerIdentity();
7000         Preconditions.checkCallAuthorization(isSystemUid(caller),
7001                 String.format(NOT_SYSTEM_CALLER_MSG, "choose private key alias"));
7002 
7003         // If there is a profile owner, redirect to that; otherwise query the device owner.
7004         ComponentName aliasChooser = getProfileOwnerAsUser(caller.getUserId());
7005         boolean isDoUser = Flags.headlessSingleUserFixes()
7006                 ? caller.getUserId() == getDeviceOwnerUserId()
7007                 : caller.getUserHandle().isSystem();
7008         if (aliasChooser == null && isDoUser) {
7009             synchronized (getLockObject()) {
7010                 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
7011                 if (deviceOwnerAdmin != null) {
7012                     aliasChooser = deviceOwnerAdmin.info.getComponent();
7013                 }
7014             }
7015         }
7016         if (aliasChooser == null) {
7017             sendPrivateKeyAliasResponse(null, response);
7018             return;
7019         }
7020 
7021         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
7022         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
7023         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
7024         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
7025         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
7026         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
7027 
7028         final ComponentName delegateReceiver;
7029         delegateReceiver = resolveDelegateReceiver(DELEGATION_CERT_SELECTION,
7030                 DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS, caller.getUserId());
7031 
7032         final boolean isDelegate;
7033         if (delegateReceiver != null) {
7034             intent.setComponent(delegateReceiver);
7035             isDelegate = true;
7036         } else {
7037             intent.setComponent(aliasChooser);
7038             isDelegate = false;
7039         }
7040 
7041         mInjector.binderWithCleanCallingIdentity(() -> {
7042             mContext.sendOrderedBroadcastAsUser(intent, caller.getUserHandle(), null,
7043                     new BroadcastReceiver() {
7044                 @Override
7045                 public void onReceive(Context context, Intent intent) {
7046                     final String chosenAlias = getResultData();
7047                     sendPrivateKeyAliasResponse(chosenAlias, response);
7048                 }
7049             }, null, Activity.RESULT_OK, null, null);
7050             DevicePolicyEventLogger
7051                     .createEvent(DevicePolicyEnums.CHOOSE_PRIVATE_KEY_ALIAS)
7052                     .setAdmin(intent.getComponent())
7053                     .setBoolean(isDelegate)
7054                     .write();
7055         });
7056     }
7057 
7058     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
7059         final IKeyChainAliasCallback keyChainAliasResponse =
7060                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
7061         // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
7062         // is oneway, which means it won't block if the recipient lives in another process.
7063         try {
7064             keyChainAliasResponse.alias(alias);
7065         } catch (Exception e) {
7066             // Caller could throw RuntimeException or RemoteException back across processes. Catch
7067             // everything just to be sure.
7068             Slogf.e(LOG_TAG, "error while responding to callback", e);
7069         }
7070     }
7071 
7072     /**
7073      * Determine whether DPMS should check if a delegate package is already installed before
7074      * granting it new delegations via {@link #setDelegatedScopes}.
7075      */
7076     private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
7077             int targetSdk, List<String> scopes) {
7078         // 1) Never skip is installed check from N.
7079         if (targetSdk >= Build.VERSION_CODES.N) {
7080             return true;
7081         }
7082         // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
7083         if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
7084             return false;
7085         }
7086         // 3) Skip if all previously granted scopes are being cleared.
7087         if (scopes.isEmpty()) {
7088             return false;
7089         }
7090         // Otherwise it should check that delegatePackage is installed.
7091         return true;
7092     }
7093 
7094     /**
7095      * Set the scopes of a device owner or profile owner delegate.
7096      *
7097      * @param who the device owner or profile owner.
7098      * @param delegatePackage the name of the delegate package.
7099      * @param scopeList the list of delegation scopes to be given to the delegate package.
7100      */
7101     @Override
7102     public void setDelegatedScopes(ComponentName who, String delegatePackage,
7103             List<String> scopeList) throws SecurityException {
7104         Objects.requireNonNull(who, "ComponentName is null");
7105         Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
7106         Preconditions.checkCollectionElementsNotNull(scopeList, "Scopes");
7107         final CallerIdentity caller = getCallerIdentity(who);
7108 
7109         // Remove possible duplicates.
7110         final ArrayList<String> scopes = new ArrayList(new ArraySet(scopeList));
7111         // Ensure given scopes are valid.
7112         if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
7113             throw new IllegalArgumentException("Unexpected delegation scopes");
7114         }
7115         // Retrieve the user ID of the calling process.
7116         final int userId = caller.getUserId();
7117         // Ensure calling process is device/profile owner.
7118         if (!Collections.disjoint(scopes, DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS)) {
7119             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
7120                     || (isProfileOwner(caller) && isManagedProfile(caller.getUserId())));
7121         } else if (!Collections.disjoint(
7122                 scopes, DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS)) {
7123             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
7124                     || isProfileOwnerOfOrganizationOwnedDevice(caller));
7125         } else {
7126             Preconditions.checkCallAuthorization(
7127                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7128         }
7129 
7130         synchronized (getLockObject()) {
7131             // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
7132             if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
7133                         getTargetSdk(who.getPackageName(), userId), scopes)) {
7134                 // Throw when the delegate package is not installed.
7135                 if (!isPackageInstalledForUser(delegatePackage, userId)) {
7136                     throw new IllegalArgumentException("Package " + delegatePackage
7137                             + " is not installed on the current user");
7138                 }
7139             }
7140 
7141             // Set the new delegate in user policies.
7142             final DevicePolicyData policy = getUserData(userId);
7143             List<String> exclusiveScopes = null;
7144             if (!scopes.isEmpty()) {
7145                 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
7146                 exclusiveScopes = new ArrayList<>(scopes);
7147                 exclusiveScopes.retainAll(EXCLUSIVE_DELEGATIONS);
7148             } else {
7149                 // Remove any delegation info if the given scopes list is empty.
7150                 policy.mDelegationMap.remove(delegatePackage);
7151             }
7152             sendDelegationChangedBroadcast(delegatePackage, scopes, userId);
7153 
7154             // If set, remove exclusive scopes from all other delegates
7155             if (exclusiveScopes != null && !exclusiveScopes.isEmpty()) {
7156                 for (int i = policy.mDelegationMap.size() - 1; i >= 0; --i) {
7157                     final String currentPackage = policy.mDelegationMap.keyAt(i);
7158                     final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
7159 
7160                     if (!currentPackage.equals(delegatePackage)) {
7161                         // Iterate through all other delegates
7162                         if (currentScopes.removeAll(exclusiveScopes)) {
7163                             // And if this delegate had some exclusive scopes which are now moved
7164                             // to the new delegate, notify about its delegation changes.
7165                             if (currentScopes.isEmpty()) {
7166                                 policy.mDelegationMap.removeAt(i);
7167                             }
7168                             sendDelegationChangedBroadcast(currentPackage,
7169                                     new ArrayList<>(currentScopes), userId);
7170                         }
7171                     }
7172                 }
7173             }
7174             // Persist updates.
7175             saveSettingsLocked(userId);
7176         }
7177     }
7178 
7179     private void sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes,
7180             int userId) {
7181         // Notify delegate package of updates.
7182         final Intent intent = new Intent(
7183                 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
7184         // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
7185         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7186         // Limit components this intent resolves to to the delegate package.
7187         intent.setPackage(delegatePackage);
7188         // Include the list of delegated scopes as an extra.
7189         intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes);
7190         // Send the broadcast.
7191         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
7192     }
7193 
7194     /**
7195      * Get the delegation scopes given to a delegate package by a device owner or profile owner.
7196      *
7197      * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
7198      * passing in {@code null} as the {@code who} parameter and its own name as the
7199      * {@code delegatepackage}.
7200      *
7201      * @param who the device owner or profile owner, or {@code null} if the caller is
7202      *            {@code delegatePackage}.
7203      * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
7204      * @return a list of the delegation scopes currently given to {@code delegatePackage}.
7205      */
7206     @Override
7207     @NonNull
7208     public List<String> getDelegatedScopes(ComponentName who,
7209             String delegatePackage) throws SecurityException {
7210         Objects.requireNonNull(delegatePackage, "Delegate package is null");
7211         final CallerIdentity caller = getCallerIdentity(who);
7212 
7213         // Ensure the caller may call this method:
7214         // * Either it's a profile owner / device owner, if componentName is provided
7215         // * Or it's an app querying its own delegation scopes
7216         if (caller.hasAdminComponent()) {
7217             Preconditions.checkCallAuthorization(
7218                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
7219         } else {
7220             Preconditions.checkCallAuthorization(isPackage(caller, delegatePackage),
7221                     String.format("Caller with uid %d is not %s", caller.getUid(),
7222                             delegatePackage));
7223         }
7224         synchronized (getLockObject()) {
7225             final DevicePolicyData policy = getUserData(caller.getUserId());
7226             // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
7227             final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
7228             return scopes == null ? Collections.EMPTY_LIST : scopes;
7229         }
7230     }
7231 
7232     /**
7233      * Get a list of  packages that were given a specific delegation scopes by a device owner or
7234      * profile owner.
7235      *
7236      * @param who the device owner or profile owner.
7237      * @param scope the scope whose delegates are to be retrieved.
7238      * @return a list of the delegate packages currently given the {@code scope} delegation.
7239      */
7240     @NonNull
7241     public List<String> getDelegatePackages(ComponentName who, String scope)
7242             throws SecurityException {
7243         Objects.requireNonNull(who, "ComponentName is null");
7244         Objects.requireNonNull(scope, "Scope is null");
7245         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
7246             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
7247         }
7248 
7249         // Retrieve the user ID of the calling process.
7250         final CallerIdentity caller = getCallerIdentity(who);
7251         Preconditions.checkCallAuthorization(
7252                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7253         synchronized (getLockObject()) {
7254             return getDelegatePackagesInternalLocked(scope, caller.getUserId());
7255         }
7256     }
7257 
7258     private List<String> getDelegatePackagesInternalLocked(String scope, int userId) {
7259         final DevicePolicyData policy = getUserData(userId);
7260 
7261         // Create a list to hold the resulting delegate packages.
7262         final List<String> delegatePackagesWithScope = new ArrayList<>();
7263         // Add all delegations containing scope to the result list.
7264         for (int i = 0; i < policy.mDelegationMap.size(); i++) {
7265             if (policy.mDelegationMap.valueAt(i).contains(scope)) {
7266                 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
7267             }
7268         }
7269         return delegatePackagesWithScope;
7270     }
7271 
7272     /**
7273      * Return the ComponentName of the receiver that handles the given broadcast action, from
7274      * the app that holds the given delegation capability. If the app defines multiple receivers
7275      * with the same intent action filter, will return any one of them nondeterministically.
7276      *
7277      * @return ComponentName of the receiver or {@null} if none exists.
7278      */
7279     private ComponentName resolveDelegateReceiver(String scope, String action, int userId) {
7280 
7281         final List<String> delegates;
7282         synchronized (getLockObject()) {
7283             delegates = getDelegatePackagesInternalLocked(scope, userId);
7284         }
7285         if (delegates.size() == 0) {
7286             return null;
7287         } else if (delegates.size() > 1) {
7288             Slogf.wtf(LOG_TAG, "More than one delegate holds " + scope);
7289             return null;
7290         }
7291         final String pkg = delegates.get(0);
7292         Intent intent = new Intent(action);
7293         intent.setPackage(pkg);
7294         final List<ResolveInfo> receivers;
7295         try {
7296             receivers = mIPackageManager.queryIntentReceivers(
7297                     intent, null, 0, userId).getList();
7298         } catch (RemoteException e) {
7299             return null;
7300         }
7301         final int count = receivers.size();
7302         if (count >= 1) {
7303             if (count > 1) {
7304                 Slogf.w(LOG_TAG, pkg + " defines more than one delegate receiver for " + action);
7305             }
7306             return receivers.get(0).activityInfo.getComponentName();
7307         } else {
7308             return null;
7309         }
7310     }
7311 
7312     /**
7313      * Check whether a caller application has been delegated a given scope via
7314      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
7315      * device owner.
7316      * <p>
7317      * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
7318      * then comparing the calling UID with the UID of {@code callerPackage} as reported by
7319      * {@link PackageManager#getPackageUidAsUser}.
7320      *
7321      * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
7322      * @param scope the delegation scope to be checked.
7323      * @return {@code true} if the calling process is a delegate of {@code scope}.
7324      */
7325     private boolean isCallerDelegate(String callerPackage, int callerUid, String scope) {
7326         Objects.requireNonNull(callerPackage, "callerPackage is null");
7327         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
7328             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
7329         }
7330 
7331         // Retrieve the UID and user ID of the calling process.
7332         final int userId = UserHandle.getUserId(callerUid);
7333         synchronized (getLockObject()) {
7334             // Retrieve user policy data.
7335             final DevicePolicyData policy = getUserData(userId);
7336             // Retrieve the list of delegation scopes granted to callerPackage.
7337             final List<String> scopes = policy.mDelegationMap.get(callerPackage);
7338             // Check callingUid only if callerPackage has the required scope delegation.
7339             if (scopes != null && scopes.contains(scope)) {
7340                 // Return true if the caller is actually callerPackage.
7341                 return isCallingFromPackage(callerPackage, callerUid);
7342             }
7343             return false;
7344         }
7345     }
7346 
7347     /**
7348      * Check whether a caller application has been delegated a given scope via
7349      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
7350      * device owner.
7351      * <p>
7352      * This is done by checking that the calling package was granted {@code scope} delegation and
7353      * then comparing the calling UID with the UID of the calling package as reported by
7354      * {@link PackageManager#getPackageUidAsUser}.
7355      *
7356      * @param caller the calling identity
7357      * @param scope the delegation scope to be checked.
7358      * @return {@code true} if the calling process is a delegate of {@code scope}.
7359      */
7360     private boolean isCallerDelegate(CallerIdentity caller, String scope) {
7361         if (caller.getPackageName() == null) {
7362             return false;
7363         }
7364         Preconditions.checkArgument(Arrays.asList(DELEGATIONS).contains(scope),
7365                 "Unexpected delegation scope: %s", scope);
7366 
7367         synchronized (getLockObject()) {
7368             // Retrieve user policy data.
7369             final DevicePolicyData policy = getUserData(caller.getUserId());
7370             // Retrieve the list of delegation scopes granted to callerPackage.
7371             final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName());
7372             // Check callingUid only if callerPackage has the required scope delegation.
7373             return scopes != null && scopes.contains(scope);
7374         }
7375     }
7376 
7377     /**
7378      * Check whether a caller application has been delegated any scope via
7379      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
7380      * device owner.
7381      * <p>
7382      * This is done by checking that the calling package was granted any scope delegations and
7383      * then comparing the calling UID with the UID of the calling package as reported by
7384      * {@link PackageManager#getPackageUidAsUser}.
7385      *
7386      * @param caller the calling identity
7387      * @return {@code true} if the calling process is a delegate of any scope.
7388      */
7389     private boolean isCallerDelegate(CallerIdentity caller) {
7390         Objects.requireNonNull(caller.getPackageName(), "callerPackage is null");
7391 
7392         synchronized (getLockObject()) {
7393             // Retrieve user policy data.
7394             final DevicePolicyData policy = getUserData(caller.getUserId());
7395             // Retrieve the list of delegation scopes granted to callerPackage.
7396             final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName());
7397             // Check callingUid only if callerPackage has the required scope delegation.
7398             return scopes != null;
7399         }
7400     }
7401 
7402     /**
7403      * Helper function to preserve delegation behavior pre-O when using the deprecated functions
7404      * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
7405      */
7406     private void setDelegatedScopePreO(ComponentName who,
7407             String delegatePackage, String scope) {
7408         Objects.requireNonNull(who, "ComponentName is null");
7409 
7410         final CallerIdentity caller = getCallerIdentity(who);
7411         // Ensure calling process is device/profile owner.
7412         Preconditions.checkCallAuthorization(
7413                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
7414 
7415         synchronized (getLockObject()) {
7416             final DevicePolicyData policy = getUserData(caller.getUserId());
7417 
7418             if (delegatePackage != null) {
7419                 // Set package as a delegate for scope if it is not already one.
7420                 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
7421                 if (scopes == null) {
7422                     scopes = new ArrayList<>();
7423                 }
7424                 if (!scopes.contains(scope)) {
7425                     scopes.add(scope);
7426                     setDelegatedScopes(who, delegatePackage, scopes);
7427                 }
7428             }
7429 
7430             // Clear any existing scope delegates.
7431             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
7432                 final String currentPackage = policy.mDelegationMap.keyAt(i);
7433                 final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
7434 
7435                 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
7436                     final List<String> newScopes = new ArrayList(currentScopes);
7437                     newScopes.remove(scope);
7438                     setDelegatedScopes(who, currentPackage, newScopes);
7439                 }
7440             }
7441         }
7442     }
7443 
7444     /**
7445      * Check whether a caller application is the credential management app, which can access
7446      * privileged APIs.
7447      * <p>
7448      * This is done by checking that the calling package is authorized to perform the app operation
7449      * {@link android.app.AppOpsManager#OP_MANAGE_CREDENTIALS}.
7450      *
7451      * @param caller the calling identity
7452      * @return {@code true} if the calling process is the credential management app.
7453      */
7454     private boolean isCredentialManagementApp(CallerIdentity caller) {
7455         return mInjector.binderWithCleanCallingIdentity(() -> {
7456             AppOpsManager appOpsManager = mInjector.getAppOpsManager();
7457             if (appOpsManager == null) return false;
7458             return appOpsManager.noteOpNoThrow(AppOpsManager.OP_MANAGE_CREDENTIALS, caller.getUid(),
7459                     caller.getPackageName(), null, null) == AppOpsManager.MODE_ALLOWED;
7460         });
7461     }
7462 
7463     /**
7464      * If the caller is the credential management app, the alias provided must be contained
7465      * in the aliases specified in the credential management app's authentication policy.
7466      */
7467     private boolean isAliasInCredentialManagementAppPolicy(CallerIdentity caller, String alias) {
7468         return mInjector.binderWithCleanCallingIdentity(() -> {
7469             try (KeyChainConnection connection = KeyChain.bindAsUser(mContext,
7470                     caller.getUserHandle())) {
7471                 // The policy will be null if there is no credential management app
7472                 AppUriAuthenticationPolicy policy =
7473                         connection.getService().getCredentialManagementAppPolicy();
7474                 return policy != null && !policy.getAppAndUriMappings().isEmpty()
7475                         && containsAlias(policy, alias);
7476             } catch (RemoteException | InterruptedException | AssertionError e) {
7477                 return false;
7478             }
7479         });
7480     }
7481 
7482     private static boolean containsAlias(AppUriAuthenticationPolicy policy, String alias) {
7483         for (Map.Entry<String, Map<Uri, String>> appsToUris :
7484                 policy.getAppAndUriMappings().entrySet()) {
7485             for (Map.Entry<Uri, String> urisToAliases : appsToUris.getValue().entrySet()) {
7486                 if (urisToAliases.getValue().equals(alias)) {
7487                     return true;
7488                 }
7489             }
7490         }
7491         return false;
7492     }
7493 
7494     @Override
7495     public void setCertInstallerPackage(ComponentName who, String installerPackage)
7496             throws SecurityException {
7497         setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
7498         DevicePolicyEventLogger
7499                 .createEvent(DevicePolicyEnums.SET_CERT_INSTALLER_PACKAGE)
7500                 .setAdmin(who)
7501                 .setStrings(installerPackage)
7502                 .write();
7503     }
7504 
7505     @Override
7506     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
7507         final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
7508         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
7509     }
7510 
7511     /**
7512      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
7513      * not installed and therefore not available.
7514      *
7515      * @throws SecurityException if the caller is not a profile or device owner.
7516      * @throws UnsupportedOperationException if the package does not support being set as always-on.
7517      */
7518     @Override
7519     public boolean setAlwaysOnVpnPackage(ComponentName who, String vpnPackage, boolean lockdown,
7520             List<String> lockdownAllowlist)
7521             throws SecurityException {
7522         Objects.requireNonNull(who, "ComponentName is null");
7523 
7524         final CallerIdentity caller = getCallerIdentity(who);
7525         Preconditions.checkCallAuthorization(
7526                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7527         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_ALWAYS_ON_VPN_PACKAGE);
7528 
7529         if (vpnPackage == null) {
7530             final String prevVpnPackage;
7531             synchronized (getLockObject()) {
7532                 prevVpnPackage = getProfileOwnerOrDeviceOwnerLocked(
7533                         caller.getUserId()).mAlwaysOnVpnPackage;
7534                 // If the admin is clearing VPN package but hasn't configure any VPN previously,
7535                 // ignore it so that it doesn't interfere with user-configured VPNs.
7536                 if (TextUtils.isEmpty(prevVpnPackage)) {
7537                     return true;
7538                 }
7539             }
7540             revokeVpnAuthorizationForPackage(prevVpnPackage, caller.getUserId());
7541         }
7542 
7543         final int userId = caller.getUserId();
7544         mInjector.binderWithCleanCallingIdentity(() -> {
7545             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
7546                 Slogf.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage);
7547                 throw new ServiceSpecificException(
7548                         DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage);
7549             }
7550 
7551             if (vpnPackage != null && lockdown && lockdownAllowlist != null) {
7552                 for (String packageName : lockdownAllowlist) {
7553                     if (!isPackageInstalledForUser(packageName, userId)) {
7554                         Slogf.w(LOG_TAG, "Non-existent package in VPN allowlist: " + packageName);
7555                         throw new ServiceSpecificException(
7556                                 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName);
7557                     }
7558                 }
7559             }
7560             // If some package is uninstalled after the check above, it will be ignored by CM.
7561             if (!mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(
7562                     userId, vpnPackage, lockdown, lockdownAllowlist)) {
7563                 throw new UnsupportedOperationException();
7564             }
7565         });
7566         DevicePolicyEventLogger
7567                 .createEvent(DevicePolicyEnums.SET_ALWAYS_ON_VPN_PACKAGE)
7568                 .setAdmin(caller.getComponentName())
7569                 .setStrings(vpnPackage)
7570                 .setBoolean(lockdown)
7571                 .setInt(lockdownAllowlist != null ? lockdownAllowlist.size() : 0)
7572                 .write();
7573         synchronized (getLockObject()) {
7574             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
7575             if (!TextUtils.equals(vpnPackage, admin.mAlwaysOnVpnPackage)
7576                     || lockdown != admin.mAlwaysOnVpnLockdown) {
7577                 admin.mAlwaysOnVpnPackage = vpnPackage;
7578                 admin.mAlwaysOnVpnLockdown = lockdown;
7579                 saveSettingsLocked(userId);
7580             }
7581         }
7582         return true;
7583     }
7584 
7585     private void revokeVpnAuthorizationForPackage(String vpnPackage, int userId) {
7586         mInjector.binderWithCleanCallingIdentity(() -> {
7587             try {
7588                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
7589                         vpnPackage, /* flags= */ 0, userId);
7590                 if (ai == null) {
7591                     Slogf.w(LOG_TAG, "Non-existent VPN package: " + vpnPackage);
7592                 } else {
7593                     mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN,
7594                             ai.uid, vpnPackage, MODE_DEFAULT);
7595                 }
7596             } catch (RemoteException e) {
7597                 Slogf.e(LOG_TAG, "Can't talk to package managed", e);
7598             }
7599         });
7600     }
7601 
7602     @Override
7603     public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException {
7604         Objects.requireNonNull(admin, "ComponentName is null");
7605 
7606         final CallerIdentity caller = getCallerIdentity(admin);
7607         Preconditions.checkCallAuthorization(
7608                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7609 
7610         return mInjector.binderWithCleanCallingIdentity(
7611                 () -> mInjector.getVpnManager().getAlwaysOnVpnPackageForUser(caller.getUserId()));
7612     }
7613 
7614     @Override
7615     public String getAlwaysOnVpnPackageForUser(int userHandle) {
7616         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
7617                 String.format(NOT_SYSTEM_CALLER_MSG, "call getAlwaysOnVpnPackageForUser"));
7618         synchronized (getLockObject()) {
7619             ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle);
7620             return admin != null ? admin.mAlwaysOnVpnPackage : null;
7621         }
7622     }
7623 
7624     @Override
7625     public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException {
7626         final CallerIdentity caller;
7627         if (hasCallingPermission(PERMISSION_MAINLINE_NETWORK_STACK)) {
7628             // TODO: CaptivePortalLoginActivity erroneously calls this method with a non-admin
7629             // ComponentName, so we have to use a separate code path for it:
7630             // getCallerIdentity(admin) will throw if the admin is not in the known admin list.
7631             caller = getCallerIdentity();
7632         } else {
7633             caller = getCallerIdentity(admin);
7634             Preconditions.checkCallAuthorization(
7635                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7636         }
7637 
7638         return mInjector.binderWithCleanCallingIdentity(
7639                 () -> mInjector.getVpnManager().isVpnLockdownEnabled(caller.getUserId()));
7640     }
7641 
7642     @Override
7643     public boolean isAlwaysOnVpnLockdownEnabledForUser(int userHandle) {
7644         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
7645                 String.format(NOT_SYSTEM_CALLER_MSG, "call isAlwaysOnVpnLockdownEnabledForUser"));
7646         synchronized (getLockObject()) {
7647             ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle);
7648             return admin != null && admin.mAlwaysOnVpnLockdown;
7649         }
7650     }
7651 
7652     @Override
7653     public List<String> getAlwaysOnVpnLockdownAllowlist(ComponentName admin)
7654             throws SecurityException {
7655         Objects.requireNonNull(admin, "ComponentName is null");
7656 
7657         final CallerIdentity caller = getCallerIdentity(admin);
7658         Preconditions.checkCallAuthorization(
7659                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
7660 
7661         return mInjector.binderWithCleanCallingIdentity(
7662                 () -> mInjector.getVpnManager().getVpnLockdownAllowlist(caller.getUserId()));
7663     }
7664 
7665     private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc,
7666             boolean wipeResetProtectionData) {
7667         wtfIfInLock();
7668         boolean success = false;
7669 
7670         try {
7671             boolean delayed = !mInjector.recoverySystemRebootWipeUserData(
7672                     /* shutdown= */ false, reason, /* force= */ true, /* wipeEuicc= */ wipeEuicc,
7673                     wipeExtRequested, wipeResetProtectionData);
7674             if (delayed) {
7675                 // Persist the request so the device is automatically factory-reset on next start if
7676                 // the system crashes or reboots before the {@code DevicePolicySafetyChecker} calls
7677                 // its callback.
7678                 Slogf.i(LOG_TAG, "Persisting factory reset request as it could be delayed by %s",
7679                         mSafetyChecker);
7680                 synchronized (getLockObject()) {
7681                     DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
7682                     policy.setDelayedFactoryReset(reason, wipeExtRequested, wipeEuicc,
7683                             wipeResetProtectionData);
7684                     saveSettingsLocked(UserHandle.USER_SYSTEM);
7685                 }
7686             }
7687             success = true;
7688         } catch (IOException | SecurityException e) {
7689             Slogf.w(LOG_TAG, "Failed requesting data wipe", e);
7690         } finally {
7691             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
7692         }
7693     }
7694 
7695     private void factoryResetIfDelayedEarlier() {
7696         synchronized (getLockObject()) {
7697             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
7698 
7699             if (policy.mFactoryResetFlags == 0) return;
7700 
7701             if (policy.mFactoryResetReason == null) {
7702                 // Shouldn't happen.
7703                 Slogf.e(LOG_TAG, "no persisted reason for factory resetting");
7704                 policy.mFactoryResetReason = "requested before boot";
7705             }
7706             FactoryResetter factoryResetter = FactoryResetter.newBuilder(mContext)
7707                     .setReason(policy.mFactoryResetReason).setForce(true)
7708                     .setWipeEuicc((policy.mFactoryResetFlags & DevicePolicyData
7709                             .FACTORY_RESET_FLAG_WIPE_EUICC) != 0)
7710                     .setWipeAdoptableStorage((policy.mFactoryResetFlags & DevicePolicyData
7711                             .FACTORY_RESET_FLAG_WIPE_EXTERNAL_STORAGE) != 0)
7712                     .setWipeFactoryResetProtection((policy.mFactoryResetFlags & DevicePolicyData
7713                             .FACTORY_RESET_FLAG_WIPE_FACTORY_RESET_PROTECTION) != 0)
7714                     .build();
7715             Slogf.i(LOG_TAG, "Factory resetting on boot using " + factoryResetter);
7716             try {
7717                 if (!factoryResetter.factoryReset()) {
7718                     // Shouldn't happen because FactoryResetter was created without a
7719                     // DevicePolicySafetyChecker.
7720                     Slogf.wtf(LOG_TAG, "Factory reset using " + factoryResetter + " failed.");
7721                 }
7722             } catch (IOException e) {
7723                 // Shouldn't happen.
7724                 Slogf.wtf(LOG_TAG, "Could not factory reset using " + factoryResetter, e);
7725             }
7726         }
7727     }
7728 
7729     private void forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently) {
7730         boolean success = false;
7731         try {
7732             if (getCurrentForegroundUserId() == userId) {
7733                 // TODO: We need to special case headless here as we can't switch to the system user
7734                 mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM);
7735             }
7736 
7737             success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
7738             if (!success) {
7739                 Slogf.w(LOG_TAG, "Couldn't remove user " + userId);
7740             } else if (isManagedProfile(userId) && !wipeSilently) {
7741                 sendWipeProfileNotification(wipeReasonForUser,
7742                         UserHandle.of(getProfileParentId(userId)));
7743             }
7744         } catch (RemoteException re) {
7745             // Shouldn't happen
7746             Slogf.wtf(LOG_TAG, "Error forcing wipe user", re);
7747         } finally {
7748             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
7749         }
7750     }
7751 
7752     @Override
7753     public void wipeDataWithReason(String callerPackageName, int flags,
7754             @NonNull String wipeReasonForUser, boolean calledOnParentInstance,
7755             boolean factoryReset) {
7756         if (!mHasFeature && !hasCallingOrSelfPermission(permission.MASTER_CLEAR)) {
7757             return;
7758         }
7759         CallerIdentity caller = getCallerIdentity(callerPackageName);
7760 
7761         boolean calledByProfileOwnerOnOrgOwnedDevice =
7762                 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId());
7763         EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
7764                 /*admin=*/ null,
7765                 /*permission=*/ new String[]{MANAGE_DEVICE_POLICY_WIPE_DATA, MASTER_CLEAR},
7766                 USES_POLICY_WIPE_DATA,
7767                 caller.getPackageName(),
7768                 factoryReset ? UserHandle.USER_ALL : getAffectedUser(calledOnParentInstance));
7769         ActiveAdmin admin = enforcingAdmin.getActiveAdmin();
7770 
7771         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_WIPE_DATA);
7772 
7773         if (TextUtils.isEmpty(wipeReasonForUser)) {
7774             wipeReasonForUser = getGenericWipeReason(
7775                     calledByProfileOwnerOnOrgOwnedDevice, calledOnParentInstance);
7776         }
7777 
7778         int userId = admin != null ? admin.getUserHandle().getIdentifier()
7779                 : caller.getUserId();
7780         Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser, admin,
7781                 userId);
7782         if (calledByProfileOwnerOnOrgOwnedDevice) {
7783             // When wipeData is called on the parent instance, it implies wiping the entire device.
7784             if (calledOnParentInstance) {
7785                 userId = UserHandle.USER_SYSTEM;
7786             } else {
7787                 // when wipeData is _not_ called on the parent instance, it implies relinquishing
7788                 // control over the device, wiping only the work profile. So the user restriction
7789                 // on profile removal needs to be removed first.
7790                 final UserHandle parentUser = UserHandle.of(getProfileParentId(userId));
7791                 mInjector.binderWithCleanCallingIdentity(
7792                         () -> clearOrgOwnedProfileOwnerUserRestrictions(parentUser));
7793             }
7794         }
7795         DevicePolicyEventLogger event = DevicePolicyEventLogger
7796                 .createEvent(DevicePolicyEnums.WIPE_DATA_WITH_REASON)
7797                 .setInt(flags)
7798                 .setStrings(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT);
7799 
7800         final String adminName;
7801         final ComponentName adminComp;
7802         if (admin != null) {
7803             if (admin.isPermissionBased) {
7804                 adminComp = null;
7805                 adminName = caller.getPackageName();
7806                 event.setAdmin(adminName);
7807             } else {
7808                 adminComp = admin.info.getComponent();
7809                 adminName = adminComp.flattenToShortString();
7810                 event.setAdmin(adminComp);
7811             }
7812         } else {
7813             adminComp = null;
7814             adminName = mInjector.getPackageManager().getPackagesForUid(caller.getUid())[0];
7815             Slogf.i(LOG_TAG, "Logging wipeData() event admin as " + adminName);
7816             event.setAdmin(adminName);
7817             if (mInjector.userManagerIsHeadlessSystemUserMode()) {
7818                 // On headless system user mode, the call is meant to factory reset the whole
7819                 // device, otherwise the caller could simply remove the current user.
7820                 userId = UserHandle.USER_SYSTEM;
7821             }
7822         }
7823         event.write();
7824 
7825         String internalReason = String.format(
7826                 "DevicePolicyManager.wipeDataWithReason() from %s, organization-owned? %s",
7827                 adminName, calledByProfileOwnerOnOrgOwnedDevice);
7828 
7829         wipeDataNoLock(adminComp, flags, internalReason, wipeReasonForUser, userId,
7830                 calledOnParentInstance, factoryReset);
7831     }
7832 
7833     private String getGenericWipeReason(
7834             boolean calledByProfileOwnerOnOrgOwnedDevice, boolean calledOnParentInstance) {
7835         return calledByProfileOwnerOnOrgOwnedDevice && !calledOnParentInstance
7836                 ? getUpdatableString(
7837                         WORK_PROFILE_DELETED_ORG_OWNED_MESSAGE,
7838                         R.string.device_ownership_relinquished)
7839                 : getUpdatableString(
7840                         WORK_PROFILE_DELETED_GENERIC_MESSAGE,
7841                         R.string.work_profile_deleted_description_dpm_wipe);
7842     }
7843 
7844     /**
7845      * Clears device wide policies enforced by COPE PO when relinquishing the device. This method
7846      * should be invoked once the admin is gone, so that all methods that rely on calculating
7847      * aggregate policy (e.g. strong auth timeout) from all admins aren't affected by its policies.
7848      * This method assumes that there is no other device or profile owners left on the device.
7849      * Shouldn't be called from binder thread without clearing identity.
7850      */
7851     private void clearOrgOwnedProfileOwnerDeviceWidePolicies(@UserIdInt int parentId) {
7852         Slogf.i(LOG_TAG, "Cleaning up device-wide policies left over from org-owned profile...");
7853         // Lockscreen message
7854         mLockPatternUtils.setDeviceOwnerInfo(null);
7855         // Wifi config lockdown
7856         mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
7857         // Security logging
7858         if (mInjector.securityLogGetLoggingEnabledProperty()) {
7859             mSecurityLogMonitor.stop();
7860             mInjector.securityLogSetLoggingEnabledProperty(false);
7861         }
7862         // Network logging
7863         setNetworkLoggingActiveInternal(false);
7864 
7865         // System update policy.
7866         final boolean hasSystemUpdatePolicy;
7867         synchronized (getLockObject()) {
7868             hasSystemUpdatePolicy = mOwners.getSystemUpdatePolicy() != null;
7869             if (hasSystemUpdatePolicy) {
7870                 mOwners.clearSystemUpdatePolicy();
7871                 mOwners.writeDeviceOwner();
7872             }
7873         }
7874         if (hasSystemUpdatePolicy) {
7875             mContext.sendBroadcastAsUser(
7876                     new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM);
7877         }
7878 
7879         // Unsuspend personal apps if needed.
7880         suspendPersonalAppsInternal(parentId, getManagedUserId(parentId), false);
7881 
7882         // Notify FRP agent, LSS and WindowManager to ensure they don't hold on to stale policies.
7883         final int frpAgentUid = getFrpManagementAgentUid();
7884         if (frpAgentUid > 0) {
7885             notifyResetProtectionPolicyChanged(frpAgentUid);
7886         }
7887         mLockSettingsInternal.refreshStrongAuthTimeout(parentId);
7888 
7889         clearManagedSubscriptionsPolicy();
7890         clearLauncherShortcutOverrides();
7891         updateTelephonyCrossProfileIntentFilters(parentId, UserHandle.USER_NULL, false);
7892 
7893         Slogf.i(LOG_TAG, "Cleaning up device-wide policies done.");
7894     }
7895 
7896     private void clearManagedSubscriptionsPolicy() {
7897         unregisterOnSubscriptionsChangedListener();
7898 
7899         SubscriptionManager subscriptionManager = mContext.getSystemService(
7900                 SubscriptionManager.class);
7901         //Iterate over all the subscriptions and remove association with any user.
7902         int[] subscriptionIds = subscriptionManager.getActiveSubscriptionIdList(false);
7903         for (int subId : subscriptionIds) {
7904             subscriptionManager.setSubscriptionUserHandle(subId, null);
7905         }
7906     }
7907 
7908     private void clearLauncherShortcutOverrides() {
7909         mPolicyCache.setLauncherShortcutOverrides(new ArrayMap<>());
7910     }
7911 
7912     private void updateTelephonyCrossProfileIntentFilters(int parentUserId, int profileUserId,
7913             boolean enableWorkTelephony) {
7914         try {
7915             // This should only occur when managed profile is being removed.
7916             if (!enableWorkTelephony && profileUserId == UserHandle.USER_NULL) {
7917                 mIPackageManager.clearCrossProfileIntentFilters(parentUserId,
7918                         mContext.getPackageName());
7919                 return;
7920             }
7921             for (DefaultCrossProfileIntentFilter filter :
7922                     DefaultCrossProfileIntentFiltersUtils
7923                             .getDefaultCrossProfileTelephonyIntentFilters(!enableWorkTelephony)) {
7924                 if (removeCrossProfileIntentFilter(filter, parentUserId, profileUserId)) {
7925                     Slogf.w(LOG_TAG,
7926                             "Failed to remove cross-profile intent filter: "
7927                                     + filter.filter.getIntentFilter() + ", enableWorkTelephony: "
7928                                     + enableWorkTelephony);
7929                 }
7930             }
7931             for (DefaultCrossProfileIntentFilter filter :
7932                     DefaultCrossProfileIntentFiltersUtils
7933                             .getDefaultCrossProfileTelephonyIntentFilters(enableWorkTelephony)) {
7934                 addCrossProfileIntentFilter(filter, parentUserId, profileUserId);
7935             }
7936         } catch (RemoteException re) {
7937             Slogf.wtf(LOG_TAG, "Error updating telephony cross profile intent filters", re);
7938         }
7939     }
7940 
7941     void addCrossProfileIntentFilter(DefaultCrossProfileIntentFilter filter, int parentUserId,
7942             int profileUserId)
7943             throws RemoteException {
7944         if (filter.direction == DefaultCrossProfileIntentFilter.Direction.TO_PROFILE) {
7945             mIPackageManager.addCrossProfileIntentFilter(
7946                     filter.filter.getIntentFilter(),
7947                     mContext.getOpPackageName(),
7948                     parentUserId,
7949                     profileUserId,
7950                     filter.flags);
7951         } else {
7952             mIPackageManager.addCrossProfileIntentFilter(
7953                     filter.filter.getIntentFilter(),
7954                     mContext.getOpPackageName(),
7955                     profileUserId,
7956                     parentUserId,
7957                     filter.flags);
7958         }
7959     }
7960 
7961     boolean removeCrossProfileIntentFilter(DefaultCrossProfileIntentFilter filter, int parentUserId,
7962             int profileUserId)
7963             throws RemoteException {
7964         if (filter.direction == DefaultCrossProfileIntentFilter.Direction.TO_PROFILE) {
7965             return mIPackageManager.removeCrossProfileIntentFilter(
7966                     filter.filter.getIntentFilter(),
7967                     mContext.getOpPackageName(),
7968                     parentUserId,
7969                     profileUserId,
7970                     filter.flags);
7971         } else {
7972             return mIPackageManager.removeCrossProfileIntentFilter(
7973                     filter.filter.getIntentFilter(),
7974                     mContext.getOpPackageName(),
7975                     profileUserId,
7976                     parentUserId,
7977                     filter.flags);
7978         }
7979     }
7980 
7981     /**
7982      * @param factoryReset null: legacy behaviour, false: attempt to remove user, true: attempt to
7983      *                     factory reset
7984      */
7985     private void wipeDataNoLock(@Nullable ComponentName admin, int flags, String internalReason,
7986             String wipeReasonForUser, int userId, boolean calledOnParentInstance,
7987             @Nullable Boolean factoryReset) {
7988         wtfIfInLock();
7989         final String adminPackage;
7990         if (admin != null) {
7991             adminPackage = admin.getPackageName();
7992         } else {
7993             int callerId = mInjector.binderGetCallingUid();
7994             String[] adminPackages = mInjector.getPackageManager().getPackagesForUid(callerId);
7995             Preconditions.checkState(adminPackages.length > 0,
7996                     "Caller %s does not have any associated packages", callerId);
7997             adminPackage = adminPackages[0];
7998         }
7999         mInjector.binderWithCleanCallingIdentity(() -> {
8000             // First check whether the admin is allowed to wipe the device/user/profile.
8001             final String restriction;
8002             boolean shouldFactoryReset = userId == UserHandle.USER_SYSTEM;
8003             if (Flags.headlessSingleUserFixes() && getHeadlessDeviceOwnerModeForDeviceOwner()
8004                     == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER) {
8005                 shouldFactoryReset = userId == getMainUserId();
8006             }
8007             if (shouldFactoryReset) {
8008                 restriction = UserManager.DISALLOW_FACTORY_RESET;
8009             } else if (isManagedProfile(userId)) {
8010                 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
8011             } else {
8012                 restriction = UserManager.DISALLOW_REMOVE_USER;
8013             }
8014             if (isAdminAffectedByRestriction(admin, restriction, userId)) {
8015                 throw new SecurityException("Cannot wipe data. " + restriction
8016                         + " restriction is set for user " + userId);
8017             }
8018         });
8019 
8020         boolean isSystemUser = userId == UserHandle.USER_SYSTEM;
8021         boolean isMainUser = userId == getMainUserId();
8022         boolean wipeDevice;
8023         if (factoryReset == null || !mInjector.isChangeEnabled(EXPLICIT_WIPE_BEHAVIOUR,
8024                 adminPackage,
8025                 userId)) {
8026             // Legacy mode
8027             wipeDevice = Flags.headlessSingleUserFixes()
8028                     && getHeadlessDeviceOwnerModeForDeviceOwner()
8029                     == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER ? isMainUser : isSystemUser;
8030         } else {
8031             // Explicit behaviour
8032             if (factoryReset) {
8033                 EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
8034                         /*admin=*/ null,
8035                         /*permission=*/ new String[]{MANAGE_DEVICE_POLICY_WIPE_DATA,
8036                                 MASTER_CLEAR},
8037                         USES_POLICY_WIPE_DATA,
8038                         adminPackage,
8039                         factoryReset ? UserHandle.USER_ALL :
8040                                 getAffectedUser(calledOnParentInstance));
8041                 wipeDevice = true;
8042             } else {
8043                 mInjector.binderWithCleanCallingIdentity(() -> {
8044                     Preconditions.checkCallAuthorization(!isSystemUser,
8045                             "User %s is a system user and cannot be removed", userId);
8046                     boolean isLastNonHeadlessUser = getUserInfo(userId).isFull()
8047                             && mUserManager.getAliveUsers().stream()
8048                             .filter((it) -> it.getUserHandle().getIdentifier() != userId)
8049                             .noneMatch(UserInfo::isFull);
8050                     Preconditions.checkState(!isLastNonHeadlessUser,
8051                             "Removing user %s would leave the device without any active users. "
8052                                     + "Consider factory resetting the device instead.",
8053                             userId);
8054                 });
8055                 wipeDevice = false;
8056             }
8057         }
8058         mInjector.binderWithCleanCallingIdentity(() -> {
8059             if (wipeDevice) {
8060                 forceWipeDeviceNoLock(
8061                         (flags & WIPE_EXTERNAL_STORAGE) != 0,
8062                         internalReason,
8063                         (flags & WIPE_EUICC) != 0,
8064                         (flags & WIPE_RESET_PROTECTION_DATA) != 0);
8065             } else {
8066                 forceWipeUser(userId, wipeReasonForUser, (flags & WIPE_SILENTLY) != 0);
8067             }
8068         });
8069     }
8070 
8071     private void sendWipeProfileNotification(String wipeReasonForUser, UserHandle user) {
8072         Notification notification =
8073                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
8074                         .setSmallIcon(android.R.drawable.stat_sys_warning)
8075                         .setContentTitle(getWorkProfileDeletedTitle())
8076                         .setContentText(wipeReasonForUser)
8077                         .setColor(mContext.getColor(R.color.system_notification_accent_color))
8078                         .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
8079                         .build();
8080         mInjector.getNotificationManager().notifyAsUser(
8081                 /* tag= */ null, SystemMessage.NOTE_PROFILE_WIPED, notification, user);
8082     }
8083 
8084     private String getWorkProfileDeletedTitle() {
8085         return getUpdatableString(WORK_PROFILE_DELETED_TITLE, R.string.work_profile_deleted);
8086     }
8087 
8088     private void clearWipeProfileNotification() {
8089         mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
8090     }
8091 
8092     @Override
8093     public void setFactoryResetProtectionPolicy(ComponentName who, String callerPackageName,
8094             @Nullable FactoryResetProtectionPolicy policy) {
8095         if (!mHasFeature) {
8096             return;
8097         }
8098         if (!isPermissionCheckFlagEnabled()) {
8099             Preconditions.checkNotNull(who, "ComponentName is null");
8100         }
8101         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
8102         if (!isPermissionCheckFlagEnabled()) {
8103             Preconditions.checkCallAuthorization(
8104                     isDefaultDeviceOwner(caller)
8105                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
8106         }
8107         checkCanExecuteOrThrowUnsafe(DevicePolicyManager
8108                 .OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY);
8109 
8110         final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow();
8111         synchronized (getLockObject()) {
8112             ActiveAdmin admin;
8113             if (isPermissionCheckFlagEnabled()) {
8114                 admin = enforcePermissionAndGetEnforcingAdmin(
8115                         who, MANAGE_DEVICE_POLICY_FACTORY_RESET, caller.getPackageName(),
8116                         UserHandle.USER_ALL)
8117                         .getActiveAdmin();
8118             } else {
8119                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
8120             }
8121             admin.mFactoryResetProtectionPolicy = policy;
8122             saveSettingsLocked(caller.getUserId());
8123         }
8124 
8125         mInjector.binderWithCleanCallingIdentity(
8126                 () -> notifyResetProtectionPolicyChanged(frpManagementAgentUid));
8127 
8128         DevicePolicyEventLogger
8129                 .createEvent(DevicePolicyEnums.SET_FACTORY_RESET_PROTECTION)
8130                 .setAdmin(caller.getPackageName())
8131                 .write();
8132     }
8133 
8134     // Shouldn't be called from binder thread without clearing identity.
8135     private void notifyResetProtectionPolicyChanged(int frpManagementAgentUid) {
8136         final Intent intent = new Intent(
8137                 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED).addFlags(
8138                 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND | Intent.FLAG_RECEIVER_FOREGROUND);
8139         mContext.sendBroadcastAsUser(intent,
8140                 UserHandle.getUserHandleForUid(frpManagementAgentUid),
8141                 permission.MANAGE_FACTORY_RESET_PROTECTION);
8142     }
8143 
8144     @Override
8145     public FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
8146             @Nullable ComponentName who) {
8147         if (!mHasFeature) {
8148             return null;
8149         }
8150 
8151         final CallerIdentity caller = getCallerIdentity(who);
8152         final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow();
8153         final ActiveAdmin admin;
8154         synchronized (getLockObject()) {
8155             if (who == null) {
8156                 Preconditions.checkCallAuthorization(frpManagementAgentUid == caller.getUid()
8157                                 || hasCallingPermission(permission.MASTER_CLEAR)
8158                                 || hasCallingPermission(MANAGE_DEVICE_POLICY_FACTORY_RESET),
8159                         "Must be called by the FRP management agent on device");
8160                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked();
8161             } else {
8162                 Preconditions.checkCallAuthorization(
8163                         isDefaultDeviceOwner(caller)
8164                                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
8165                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
8166             }
8167         }
8168 
8169         return admin != null ? admin.mFactoryResetProtectionPolicy : null;
8170     }
8171 
8172     private int getFrpManagementAgentUid() {
8173         PersistentDataBlockManagerInternal pdb = mInjector.getPersistentDataBlockManagerInternal();
8174         return pdb != null ? pdb.getAllowedUid() : -1;
8175     }
8176 
8177     private int getFrpManagementAgentUidOrThrow() {
8178         int uid = getFrpManagementAgentUid();
8179         if (uid == -1) {
8180             throw new UnsupportedOperationException(
8181                     "The persistent data block service is not supported on this device");
8182         }
8183         return uid;
8184     }
8185 
8186     @Override
8187     public boolean isFactoryResetProtectionPolicySupported() {
8188         return getFrpManagementAgentUid() != -1;
8189     }
8190 
8191     @Override
8192     public void sendLostModeLocationUpdate(AndroidFuture<Boolean> future) {
8193         if (!mHasFeature) {
8194             future.complete(false);
8195             return;
8196         }
8197         Preconditions.checkCallAuthorization(
8198                 hasCallingOrSelfPermission(permission.TRIGGER_LOST_MODE));
8199 
8200         synchronized (getLockObject()) {
8201             ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
8202 
8203             Preconditions.checkState(admin != null,
8204                     "Lost mode location updates can only be sent on an organization-owned device.");
8205             mInjector.binderWithCleanCallingIdentity(() -> {
8206                 String[] providers = {LocationManager.FUSED_PROVIDER,
8207                         LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER};
8208                 tryRetrieveAndSendLocationUpdate(admin, future, providers, /* index= */ 0);
8209             });
8210         }
8211     }
8212 
8213     /** Send lost mode location updates recursively, in order of the list of location providers. */
8214     private void tryRetrieveAndSendLocationUpdate(ActiveAdmin admin,
8215             AndroidFuture<Boolean> future, String[] providers, int index) {
8216         // None of the providers were able to get location, return false
8217         if (index == providers.length) {
8218             future.complete(false);
8219             return;
8220         }
8221         if (mInjector.getLocationManager().isProviderEnabled(providers[index])) {
8222             mInjector.getLocationManager().getCurrentLocation(providers[index],
8223                     /* cancellationSignal= */ null, mContext.getMainExecutor(), location -> {
8224                         if (location != null) {
8225                             mContext.sendBroadcastAsUser(
8226                                     newLostModeLocationUpdateIntent(admin, location),
8227                                     admin.getUserHandle());
8228                             future.complete(true);
8229                         } else {
8230                             tryRetrieveAndSendLocationUpdate(admin, future, providers, index + 1);
8231                         }
8232                     }
8233             );
8234         } else {
8235            tryRetrieveAndSendLocationUpdate(admin, future, providers, index + 1);
8236         }
8237     }
8238 
8239     private Intent newLostModeLocationUpdateIntent(ActiveAdmin admin, Location location) {
8240         final Intent intent = new Intent(
8241                 DevicePolicyManager.ACTION_LOST_MODE_LOCATION_UPDATE);
8242         intent.putExtra(DevicePolicyManager.EXTRA_LOST_MODE_LOCATION, location);
8243         intent.setPackage(admin.info.getPackageName());
8244         return intent;
8245     }
8246 
8247     /**
8248      * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
8249      * the remove warning for the given device admin.
8250      */
8251     @Override
8252     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
8253         if (!mHasFeature) {
8254             return;
8255         }
8256         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8257 
8258         final CallerIdentity caller = getCallerIdentity();
8259         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8260         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8261 
8262         synchronized (getLockObject()) {
8263             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
8264             if (admin == null) {
8265                 result.sendResult(null);
8266                 return;
8267             }
8268             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
8269             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8270             intent.setComponent(admin.info.getComponent());
8271             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
8272                     null, new BroadcastReceiver() {
8273                 @Override
8274                 public void onReceive(Context context, Intent intent) {
8275                     result.sendResult(getResultExtras(false));
8276                 }
8277             }, null, Activity.RESULT_OK, null, null);
8278         }
8279     }
8280 
8281     @Override
8282     public void reportPasswordChanged(PasswordMetrics metrics, @UserIdInt int userId) {
8283         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
8284             return;
8285         }
8286 
8287         final CallerIdentity caller = getCallerIdentity();
8288         Preconditions.checkCallAuthorization(isSystemUid(caller));
8289         // Managed Profile password can only be changed when it has a separate challenge.
8290         if (!isSeparateProfileChallengeEnabled(userId)) {
8291             Preconditions.checkCallAuthorization(!isManagedProfile(userId), "You can "
8292                     + "not set the active password for a managed profile, userId = %d", userId);
8293         }
8294 
8295         DevicePolicyData policy = getUserData(userId);
8296         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
8297 
8298         synchronized (getLockObject()) {
8299             policy.mFailedPasswordAttempts = 0;
8300             affectedUserIds.add(userId);
8301             affectedUserIds.addAll(updatePasswordValidityCheckpointLocked(
8302                     userId, /* parent */ false));
8303             affectedUserIds.addAll(updatePasswordExpirationsLocked(userId));
8304             setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
8305 
8306             // Send a broadcast to each profile using this password as its primary unlock.
8307             sendAdminCommandForLockscreenPoliciesLocked(
8308                     DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
8309                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
8310 
8311             affectedUserIds.addAll(removeCaApprovalsIfNeeded(userId));
8312             saveSettingsForUsersLocked(affectedUserIds);
8313         }
8314         if (mInjector.securityLogIsLoggingEnabled()) {
8315             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_CHANGED,
8316                     /* complexity */ metrics.determineComplexity(), /*user*/ userId);
8317         }
8318     }
8319 
8320     /**
8321      * Called any time the device password is updated. Resets all password expiration clocks.
8322      *
8323      * @return the set of user IDs that have been affected
8324      */
8325     @GuardedBy("getLockObject()")
8326     private Set<Integer> updatePasswordExpirationsLocked(int userHandle) {
8327         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
8328         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
8329         for (int i = 0; i < admins.size(); i++) {
8330             ActiveAdmin admin = admins.get(i);
8331             if (admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
8332                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
8333                 long timeout = admin.passwordExpirationTimeout;
8334                 admin.passwordExpirationDate =
8335                         timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
8336             }
8337         }
8338         return affectedUserIds;
8339     }
8340 
8341     @Override
8342     public void reportFailedPasswordAttempt(int userHandle, boolean parent) {
8343         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8344 
8345         final CallerIdentity caller = getCallerIdentity();
8346         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8347         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8348         if (!isSeparateProfileChallengeEnabled(userHandle)) {
8349             Preconditions.checkCallAuthorization(!isManagedProfile(userHandle),
8350                     "You can not report failed password attempt if separate profile challenge is "
8351                             + "not in place for a managed profile, userId = %d", userHandle);
8352         }
8353 
8354         boolean wipeData = false;
8355         ActiveAdmin strictestAdmin = null;
8356         final long ident = mInjector.binderClearCallingIdentity();
8357         try {
8358             synchronized (getLockObject()) {
8359                 DevicePolicyData policy = getUserData(userHandle);
8360                 policy.mFailedPasswordAttempts++;
8361                 saveSettingsLocked(userHandle);
8362                 if (mHasFeature) {
8363                     strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
8364                             userHandle, /* parent= */ false);
8365                     int max = strictestAdmin != null
8366                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
8367 
8368                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
8369                         wipeData = true;
8370                     }
8371 
8372                     sendAdminCommandForLockscreenPoliciesLocked(
8373                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
8374                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
8375                 }
8376             }
8377         } finally {
8378             mInjector.binderRestoreCallingIdentity(ident);
8379         }
8380 
8381         if (wipeData && strictestAdmin != null) {
8382             final int userId = getUserIdToWipeForFailedPasswords(strictestAdmin);
8383             Slogf.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
8384                     + strictestAdmin.info.getComponent().flattenToShortString()
8385                     + ". Calling wipeData for user " + userId);
8386 
8387             // Attempt to wipe the device/user/profile associated with the admin, as if the
8388             // admin had called wipeData(). That way we can check whether the admin is actually
8389             // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
8390             // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
8391             // able to do so).
8392             // IMPORTANT: Call without holding the lock to prevent deadlock.
8393             try {
8394                 wipeDataNoLock(strictestAdmin.info.getComponent(),
8395                         /* flags= */ 0,
8396                         /* reason= */ "reportFailedPasswordAttempt()",
8397                         getFailedPasswordAttemptWipeMessage(),
8398                         userId,
8399                         /* calledOnParentInstance= */ parent,
8400                         // factoryReset=null to enable U- behaviour
8401                         /* factoryReset= */ null);
8402             } catch (SecurityException e) {
8403                 Slogf.w(LOG_TAG, "Failed to wipe user " + userId
8404                         + " after max failed password attempts reached.", e);
8405             }
8406         }
8407 
8408         if (mInjector.securityLogIsLoggingEnabled()) {
8409             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
8410                     /* result= */ 0, /* method strength= */ 1);
8411         }
8412     }
8413 
8414     private String getFailedPasswordAttemptWipeMessage() {
8415         return getUpdatableString(
8416                 WORK_PROFILE_DELETED_FAILED_PASSWORD_ATTEMPTS_MESSAGE,
8417                R.string.work_profile_deleted_reason_maximum_password_failure);
8418     }
8419 
8420     /**
8421      * Returns which user should be wiped if this admin's maximum filed password attempts policy is
8422      * violated.
8423      */
8424     private int getUserIdToWipeForFailedPasswords(ActiveAdmin admin) {
8425         final int userId = admin.getUserHandle().getIdentifier();
8426         if (admin.isPermissionBased) {
8427             return userId;
8428         }
8429         final ComponentName component = admin.info.getComponent();
8430         return isProfileOwnerOfOrganizationOwnedDevice(component, userId)
8431                 ? getProfileParentId(userId) : userId;
8432     }
8433 
8434     @Override
8435     public void reportSuccessfulPasswordAttempt(int userHandle) {
8436         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8437 
8438         final CallerIdentity caller = getCallerIdentity();
8439         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8440         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8441 
8442         synchronized (getLockObject()) {
8443             DevicePolicyData policy = getUserData(userHandle);
8444             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
8445                 mInjector.binderWithCleanCallingIdentity(() -> {
8446                     policy.mFailedPasswordAttempts = 0;
8447                     policy.mPasswordOwner = -1;
8448                     saveSettingsLocked(userHandle);
8449                     if (mHasFeature) {
8450                         sendAdminCommandForLockscreenPoliciesLocked(
8451                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
8452                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
8453                     }
8454                 });
8455             }
8456         }
8457 
8458         if (mInjector.securityLogIsLoggingEnabled()) {
8459             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
8460                     /*method strength*/ 1);
8461         }
8462     }
8463 
8464     @Override
8465     public void reportFailedBiometricAttempt(int userHandle) {
8466         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8467 
8468         final CallerIdentity caller = getCallerIdentity();
8469         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8470         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8471 
8472         if (mInjector.securityLogIsLoggingEnabled()) {
8473             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
8474                     /*method strength*/ 0);
8475         }
8476     }
8477 
8478     @Override
8479     public void reportSuccessfulBiometricAttempt(int userHandle) {
8480         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8481 
8482         final CallerIdentity caller = getCallerIdentity();
8483         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8484         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8485 
8486         if (mInjector.securityLogIsLoggingEnabled()) {
8487             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
8488                     /*method strength*/ 0);
8489         }
8490     }
8491 
8492     @Override
8493     public void reportKeyguardDismissed(int userHandle) {
8494         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8495 
8496         final CallerIdentity caller = getCallerIdentity();
8497         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8498         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8499 
8500         if (mInjector.securityLogIsLoggingEnabled()) {
8501             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
8502         }
8503     }
8504 
8505     @Override
8506     public void reportKeyguardSecured(int userHandle) {
8507         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8508 
8509         final CallerIdentity caller = getCallerIdentity();
8510         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8511         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
8512 
8513         if (mInjector.securityLogIsLoggingEnabled()) {
8514             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
8515         }
8516     }
8517 
8518     @Override
8519     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
8520             String exclusionList) {
8521         if (!mHasFeature) {
8522             return null;
8523         }
8524         synchronized (getLockObject()) {
8525             Objects.requireNonNull(who, "ComponentName is null");
8526 
8527             // Only check if system user has set global proxy. We don't allow other users to set it.
8528             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
8529             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8530                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
8531 
8532             // Scan through active admins and find if anyone has already
8533             // set the global proxy.
8534             Set<ComponentName> compSet = policy.mAdminMap.keySet();
8535             for (ComponentName component : compSet) {
8536                 ActiveAdmin ap = policy.mAdminMap.get(component);
8537                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
8538                     // Another admin already sets the global proxy
8539                     // Return it to the caller.
8540                     return component;
8541                 }
8542             }
8543 
8544             // If the user is not system, don't set the global proxy. Fail silently.
8545             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8546                 Slogf.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
8547                         + UserHandle.getCallingUserId() + " is not permitted.");
8548                 return null;
8549             }
8550             if (proxySpec == null) {
8551                 admin.specifiesGlobalProxy = false;
8552                 admin.globalProxySpec = null;
8553                 admin.globalProxyExclusionList = null;
8554             } else {
8555 
8556                 admin.specifiesGlobalProxy = true;
8557                 admin.globalProxySpec = proxySpec;
8558                 admin.globalProxyExclusionList = exclusionList;
8559             }
8560 
8561             // Reset the global proxy accordingly
8562             // Do this using system permissions, as apps cannot write to secure settings
8563             mInjector.binderWithCleanCallingIdentity(() -> resetGlobalProxyLocked(policy));
8564             return null;
8565         }
8566     }
8567 
8568     @Override
8569     public ComponentName getGlobalProxyAdmin(int userHandle) {
8570         if (!mHasFeature) {
8571             return null;
8572         }
8573         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8574 
8575         final CallerIdentity caller = getCallerIdentity();
8576         Preconditions.checkCallAuthorization(
8577                 hasFullCrossUsersPermission(caller, userHandle) && canQueryAdminPolicy(caller));
8578 
8579         synchronized (getLockObject()) {
8580             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
8581             // Scan through active admins and find if anyone has already
8582             // set the global proxy.
8583             final int N = policy.mAdminList.size();
8584             for (int i = 0; i < N; i++) {
8585                 ActiveAdmin ap = policy.mAdminList.get(i);
8586                 if (ap.specifiesGlobalProxy) {
8587                     // Device admin sets the global proxy
8588                     // Return it to the caller.
8589                     return ap.info.getComponent();
8590                 }
8591             }
8592         }
8593         // No device admin sets the global proxy.
8594         return null;
8595     }
8596 
8597     @Override
8598     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
8599         Objects.requireNonNull(who, "ComponentName is null");
8600         final CallerIdentity caller = getCallerIdentity(who);
8601         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
8602         checkAllUsersAreAffiliatedWithDevice();
8603         mInjector.binderWithCleanCallingIdentity(
8604                 () -> mInjector.getConnectivityManager().setGlobalProxy(proxyInfo));
8605     }
8606 
8607     private void resetGlobalProxyLocked(DevicePolicyData policy) {
8608         final int N = policy.mAdminList.size();
8609         for (int i = 0; i < N; i++) {
8610             ActiveAdmin ap = policy.mAdminList.get(i);
8611             if (ap.specifiesGlobalProxy) {
8612                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
8613                 return;
8614             }
8615         }
8616         // No device admins defining global proxies - reset global proxy settings to none
8617         saveGlobalProxyLocked(null, null);
8618     }
8619 
8620     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
8621         if (exclusionList == null) {
8622             exclusionList = "";
8623         }
8624         if (proxySpec == null) {
8625             proxySpec = "";
8626         }
8627         // Remove white spaces
8628         proxySpec = proxySpec.trim();
8629         String data[] = proxySpec.split(":");
8630         int proxyPort = 8080;
8631         if (data.length > 1) {
8632             try {
8633                 proxyPort = Integer.parseInt(data[1]);
8634             } catch (NumberFormatException e) {}
8635         }
8636         exclusionList = exclusionList.trim();
8637 
8638         ProxyInfo proxyProperties = ProxyInfo.buildDirectProxy(data[0], proxyPort,
8639                 ProxyUtils.exclusionStringAsList(exclusionList));
8640         if (!proxyProperties.isValid()) {
8641             Slogf.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
8642             return;
8643         }
8644         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
8645         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
8646         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
8647                 exclusionList);
8648     }
8649 
8650     /**
8651      * Called by an application that is administering the device to request that the storage system
8652      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
8653      *
8654      * @return the new total request status (for all admins), or {@link
8655      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user
8656      */
8657     @Override
8658     public int setStorageEncryption(ComponentName who, boolean encrypt) {
8659         if (!mHasFeature) {
8660             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8661         }
8662         Objects.requireNonNull(who, "ComponentName is null");
8663         final int userHandle = UserHandle.getCallingUserId();
8664         synchronized (getLockObject()) {
8665             // Check for permissions
8666             // Only system user can set storage encryption
8667             if (userHandle != UserHandle.USER_SYSTEM) {
8668                 Slogf.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. "
8669                         + "User " + UserHandle.getCallingUserId() + " is not permitted.");
8670                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8671             }
8672 
8673             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
8674                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
8675 
8676             // Quick exit:  If the filesystem does not support encryption, we can exit early.
8677             if (!isEncryptionSupported()) {
8678                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8679             }
8680 
8681             // (1) Record the value for the admin so it's sticky
8682             if (ap.encryptionRequested != encrypt) {
8683                 ap.encryptionRequested = encrypt;
8684                 saveSettingsLocked(userHandle);
8685             }
8686 
8687             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
8688             // (2) Compute "max" for all admins
8689             boolean newRequested = false;
8690             final int N = policy.mAdminList.size();
8691             for (int i = 0; i < N; i++) {
8692                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
8693             }
8694 
8695             // Notify OS of new request
8696             setEncryptionRequested(newRequested);
8697 
8698             // Return the new global request status
8699             return newRequested
8700                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
8701                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
8702         }
8703     }
8704 
8705     /**
8706      * Get the current storage encryption request status for a given admin, or aggregate of all
8707      * active admins.
8708      */
8709     @Override
8710     public boolean getStorageEncryption(@Nullable ComponentName who, int userHandle) {
8711         if (!mHasFeature) {
8712             return false;
8713         }
8714         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8715 
8716         final CallerIdentity caller = getCallerIdentity(who);
8717         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8718 
8719         synchronized (getLockObject()) {
8720             // Check for permissions if a particular caller is specified
8721             if (caller.hasAdminComponent()) {
8722                 // When checking for a single caller, status is based on caller's request
8723                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
8724                 return ap != null ? ap.encryptionRequested : false;
8725             }
8726 
8727             // If no particular caller is specified, return the aggregate set of requests.
8728             // This is short circuited by returning true on the first hit.
8729             DevicePolicyData policy = getUserData(userHandle);
8730             final int N = policy.mAdminList.size();
8731             for (int i = 0; i < N; i++) {
8732                 if (policy.mAdminList.get(i).encryptionRequested) {
8733                     return true;
8734                 }
8735             }
8736             return false;
8737         }
8738     }
8739 
8740     /**
8741      * Get the current encryption status of the device.
8742      */
8743     @Override
8744     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
8745         if (!mHasFeature) {
8746             // Ok to return current status.
8747         }
8748         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8749 
8750         final CallerIdentity caller = getCallerIdentity(callerPackage);
8751         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8752 
8753 
8754         final ApplicationInfo ai;
8755         try {
8756             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
8757         } catch (RemoteException e) {
8758             throw new SecurityException(e);
8759         }
8760 
8761         boolean legacyApp = false;
8762         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
8763             legacyApp = true;
8764         }
8765 
8766         final int rawStatus = getEncryptionStatus();
8767         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
8768             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
8769         }
8770         return rawStatus;
8771     }
8772 
8773     /**
8774      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
8775      */
8776     private boolean isEncryptionSupported() {
8777         // Note, this can be implemented as
8778         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8779         // But is provided as a separate internal method if there's a faster way to do a
8780         // simple check for supported-or-not.
8781         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8782     }
8783 
8784     /**
8785      * Hook to low-levels:  Reporting the current status of encryption.
8786      * @return Either {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}
8787      * or {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}.
8788      */
8789     private int getEncryptionStatus() {
8790         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
8791             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
8792         } else {
8793             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
8794         }
8795     }
8796 
8797     /**
8798      * Hook to low-levels:  If needed, record the new admin setting for encryption.
8799      */
8800     private void setEncryptionRequested(boolean encrypt) {
8801     }
8802 
8803     /**
8804      * Set whether the screen capture is disabled for the user managed by the specified admin.
8805      */
8806     @Override
8807     public void setScreenCaptureDisabled(
8808             ComponentName who, String callerPackage, boolean disabled, boolean parent) {
8809         if (!mHasFeature) {
8810             return;
8811         }
8812 
8813         CallerIdentity caller = getCallerIdentity(who, callerPackage);
8814         int callerUserId = Binder.getCallingUserHandle().getIdentifier();
8815         int targetUserId = parent ? getProfileParentId(callerUserId) : callerUserId;
8816         EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
8817                 who, MANAGE_DEVICE_POLICY_SCREEN_CAPTURE, caller.getPackageName(),
8818                 targetUserId);
8819         if ((parent && isProfileOwnerOfOrganizationOwnedDevice(caller))
8820                 || isDefaultDeviceOwner(caller)) {
8821             if (disabled) {
8822                 mDevicePolicyEngine.setGlobalPolicy(
8823                         PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8824                         admin,
8825                         new BooleanPolicyValue(disabled));
8826             } else {
8827                 mDevicePolicyEngine.removeGlobalPolicy(
8828                         PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8829                         admin);
8830             }
8831         } else {
8832             if (disabled) {
8833                 mDevicePolicyEngine.setLocalPolicy(
8834                         PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8835                         admin,
8836                         new BooleanPolicyValue(disabled),
8837                         callerUserId);
8838             } else {
8839                 mDevicePolicyEngine.removeLocalPolicy(
8840                         PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8841                         admin,
8842                         callerUserId);
8843             }
8844         }
8845         DevicePolicyEventLogger
8846                 .createEvent(DevicePolicyEnums.SET_SCREEN_CAPTURE_DISABLED)
8847                 .setAdmin(caller.getPackageName())
8848                 .setBoolean(disabled)
8849                 .write();
8850     }
8851 
8852     /**
8853      * Returns whether or not screen capture is disabled for  any active admin.
8854      */
8855     @Override
8856     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle, boolean parent) {
8857         if (!mHasFeature) {
8858             return false;
8859         }
8860         final CallerIdentity caller = getCallerIdentity(who);
8861         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8862 
8863         if (parent) {
8864             Preconditions.checkCallAuthorization(
8865                     isProfileOwnerOfOrganizationOwnedDevice(getCallerIdentity().getUserId()));
8866         }
8867         Boolean disallowed = mDevicePolicyEngine.getResolvedPolicy(
8868                 PolicyDefinition.SCREEN_CAPTURE_DISABLED,
8869                 userHandle);
8870         return disallowed != null && disallowed;
8871     }
8872 
8873     private void updateScreenCaptureDisabled() {
8874         mHandler.post(() -> {
8875             try {
8876                 mInjector.getIWindowManager().refreshScreenCaptureDisabled();
8877             } catch (RemoteException e) {
8878                 Slogf.w(LOG_TAG, "Unable to notify WindowManager.", e);
8879             }
8880         });
8881     }
8882 
8883     @Override
8884     public void setNearbyNotificationStreamingPolicy(int policy) {
8885         if (!mHasFeature) {
8886             return;
8887         }
8888 
8889         final CallerIdentity caller = getCallerIdentity();
8890         Preconditions.checkCallAuthorization(
8891                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
8892 
8893         synchronized (getLockObject()) {
8894             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
8895             if (admin.mNearbyNotificationStreamingPolicy != policy) {
8896                 admin.mNearbyNotificationStreamingPolicy = policy;
8897                 saveSettingsLocked(caller.getUserId());
8898             }
8899         }
8900     }
8901 
8902     @Override
8903     public int getNearbyNotificationStreamingPolicy(final int userId) {
8904         if (!mHasFeature) {
8905             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8906         }
8907 
8908         final CallerIdentity caller = getCallerIdentity();
8909         Preconditions.checkCallAuthorization(
8910                 isProfileOwner(caller) || isDefaultDeviceOwner(caller)
8911                         || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY));
8912         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
8913 
8914         synchronized (getLockObject()) {
8915             final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
8916             return admin != null
8917                     ? admin.mNearbyNotificationStreamingPolicy
8918                     : NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8919         }
8920     }
8921 
8922     @Override
8923     public void setNearbyAppStreamingPolicy(int policy) {
8924         if (!mHasFeature) {
8925             return;
8926         }
8927 
8928         final CallerIdentity caller = getCallerIdentity();
8929         Preconditions.checkCallAuthorization(
8930                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
8931 
8932         synchronized (getLockObject()) {
8933             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
8934             if (admin.mNearbyAppStreamingPolicy != policy) {
8935                 admin.mNearbyAppStreamingPolicy = policy;
8936                 saveSettingsLocked(caller.getUserId());
8937             }
8938         }
8939     }
8940 
8941     @Override
8942     public int getNearbyAppStreamingPolicy(final int userId) {
8943         if (!mHasFeature) {
8944             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8945         }
8946 
8947         final CallerIdentity caller = getCallerIdentity();
8948         Preconditions.checkCallAuthorization(
8949                 isProfileOwner(caller) || isDefaultDeviceOwner(caller)
8950                         || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY));
8951         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
8952 
8953         synchronized (getLockObject()) {
8954             final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
8955             return admin != null
8956                     ? admin.mNearbyAppStreamingPolicy
8957                     : NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
8958         }
8959     }
8960 
8961     /**
8962      * Set whether auto time is required by the specified admin (must be device or profile owner).
8963      */
8964     @Override
8965     public void setAutoTimeRequired(ComponentName who, boolean required) {
8966         if (!mHasFeature) {
8967             return;
8968         }
8969         Objects.requireNonNull(who, "ComponentName is null");
8970         final CallerIdentity caller = getCallerIdentity(who);
8971         Preconditions.checkCallAuthorization(
8972                 isDeviceOwner(caller) || isProfileOwner(caller));
8973 
8974         boolean requireAutoTimeChanged = false;
8975         synchronized (getLockObject()) {
8976             Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
8977                     "Managed profile cannot set auto time required");
8978 
8979             EnforcingAdmin admin = getEnforcingAdminForCaller(who, who.getPackageName());
8980             setGlobalUserRestrictionInternal(
8981                     admin, UserManager.DISALLOW_CONFIG_DATE_TIME, required);
8982         }
8983         // Turn AUTO_TIME on in settings if it is required
8984         if (required) {
8985             mInjector.binderWithCleanCallingIdentity(
8986                     () -> mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME,
8987                             1 /* AUTO_TIME on */));
8988         }
8989         DevicePolicyEventLogger
8990                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_REQUIRED)
8991                 .setAdmin(who)
8992                 .setBoolean(required)
8993                 .write();
8994     }
8995 
8996     /**
8997      * Returns whether or not auto time is required by the device owner or any profile owner.
8998      */
8999     @Override
9000     public boolean getAutoTimeRequired() {
9001         if (!mHasFeature) {
9002             return false;
9003         }
9004         Boolean required = mDevicePolicyEngine.getResolvedPolicy(
9005                 PolicyDefinition.getPolicyDefinitionForUserRestriction(
9006                         UserManager.DISALLOW_CONFIG_DATE_TIME),
9007                 mInjector.binderGetCallingUserHandle().getIdentifier());
9008         return required != null && required;
9009     }
9010 
9011     /**
9012      * Set whether auto time is enabled on the device.
9013      */
9014     @Override
9015     public void setAutoTimeEnabled(@Nullable ComponentName who, String callerPackageName,
9016             boolean enabled) {
9017         if (!mHasFeature) {
9018             return;
9019         }
9020 
9021         CallerIdentity caller;
9022         if (isUnicornFlagEnabled()) {
9023             caller = getCallerIdentity(who, callerPackageName);
9024         } else {
9025             caller = getCallerIdentity(who);
9026         }
9027 
9028         if (isUnicornFlagEnabled()) {
9029             // The effect of this policy is device-wide.
9030             enforcePermission(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
9031         } else {
9032             Objects.requireNonNull(who, "ComponentName is null");
9033             Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
9034                     || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
9035                     caller));
9036         }
9037         mInjector.binderWithCleanCallingIdentity(() ->
9038                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, enabled ? 1 : 0));
9039 
9040         DevicePolicyEventLogger
9041                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME)
9042                 .setAdmin(caller.getPackageName())
9043                 .setBoolean(enabled)
9044                 .write();
9045     }
9046 
9047     /**
9048      * Returns whether auto time is used on the device or not.
9049      */
9050     @Override
9051     public boolean getAutoTimeEnabled(@Nullable ComponentName who, String callerPackageName) {
9052         if (!mHasFeature) {
9053             return false;
9054         }
9055         CallerIdentity caller;
9056         if (isUnicornFlagEnabled()) {
9057             caller = getCallerIdentity(who, callerPackageName);
9058         } else {
9059             caller = getCallerIdentity(who);
9060         }
9061 
9062         if (isUnicornFlagEnabled()) {
9063             enforceCanQuery(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
9064         } else {
9065             Objects.requireNonNull(who, "ComponentName is null");
9066             Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
9067                     || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
9068                     caller));
9069         }
9070 
9071         return mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) > 0;
9072     }
9073 
9074     /**
9075      * Set whether auto time zone is enabled on the device.
9076      */
9077     @Override
9078     public void setAutoTimeZoneEnabled(@Nullable ComponentName who, String callerPackageName,
9079             boolean enabled) {
9080         if (!mHasFeature) {
9081             return;
9082         }
9083 
9084         CallerIdentity caller;
9085         if (isUnicornFlagEnabled()) {
9086             caller = getCallerIdentity(who, callerPackageName);
9087         } else {
9088             caller = getCallerIdentity(who);
9089         }
9090 
9091         if (isUnicornFlagEnabled()) {
9092             // The effect of this policy is device-wide.
9093             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
9094                     who,
9095                     SET_TIME_ZONE,
9096                     caller.getPackageName(),
9097                     UserHandle.USER_ALL
9098             );
9099             mDevicePolicyEngine.setGlobalPolicy(
9100                     PolicyDefinition.AUTO_TIMEZONE,
9101                     // TODO(b/260573124): add correct enforcing admin when permission changes are
9102                     //  merged.
9103                     enforcingAdmin,
9104                     new BooleanPolicyValue(enabled));
9105         } else {
9106             Objects.requireNonNull(who, "ComponentName is null");
9107             Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
9108                     || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
9109                     caller));
9110             mInjector.binderWithCleanCallingIdentity(() ->
9111                     mInjector.settingsGlobalPutInt(Global.AUTO_TIME_ZONE, enabled ? 1 : 0));
9112         }
9113 
9114         DevicePolicyEventLogger
9115                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_ZONE)
9116                 .setAdmin(caller.getPackageName())
9117                 .setBoolean(enabled)
9118                 .write();
9119     }
9120 
9121     /**
9122      * Returns whether auto time zone is used on the device or not.
9123      */
9124     @Override
9125     public boolean getAutoTimeZoneEnabled(@Nullable ComponentName who, String callerPackageName) {
9126         if (!mHasFeature) {
9127             return false;
9128         }
9129 
9130         CallerIdentity caller;
9131         if (isUnicornFlagEnabled()) {
9132             caller = getCallerIdentity(who, callerPackageName);
9133         } else {
9134             caller = getCallerIdentity(who);
9135         }
9136 
9137         if (isUnicornFlagEnabled()) {
9138             // The effect of this policy is device-wide.
9139             enforceCanQuery(SET_TIME_ZONE, caller.getPackageName(), UserHandle.USER_ALL);
9140         } else {
9141             Objects.requireNonNull(who, "ComponentName is null");
9142             Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
9143                     || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDefaultDeviceOwner(
9144                     caller));
9145         }
9146 
9147         return mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) > 0;
9148     }
9149 
9150     // TODO (b/137101239): remove this method in follow-up CL
9151     // since it's only used for split system user.
9152     @Override
9153     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
9154         throw new UnsupportedOperationException("This method was used by split system user only.");
9155     }
9156 
9157     // TODO (b/137101239): remove this method in follow-up CL
9158     // since it's only used for split system user.
9159     @Override
9160     public boolean getForceEphemeralUsers(ComponentName who) {
9161         throw new UnsupportedOperationException("This method was used by split system user only.");
9162     }
9163 
9164     @Override
9165     public boolean requestBugreport(ComponentName who) {
9166         if (!mHasFeature) {
9167             return false;
9168         }
9169         Objects.requireNonNull(who, "ComponentName is null");
9170         // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
9171         // which could still contain data related to that user. Should we disallow that, e.g. until
9172         // next boot? Might not be needed given that this still requires user consent.
9173         final CallerIdentity caller = getCallerIdentity(who);
9174         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
9175         checkAllUsersAreAffiliatedWithDevice();
9176         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REQUEST_BUGREPORT);
9177 
9178         if (mBugreportCollectionManager.requestBugreport()) {
9179             DevicePolicyEventLogger
9180                     .createEvent(DevicePolicyEnums.REQUEST_BUGREPORT)
9181                     .setAdmin(who)
9182                     .write();
9183 
9184             final long currentTime = System.currentTimeMillis();
9185             synchronized (getLockObject()) {
9186                 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
9187                 if (currentTime > policyData.mLastBugReportRequestTime) {
9188                     policyData.mLastBugReportRequestTime = currentTime;
9189                     saveSettingsLocked(UserHandle.USER_SYSTEM);
9190                 }
9191             }
9192 
9193             return true;
9194         } else {
9195             return false;
9196         }
9197     }
9198 
9199     void sendDeviceOwnerCommand(String action, Bundle extras) {
9200         final int deviceOwnerUserId;
9201         final ComponentName receiverComponent;
9202         synchronized (getLockObject()) {
9203             deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
9204             receiverComponent = mOwners.getDeviceOwnerComponent();
9205         }
9206         sendActiveAdminCommand(action, extras, deviceOwnerUserId, receiverComponent,
9207                 /* inForeground */ false);
9208     }
9209 
9210     void sendDeviceOwnerOrProfileOwnerCommand(String action, Bundle extras, int userId) {
9211         if (userId == UserHandle.USER_ALL) {
9212             if (Flags.headlessDeviceOwnerDelegateSecurityLoggingBugFix()
9213                     && getHeadlessDeviceOwnerModeForDeviceOwner()
9214                     == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER) {
9215                 userId = mOwners.getDeviceOwnerUserId();
9216             } else {
9217                 userId = UserHandle.USER_SYSTEM;
9218             }
9219         }
9220         boolean inForeground = false;
9221         ComponentName receiverComponent = null;
9222         if (action.equals(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE)) {
9223             inForeground = true;
9224             receiverComponent = resolveDelegateReceiver(DELEGATION_NETWORK_LOGGING, action, userId);
9225         }
9226         if (action.equals(DeviceAdminReceiver.ACTION_SECURITY_LOGS_AVAILABLE)) {
9227             inForeground = true;
9228             receiverComponent = resolveDelegateReceiver(
9229                 DELEGATION_SECURITY_LOGGING, action, userId);
9230         }
9231         if (receiverComponent == null) {
9232             receiverComponent = getOwnerComponent(userId);
9233         }
9234         sendActiveAdminCommand(action, extras, userId, receiverComponent, inForeground);
9235     }
9236 
9237     private void sendProfileOwnerCommand(String action, Bundle extras, @UserIdInt int userId) {
9238         sendActiveAdminCommand(action, extras, userId, mOwners.getProfileOwnerComponent(userId),
9239                 /* inForeground */ false);
9240     }
9241 
9242     private void sendActiveAdminCommand(String action, Bundle extras,
9243             @UserIdInt int userId, ComponentName receiverComponent, boolean inForeground) {
9244         final Intent intent = new Intent(action);
9245         intent.setComponent(receiverComponent);
9246         if (extras != null) {
9247             intent.putExtras(extras);
9248         }
9249         if (inForeground) {
9250             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9251         }
9252 
9253         if (VERBOSE_LOG) {
9254             Slogf.v(LOG_TAG, "sendActiveAdminCommand(): broadcasting " + action + " to "
9255                     + receiverComponent.flattenToShortString() + " on user " + userId);
9256         }
9257         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9258     }
9259 
9260     private void sendOwnerChangedBroadcast(String broadcast, int userId) {
9261         final Intent intent = new Intent(broadcast)
9262                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
9263         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9264     }
9265 
9266     void sendBugreportToDeviceOwner(Uri bugreportUri, String bugreportHash) {
9267         synchronized (getLockObject()) {
9268             final Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
9269             intent.setComponent(mOwners.getDeviceOwnerComponent());
9270             intent.setDataAndType(bugreportUri, RemoteBugreportManager.BUGREPORT_MIMETYPE);
9271             intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
9272             intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9273 
9274             final UriGrantsManagerInternal ugm = LocalServices
9275                     .getService(UriGrantsManagerInternal.class);
9276             final NeededUriGrants needed = ugm.checkGrantUriPermissionFromIntent(intent,
9277                     Process.SHELL_UID, mOwners.getDeviceOwnerComponent().getPackageName(),
9278                     mOwners.getDeviceOwnerUserId());
9279             ugm.grantUriPermissionUncheckedFromIntent(needed, null);
9280 
9281             mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
9282         }
9283     }
9284 
9285     void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash) {
9286         synchronized (getLockObject()) {
9287             mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
9288         }
9289     }
9290 
9291     Pair<String, String> getDeviceOwnerRemoteBugreportUriAndHash() {
9292         synchronized (getLockObject()) {
9293             final String uri = mOwners.getDeviceOwnerRemoteBugreportUri();
9294             return uri == null ? null
9295                     : new Pair<>(uri, mOwners.getDeviceOwnerRemoteBugreportHash());
9296         }
9297     }
9298 
9299     /**
9300      * Disables all device cameras according to the specified admin.
9301      */
9302     @Override
9303     public void setCameraDisabled(ComponentName who, String callerPackageName, boolean disabled,
9304             boolean parent) {
9305         if (!mHasFeature) {
9306             return;
9307         }
9308 
9309         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
9310         final int userId = caller.getUserId();
9311 
9312         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_CAMERA_DISABLED);
9313         EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
9314                 who,
9315                 MANAGE_DEVICE_POLICY_CAMERA,
9316                 caller.getPackageName(),
9317                 getProfileParentUserIfRequested(userId, parent));
9318         try {
9319             setBackwardCompatibleUserRestriction(
9320                     caller, enforcingAdmin, UserManager.DISALLOW_CAMERA, disabled, parent);
9321         } catch (IllegalStateException e) {
9322             throw new IllegalStateException(
9323                     "Please use addUserRestriction or addUserRestrictionGlobally using the key"
9324                             + " UserManager.DISALLOW_CAMERA to disable the camera locally or"
9325                             + " globally, respectively");
9326         }
9327 
9328         final int affectedUserId = parent ? getProfileParentId(userId) : userId;
9329         if (SecurityLog.isLoggingEnabled() && who != null) {
9330             SecurityLog.writeEvent(SecurityLog.TAG_CAMERA_POLICY_SET,
9331                     who.getPackageName(), userId, affectedUserId, disabled ? 1 : 0);
9332         }
9333         DevicePolicyEventLogger
9334                 .createEvent(DevicePolicyEnums.SET_CAMERA_DISABLED)
9335                 .setAdmin(caller.getPackageName())
9336                 .setBoolean(disabled)
9337                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
9338                 .write();
9339     }
9340 
9341     /**
9342      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
9343      * active admins.
9344      */
9345     @Override
9346     public boolean getCameraDisabled(ComponentName who, String callerPackageName, int userHandle,
9347             boolean parent) {
9348         if (!mHasFeature) {
9349             return false;
9350         }
9351         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
9352         Preconditions.checkCallAuthorization(
9353                 hasFullCrossUsersPermission(caller, userHandle)
9354                         || isCameraServerUid(caller)
9355                         || hasPermission(MANAGE_DEVICE_POLICY_CAMERA,
9356                             caller.getPackageName(), userHandle)
9357                         || hasPermission(QUERY_ADMIN_POLICY, caller.getPackageName()));
9358 
9359         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
9360         PolicyDefinition<Boolean> policy =
9361                 PolicyDefinition.getPolicyDefinitionForUserRestriction(
9362                         UserManager.DISALLOW_CAMERA);
9363         if (who != null) {
9364             EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackageName);
9365             Boolean value = null;
9366             if (isDeviceOwner(caller)) {
9367                 value = mDevicePolicyEngine.getGlobalPolicySetByAdmin(policy, admin);
9368             } else {
9369                 value = mDevicePolicyEngine.getLocalPolicySetByAdmin(
9370                         policy, admin, affectedUserId);
9371             }
9372             return Boolean.TRUE.equals(value);
9373 
9374         } else {
9375             return Boolean.TRUE.equals(
9376                     mDevicePolicyEngine.getResolvedPolicy(policy, affectedUserId));
9377         }
9378     }
9379 
9380     @Override
9381     public void setKeyguardDisabledFeatures(
9382             ComponentName who, String callerPackageName, int which, boolean parent) {
9383         if (!mHasFeature) {
9384             return;
9385         }
9386 
9387         CallerIdentity caller;
9388         if (isUnicornFlagEnabled()) {
9389             caller = getCallerIdentity(who, callerPackageName);
9390         } else {
9391             caller = getCallerIdentity(who);
9392             Objects.requireNonNull(who, "ComponentName is null");
9393         }
9394 
9395         final int userHandle = caller.getUserId();
9396         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
9397         synchronized (getLockObject()) {
9398             if (isUnicornFlagEnabled()) {
9399                 // SUPPORT USES_POLICY_DISABLE_KEYGUARD_FEATURES
9400                 EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
9401                         who, MANAGE_DEVICE_POLICY_KEYGUARD, caller.getPackageName(),
9402                         affectedUserId);
9403                 if (which == 0) {
9404                     mDevicePolicyEngine.removeLocalPolicy(
9405                             PolicyDefinition.KEYGUARD_DISABLED_FEATURES, admin, affectedUserId);
9406                 } else {
9407                     // TODO(b/273723433): revisit silent masking of features
9408                     if (isManagedProfile(userHandle)) {
9409                         if (parent) {
9410                             if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
9411                                 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
9412                             } else {
9413                                 which = which
9414                                         & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
9415                             }
9416                         } else {
9417                             which = which & PROFILE_KEYGUARD_FEATURES;
9418                         }
9419                     }
9420                     mDevicePolicyEngine.setLocalPolicy(PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
9421                             admin, new IntegerPolicyValue(which), affectedUserId);
9422                 }
9423                 invalidateBinderCaches();
9424             } else {
9425                 ActiveAdmin ap = getActiveAdminForCallerLocked(
9426                         who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
9427                 if (isManagedProfile(userHandle)) {
9428                     if (parent) {
9429                         if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
9430                             which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
9431                         } else {
9432                             which = which & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
9433                         }
9434                     } else {
9435                         which = which & PROFILE_KEYGUARD_FEATURES;
9436                     }
9437                 }
9438                 if (ap.disabledKeyguardFeatures != which) {
9439                     ap.disabledKeyguardFeatures = which;
9440                     saveSettingsLocked(userHandle);
9441                 }
9442             }
9443         }
9444         if (SecurityLog.isLoggingEnabled()) {
9445             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET,
9446                     caller.getPackageName(), userHandle, affectedUserId, which);
9447         }
9448         DevicePolicyEventLogger
9449                 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED_FEATURES)
9450                 .setAdmin(caller.getPackageName())
9451                 .setInt(which)
9452                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
9453                 .write();
9454     }
9455 
9456     /**
9457      * Gets the disabled state for features in keyguard for the given admin,
9458      * or the aggregate of all active admins if who is null.
9459      * This API is cached: invalidate with invalidateBinderCaches().
9460      */
9461     @Override
9462     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
9463         if (!mHasFeature) {
9464             return 0;
9465         }
9466         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
9467 
9468         final CallerIdentity caller = getCallerIdentity();
9469         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
9470         Preconditions.checkCallAuthorization(
9471                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
9472                         || isSystemUid(caller));
9473         int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
9474 
9475         synchronized (getLockObject()) {
9476             if (who != null) {
9477                 if (isUnicornFlagEnabled()) {
9478                     EnforcingAdmin admin = getEnforcingAdminForPackage(
9479                             who, who.getPackageName(), userHandle);
9480                     Integer features = mDevicePolicyEngine.getLocalPolicySetByAdmin(
9481                             PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
9482                             admin,
9483                             affectedUserId);
9484 
9485                     return features == null ? 0 : features;
9486                 } else {
9487                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
9488                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
9489                 }
9490             }
9491 
9492             // TODO: with a quick glance this logic seems incomplete that it doesn't properly handle
9493             // the different behaviour between a profile with separate challenge vs a profile with
9494             // unified challenge, which was part of getActiveAdminsForLockscreenPoliciesLocked()
9495             // before the migration.
9496             if (isUnicornFlagEnabled()) {
9497                 Integer features = mDevicePolicyEngine.getResolvedPolicy(
9498                         PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
9499                         affectedUserId);
9500 
9501                 return Binder.withCleanCallingIdentity(() -> {
9502                     int combinedFeatures = features == null ? 0 : features;
9503                     List<UserInfo> profiles = mUserManager.getProfiles(affectedUserId);
9504                     for (UserInfo profile : profiles) {
9505                         int profileId = profile.id;
9506                         if (profileId == affectedUserId) {
9507                             continue;
9508                         }
9509                         Integer profileFeatures = mDevicePolicyEngine.getResolvedPolicy(
9510                                 PolicyDefinition.KEYGUARD_DISABLED_FEATURES,
9511                                 profileId);
9512                         if (profileFeatures != null) {
9513                             combinedFeatures |= (profileFeatures
9514                                     & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
9515                         }
9516                     }
9517                     return combinedFeatures;
9518                 });
9519             }
9520 
9521             final long ident = mInjector.binderClearCallingIdentity();
9522             try {
9523                 final List<ActiveAdmin> admins;
9524                 if (!parent && isManagedProfile(userHandle)) {
9525                     // If we are being asked about a managed profile, just return keyguard features
9526                     // disabled by admins in the profile.
9527                     admins = getUserDataUnchecked(userHandle).mAdminList;
9528                 } else {
9529                     // Otherwise return those set by admins in the user and its profiles.
9530                     admins = getActiveAdminsForLockscreenPoliciesLocked(
9531                             getProfileParentUserIfRequested(userHandle, parent));
9532                 }
9533 
9534                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
9535                 final int N = admins.size();
9536                 for (int i = 0; i < N; i++) {
9537                     ActiveAdmin admin = admins.get(i);
9538                     int userId = admin.getUserHandle().getIdentifier();
9539                     boolean isRequestedUser = !parent && (userId == userHandle);
9540                     if (isRequestedUser || !isManagedProfile(userId)) {
9541                         // If we are being asked explicitly about this user
9542                         // return all disabled features even if its a managed profile.
9543                         which |= admin.disabledKeyguardFeatures;
9544                     } else {
9545                         // Otherwise a managed profile is only allowed to disable
9546                         // some features on the parent user.
9547                         which |= (admin.disabledKeyguardFeatures
9548                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
9549                     }
9550                 }
9551                 return which;
9552             } finally {
9553                 mInjector.binderRestoreCallingIdentity(ident);
9554             }
9555         }
9556     }
9557 
9558     @Override
9559     public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
9560             List<String> packageList) {
9561         if (!mHasFeature) {
9562             return;
9563         }
9564         Objects.requireNonNull(packageList, "packageList is null");
9565         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
9566         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
9567                 &&  isDefaultDeviceOwner(caller))
9568                 || (caller.hasPackage()
9569                 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES)));
9570         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEEP_UNINSTALLED_PACKAGES);
9571 
9572         synchronized (getLockObject()) {
9573             // Get the device owner
9574             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9575             // Set list of packages to be kept even if uninstalled.
9576             deviceOwner.keepUninstalledPackages = packageList;
9577             // Save settings.
9578             saveSettingsLocked(caller.getUserId());
9579             // Notify package manager.
9580             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
9581         }
9582         DevicePolicyEventLogger
9583                 .createEvent(DevicePolicyEnums.SET_KEEP_UNINSTALLED_PACKAGES)
9584                 .setAdmin(caller.getPackageName())
9585                 .setBoolean(/* isDelegate */ who == null)
9586                 .setStrings(packageList.toArray(new String[0]))
9587                 .write();
9588     }
9589 
9590     @Override
9591     public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
9592         if (!mHasFeature) {
9593             return null;
9594         }
9595         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
9596         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
9597                 &&  isDefaultDeviceOwner(caller))
9598                 || (caller.hasPackage()
9599                 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES)));
9600 
9601         synchronized (getLockObject()) {
9602             return getKeepUninstalledPackagesLocked();
9603         }
9604     }
9605 
9606     private List<String> getKeepUninstalledPackagesLocked() {
9607         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9608         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
9609     }
9610 
9611     /**
9612      * Logs a warning when the device doesn't have {@code PackageManager.FEATURE_DEVICE_ADMIN}.
9613      *
9614      * @param message action that was not executed; should not end with a period because the missing
9615      * feature will be appended to it.
9616      */
9617     private void logMissingFeatureAction(String message) {
9618         Slogf.w(LOG_TAG, message + " because device does not have the "
9619                 + PackageManager.FEATURE_DEVICE_ADMIN + " feature.");
9620     }
9621 
9622     @Override
9623     public boolean setDeviceOwner(ComponentName admin, int userId,
9624             boolean setProfileOwnerOnCurrentUserIfNecessary) {
9625         if (!mHasFeature) {
9626             logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(admin)
9627                     + " as device owner for user " + userId);
9628             return false;
9629         }
9630         Preconditions.checkArgument(admin != null);
9631 
9632         final CallerIdentity caller = getCallerIdentity();
9633 
9634         boolean hasIncompatibleAccountsOrNonAdb =
9635                 !isAdb(caller) || hasIncompatibleAccountsOnAnyUser();
9636 
9637         if (!hasIncompatibleAccountsOrNonAdb) {
9638             synchronized (getLockObject()) {
9639                 if (!isAdminTestOnlyLocked(admin, userId) && hasAccountsOnAnyUser()) {
9640                     Slogf.w(LOG_TAG,
9641                             "Non test-only owner can't be installed with existing accounts.");
9642                     return false;
9643                 }
9644             }
9645         }
9646 
9647         synchronized (getLockObject()) {
9648             enforceCanSetDeviceOwnerLocked(caller, admin, userId, hasIncompatibleAccountsOrNonAdb);
9649 
9650             Preconditions.checkArgument(isPackageInstalledForUser(admin.getPackageName(), userId),
9651                     "Invalid component " + admin + " for device owner");
9652             final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
9653             Preconditions.checkArgument(activeAdmin != null && !getUserData(
9654                     userId).mRemovingAdmins.contains(admin), "Not active admin: " + admin);
9655 
9656             // Shutting down backup manager service permanently.
9657             toggleBackupServiceActive(UserHandle.USER_SYSTEM, /* makeActive= */ false);
9658             if (isAdb(caller)) {
9659                 // Log device owner provisioning was started using adb.
9660                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
9661                 DevicePolicyEventLogger
9662                         .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
9663                         .setAdmin(admin)
9664                         .setStrings(LOG_TAG_DEVICE_OWNER)
9665                         .write();
9666             }
9667 
9668             mOwners.setDeviceOwner(admin, userId);
9669             mOwners.writeDeviceOwner();
9670 
9671             //TODO(b/180371154): when provisionFullyManagedDevice is used in tests, remove this
9672             // hard-coded default value setting.
9673             if (isAdb(caller)) {
9674                 activeAdmin.mAdminCanGrantSensorsPermissions = true;
9675                 mPolicyCache.setAdminCanGrantSensorsPermissions(true);
9676                 saveSettingsLocked(userId);
9677             }
9678 
9679             mInjector.binderWithCleanCallingIdentity(() -> {
9680                 // Restrict adding a managed profile when a device owner is set on the device.
9681                 // That is to prevent the co-existence of a managed profile and a device owner
9682                 // on the same device.
9683                 // Instead, the device may be provisioned with an organization-owned managed
9684                 // profile, such that the admin on that managed profile has extended management
9685                 // capabilities that can affect the entire device (but not access private data
9686                 // on the primary profile).
9687                 for (int u : mUserManagerInternal.getUserIds()) {
9688                     mUserManager.setUserRestriction(
9689                             UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
9690                             UserHandle.of(u));
9691                     // Restrict adding a clone profile when a device owner is set on the device.
9692                     // That is to prevent the co-existence of a clone profile and a device owner
9693                     // on the same device.
9694                     // CDD for reference : https://source.android.com/compatibility/12/android-12-cdd#95_multi-user_support
9695                     mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_CLONE_PROFILE,
9696                             true,
9697                             UserHandle.of(u));
9698 
9699                     // Restrict adding a private profile when a device owner is set.
9700                     mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_PRIVATE_PROFILE,
9701                             true,
9702                             UserHandle.of(u));
9703                 }
9704 
9705                 // TODO Send to system too?
9706                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId);
9707             });
9708             mDeviceAdminServiceController.startServiceForAdmin(
9709                     admin.getPackageName(), userId, "set-device-owner");
9710 
9711             Slogf.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
9712         }
9713 
9714         if (setProfileOwnerOnCurrentUserIfNecessary
9715                 && mInjector.userManagerIsHeadlessSystemUserMode()
9716                 && getHeadlessDeviceOwnerModeForDeviceOwner()
9717                 == HEADLESS_DEVICE_OWNER_MODE_AFFILIATED) {
9718             int currentForegroundUser;
9719             synchronized (getLockObject()) {
9720                 currentForegroundUser = getCurrentForegroundUserId();
9721             }
9722             Slogf.i(LOG_TAG, "setDeviceOwner(): setting " + admin
9723                     + " as profile owner on user " + currentForegroundUser);
9724             // Sets profile owner on current foreground user since
9725             // the human user will complete the DO setup workflow from there.
9726             manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin,
9727                     /* managedUser= */ currentForegroundUser, /* adminExtras= */ null,
9728                     /* showDisclaimer= */ false);
9729         }
9730         return true;
9731     }
9732 
9733     private int getHeadlessDeviceOwnerModeForDeviceOwner() {
9734         synchronized (getLockObject()) {
9735             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9736             if (deviceOwner == null) {
9737                 return HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED;
9738             }
9739             return deviceOwner.info.getHeadlessDeviceOwnerMode();
9740         }
9741     }
9742 
9743     private int getHeadlessDeviceOwnerModeForDeviceAdmin(
9744             @Nullable ComponentName deviceAdmin, int userId) {
9745         synchronized (getLockObject()) {
9746             if (deviceAdmin == null) {
9747                 return HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED;
9748             }
9749             DeviceAdminInfo adminInfo = findAdmin(
9750                     deviceAdmin, userId, /* throwForMissingPermission= */ false);
9751             if (adminInfo == null) {
9752                 return HEADLESS_DEVICE_OWNER_MODE_UNSUPPORTED;
9753             }
9754             return adminInfo.getHeadlessDeviceOwnerMode();
9755         }
9756     }
9757 
9758     /**
9759      * This API is cached: invalidate with invalidateBinderCaches().
9760      */
9761     @Override
9762     public boolean hasDeviceOwner() {
9763         final CallerIdentity caller = getCallerIdentity();
9764         Preconditions.checkCallAuthorization(
9765                 isDefaultDeviceOwner(caller) || canManageUsers(caller) || isFinancedDeviceOwner(
9766                         caller) || hasCallingOrSelfPermission(
9767                         MANAGE_PROFILE_AND_DEVICE_OWNERS));
9768         return mOwners.hasDeviceOwner();
9769     }
9770 
9771     boolean isDeviceOwner(ActiveAdmin admin) {
9772         return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
9773     }
9774 
9775     /**
9776      * Check if the user is a Device Owner
9777      *
9778      * @param who    component to check against
9779      * @param userId user to check
9780      * @return if the user is a Device Owner
9781      */
9782     public boolean isDeviceOwner(@Nullable ComponentName who, int userId) {
9783         synchronized (getLockObject()) {
9784             return mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userId
9785                     && mOwners.getDeviceOwnerComponent().equals(who);
9786         }
9787     }
9788 
9789     /**
9790      * Returns {@code true} <b>only if</b> the caller is the device owner and the device owner type
9791      * is {@link DevicePolicyManager#DEVICE_OWNER_TYPE_DEFAULT}. {@code false} is returned for the
9792      * case where the caller is not the device owner, there is no device owner, or the device owner
9793      * type is not {@link DevicePolicyManager#DEVICE_OWNER_TYPE_DEFAULT}.
9794      *
9795      */
9796     private boolean isDefaultDeviceOwner(CallerIdentity caller) {
9797         synchronized (getLockObject()) {
9798             return isDeviceOwnerLocked(caller) && getDeviceOwnerTypeLocked(
9799                     mOwners.getDeviceOwnerPackageName()) == DEVICE_OWNER_TYPE_DEFAULT;
9800         }
9801     }
9802 
9803     /**
9804      * Returns {@code true} if the provided caller identity is of a device owner.
9805      * @param caller identity of caller.
9806      * @return true if {@code identity} is a device owner, false otherwise.
9807      */
9808     public boolean isDeviceOwner(CallerIdentity caller) {
9809         synchronized (getLockObject()) {
9810             return isDeviceOwnerLocked(caller);
9811         }
9812     }
9813 
9814     private boolean isDeviceOwnerLocked(CallerIdentity caller) {
9815         if (!mOwners.hasDeviceOwner() || mOwners.getDeviceOwnerUserId() != caller.getUserId()) {
9816             return false;
9817         }
9818 
9819         if (caller.hasAdminComponent()) {
9820             return mOwners.getDeviceOwnerComponent().equals(caller.getComponentName());
9821         } else {
9822             return isUidDeviceOwnerLocked(caller.getUid());
9823         }
9824     }
9825 
9826     private boolean isDeviceOwnerUserId(int userId) {
9827         synchronized (getLockObject()) {
9828             return mOwners.getDeviceOwnerComponent() != null
9829                     && mOwners.getDeviceOwnerUserId() == userId;
9830         }
9831     }
9832 
9833     /**
9834      * Check if {@link userId} is a Profile Owner
9835      *
9836      * @param who    component to check against
9837      * @param userId user to check
9838      * @return if the user is a Profile Owner
9839      */
9840     public boolean isProfileOwner(@Nullable ComponentName who, int userId) {
9841         final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(
9842                 () -> getProfileOwnerAsUser(userId));
9843         return who != null && who.equals(profileOwner);
9844     }
9845 
9846     /**
9847      * Returns {@code true} if the provided caller identity is of a profile owner.
9848      * @param caller identity of caller.
9849      * @return true if {@code identity} is a profile owner, false otherwise.
9850      */
9851     public boolean isProfileOwner(CallerIdentity caller) {
9852         synchronized (getLockObject()) {
9853             final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() ->
9854                     getProfileOwnerAsUser(caller.getUserId()));
9855             // No profile owner.
9856             if (profileOwner == null) {
9857                 return false;
9858             }
9859             // The admin ComponentName was specified, check it directly.
9860             if (caller.hasAdminComponent()) {
9861                 return profileOwner.equals(caller.getComponentName());
9862             } else {
9863                 return isUidProfileOwnerLocked(caller.getUid());
9864             }
9865         }
9866     }
9867 
9868     /**
9869      * Checks if the app uid provided is the profile owner. This method should only be called
9870      * if no componentName is available.
9871      *
9872      * @param appUid UID of the caller.
9873      * @return true if the caller is the profile owner
9874      */
9875     private boolean isUidProfileOwnerLocked(int appUid) {
9876         ensureLocked();
9877 
9878         final int userId = UserHandle.getUserId(appUid);
9879         final ComponentName profileOwnerComponent = mOwners.getProfileOwnerComponent(userId);
9880         if (profileOwnerComponent == null) {
9881             return false;
9882         }
9883         for (ActiveAdmin admin : getUserData(userId).mAdminList) {
9884             final ComponentName currentAdminComponent = admin.info.getComponent();
9885             if (admin.getUid() == appUid && profileOwnerComponent.equals(currentAdminComponent)) {
9886                 return true;
9887             }
9888         }
9889         return false;
9890     }
9891 
9892     private boolean hasProfileOwner(int userId) {
9893         synchronized (getLockObject()) {
9894             return mOwners.hasProfileOwner(userId);
9895         }
9896     }
9897 
9898     /**
9899      * Returns {@code true} if the provided caller identity is of a profile owner of an organization
9900      * owned device.
9901      *
9902      * @param caller identity of caller
9903      * @return true if {@code identity} is a profile owner of an organization owned device, false
9904      * otherwise.
9905      */
9906     private boolean isProfileOwnerOfOrganizationOwnedDevice(CallerIdentity caller) {
9907         return isProfileOwner(caller) && isProfileOwnerOfOrganizationOwnedDevice(
9908                 caller.getUserId());
9909     }
9910 
9911     private boolean isProfileOwnerOfOrganizationOwnedDevice(int userId) {
9912         synchronized (getLockObject()) {
9913             return mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId);
9914         }
9915     }
9916 
9917     private boolean isProfileOwnerOfOrganizationOwnedDevice(ComponentName who, int userId) {
9918         return isProfileOwner(who, userId) && isProfileOwnerOfOrganizationOwnedDevice(userId);
9919     }
9920 
9921     private boolean isProfileOwnerOnUser0(CallerIdentity caller) {
9922         return isProfileOwner(caller) && caller.getUserHandle().isSystem();
9923     }
9924 
9925     private boolean isPackage(CallerIdentity caller, String packageName) {
9926         return isCallingFromPackage(packageName, caller.getUid());
9927     }
9928 
9929     @Override
9930     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
9931         if (!mHasFeature) {
9932             return null;
9933         }
9934         if (!callingUserOnly) {
9935             Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
9936                     || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
9937         }
9938         synchronized (getLockObject()) {
9939             if (!mOwners.hasDeviceOwner()) {
9940                 return null;
9941             }
9942             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
9943                     mOwners.getDeviceOwnerUserId()) {
9944                 return null;
9945             }
9946             return mOwners.getDeviceOwnerComponent();
9947         }
9948     }
9949 
9950     @Override
9951     public ComponentName getDeviceOwnerComponentOnUser(int userId) {
9952         if (!mHasFeature) {
9953             return null;
9954         }
9955         if (mInjector.userHandleGetCallingUserId() != userId) {
9956             Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
9957                     || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
9958         }
9959         synchronized (getLockObject()) {
9960             // There is only ever one device owner on a device so if the passed userId is the same
9961             // as the device owner userId we know that the componentName returned by
9962             // getDeviceOwnerComponent will be the correct one.
9963             if (mOwners.getDeviceOwnerUserId() == userId || userId == UserHandle.USER_ALL) {
9964                 return mOwners.getDeviceOwnerComponent();
9965             }
9966         }
9967         return null;
9968     }
9969 
9970     private int getDeviceOwnerUserIdUncheckedLocked() {
9971         return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
9972     }
9973 
9974     @Override
9975     public int getDeviceOwnerUserId() {
9976         if (!mHasFeature) {
9977             return UserHandle.USER_NULL;
9978         }
9979         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
9980 
9981         synchronized (getLockObject()) {
9982             return getDeviceOwnerUserIdUncheckedLocked();
9983         }
9984     }
9985 
9986     private @UserIdInt int getMainUserId() {
9987         int mainUserId = mUserManagerInternal.getMainUserId();
9988         if (mainUserId == UserHandle.USER_NULL) {
9989             Slogf.d(LOG_TAG, "getMainUserId(): no main user, returning USER_SYSTEM");
9990             return UserHandle.USER_SYSTEM;
9991         }
9992         return mainUserId;
9993     }
9994 
9995     // TODO(b/240562946): Remove api as owner name is not used.
9996     /**
9997      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
9998      * MANAGE_USERS.
9999      */
10000     @Override
10001     public String getDeviceOwnerName() {
10002         if (!mHasFeature) {
10003             return null;
10004         }
10005         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
10006                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10007 
10008         synchronized (getLockObject()) {
10009             if (!mOwners.hasDeviceOwner()) {
10010                 return null;
10011             }
10012             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
10013             // Should setDeviceOwner/ProfileOwner still take a name?
10014             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
10015             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
10016         }
10017     }
10018 
10019     /** Returns the active device owner or {@code null} if there is no device owner. */
10020     @VisibleForTesting
10021     ActiveAdmin getDeviceOwnerAdminLocked() {
10022         ensureLocked();
10023         ComponentName component = mOwners.getDeviceOwnerComponent();
10024         if (component == null) {
10025             return null;
10026         }
10027 
10028         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
10029         final int n = policy.mAdminList.size();
10030         for (int i = 0; i < n; i++) {
10031             ActiveAdmin admin = policy.mAdminList.get(i);
10032             if (component.equals(admin.info.getComponent())) {
10033                 return admin;
10034             }
10035         }
10036         Slogf.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
10037         return null;
10038     }
10039 
10040     /**
10041      * @deprecated Use the version which does not take a user id.
10042      */
10043     @Deprecated
10044     ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(int userId) {
10045         ensureLocked();
10046         ActiveAdmin admin = getDeviceOwnerAdminLocked();
10047         if (admin == null) {
10048             admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
10049         }
10050         return admin;
10051     }
10052 
10053     ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked() {
10054         ensureLocked();
10055         ActiveAdmin admin = getDeviceOwnerAdminLocked();
10056         if (admin == null) {
10057             admin = getProfileOwnerOfOrganizationOwnedDeviceLocked();
10058         }
10059         return admin;
10060     }
10061 
10062     ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked() {
10063         ensureLocked();
10064         ActiveAdmin doOrPo = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
10065         if (isPermissionCheckFlagEnabled() && doOrPo == null) {
10066             return getUserData(0).mPermissionBasedAdmin;
10067         }
10068         return doOrPo;
10069     }
10070 
10071     @Override
10072     public void clearDeviceOwner(String packageName) {
10073         Objects.requireNonNull(packageName, "packageName is null");
10074 
10075         final CallerIdentity caller = getCallerIdentity(packageName);
10076         synchronized (getLockObject()) {
10077             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
10078             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
10079             if (!mOwners.hasDeviceOwner()
10080                     || !deviceOwnerComponent.getPackageName().equals(packageName)
10081                     || (deviceOwnerUserId != caller.getUserId())) {
10082                 throw new SecurityException(
10083                         "clearDeviceOwner can only be called by the device owner");
10084             }
10085             enforceUserUnlocked(deviceOwnerUserId);
10086 
10087             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
10088             mInjector.binderWithCleanCallingIdentity(() -> {
10089                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
10090                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
10091                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED,
10092                         deviceOwnerUserId);
10093             });
10094             Slogf.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
10095         }
10096     }
10097 
10098     private void clearOverrideApnUnchecked() {
10099         if (!mHasTelephonyFeature) {
10100             return;
10101         }
10102         // Disable Override APNs and remove them from database.
10103         setOverrideApnsEnabledUnchecked(false);
10104         final List<ApnSetting> apns = getOverrideApnsUnchecked();
10105         for (int i = 0; i < apns.size(); i ++) {
10106             removeOverrideApnUnchecked(apns.get(i).getId());
10107         }
10108     }
10109 
10110     private void clearManagedProfileApnUnchecked() {
10111         if (!mHasTelephonyFeature) {
10112             return;
10113         }
10114         if (!LocalServices.getService(SystemServiceManager.class).isBootCompleted()) {
10115             Slogf.i(LOG_TAG, "Skip clearing managed profile Apn before boot completed");
10116             // Cannot talk to APN content provider before system boots
10117             // Ideally we should delay the cleanup post boot_completed, not just
10118             // skipping  it altogether.
10119             return;
10120         }
10121         final List<ApnSetting> apns = getOverrideApnsUnchecked();
10122         for (ApnSetting apn : apns) {
10123             if (apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
10124                 removeOverrideApnUnchecked(apn.getId());
10125             }
10126         }
10127     }
10128 
10129     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
10130         String ownersPackage = mOwners.getDeviceOwnerPackageName();
10131         if (ownersPackage != null) {
10132             mDeviceAdminServiceController.stopServiceForAdmin(
10133                     ownersPackage, userId, "clear-device-owner");
10134         }
10135 
10136         if (admin != null) {
10137             admin.disableCamera = false;
10138             admin.userRestrictions = null;
10139             admin.defaultEnabledRestrictionsAlreadySet.clear();
10140             admin.forceEphemeralUsers = false;
10141             admin.isNetworkLoggingEnabled = false;
10142             admin.requireAutoTime = false;
10143             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
10144         }
10145         final DevicePolicyData policyData = getUserData(userId);
10146         policyData.mCurrentInputMethodSet = false;
10147         if (policyData.mPasswordTokenHandle != 0) {
10148             mLockPatternUtils.removeEscrowToken(policyData.mPasswordTokenHandle, userId);
10149             policyData.mPasswordTokenHandle = 0;
10150         }
10151         saveSettingsLocked(userId);
10152         mPolicyCache.onUserRemoved(userId);
10153         final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
10154         systemPolicyData.mLastSecurityLogRetrievalTime = -1;
10155         systemPolicyData.mLastBugReportRequestTime = -1;
10156         systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
10157         saveSettingsLocked(UserHandle.USER_SYSTEM);
10158         clearUserPoliciesLocked(userId);
10159         clearOverrideApnUnchecked();
10160         clearApplicationRestrictions(userId);
10161 
10162         mOwners.clearDeviceOwner();
10163         mOwners.writeDeviceOwner();
10164 
10165         updateAdminCanGrantSensorsPermissionCache(userId);
10166         clearDeviceOwnerUserRestriction(UserHandle.of(userId));
10167         mInjector.securityLogSetLoggingEnabledProperty(false);
10168         mSecurityLogMonitor.stop();
10169         setNetworkLoggingActiveInternal(false);
10170         deleteTransferOwnershipBundleLocked(userId);
10171         toggleBackupServiceActive(UserHandle.USER_SYSTEM, true);
10172         setGlobalSettingDeviceOwnerType(DEVICE_OWNER_TYPE_DEFAULT);
10173 
10174         mDevicePolicyEngine.removePoliciesForAdmin(
10175                 EnforcingAdmin.createEnterpriseEnforcingAdmin(
10176                         admin.info.getComponent(), userId, admin));
10177     }
10178 
10179     private void clearApplicationRestrictions(int userId) {
10180         // Changing app restrictions involves disk IO, offload it to the background thread.
10181         mBackgroundHandler.post(() -> {
10182             final List<PackageInfo> installedPackageInfos = mInjector.getPackageManager(userId)
10183                     .getInstalledPackages(MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
10184             final UserHandle userHandle = UserHandle.of(userId);
10185             for (final PackageInfo packageInfo : installedPackageInfos) {
10186                 mInjector.getUserManager().setApplicationRestrictions(
10187                         packageInfo.packageName, null /* restrictions */, userHandle);
10188             }
10189         });
10190     }
10191 
10192     @Override
10193     public boolean setProfileOwner(ComponentName who, int userHandle) {
10194         if (!mHasFeature) {
10195             logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(who)
10196                     + " as profile owner for user " + userHandle);
10197             return false;
10198         }
10199         Preconditions.checkArgument(who != null);
10200 
10201         final CallerIdentity caller = getCallerIdentity();
10202         // Cannot be called while holding the lock:
10203         final boolean hasIncompatibleAccountsOrNonAdb =
10204                 hasIncompatibleAccountsOrNonAdbNoLock(caller, userHandle, who);
10205         synchronized (getLockObject()) {
10206             enforceCanSetProfileOwnerLocked(
10207                     caller, who, userHandle, hasIncompatibleAccountsOrNonAdb);
10208             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10209             Preconditions.checkArgument(
10210                     isPackageInstalledForUser(who.getPackageName(), userHandle)
10211                             && admin != null
10212                             && !getUserData(userHandle).mRemovingAdmins.contains(who),
10213                     "Not active admin: " + who);
10214 
10215             final int parentUserId = getProfileParentId(userHandle);
10216             // When trying to set a profile owner on a new user, it may be that this user is
10217             // a profile - but it may not be a managed profile if there's a restriction on the
10218             // parent to add managed profiles (e.g. if the device has a device owner).
10219             if (parentUserId != userHandle && mUserManager.hasUserRestriction(
10220                     UserManager.DISALLOW_ADD_MANAGED_PROFILE,
10221                     UserHandle.of(parentUserId))) {
10222                 Slogf.i(LOG_TAG, "Cannot set profile owner because of restriction.");
10223                 return false;
10224             }
10225 
10226             if (isAdb(caller)) {
10227                 // Log profile owner provisioning was started using adb.
10228                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
10229                 DevicePolicyEventLogger
10230                         .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
10231                         .setAdmin(who)
10232                         .setStrings(LOG_TAG_PROFILE_OWNER)
10233                         .write();
10234             }
10235 
10236             // Shutting down backup manager service permanently.
10237             toggleBackupServiceActive(userHandle, /* makeActive= */ false);
10238 
10239             mOwners.setProfileOwner(who, userHandle);
10240             mOwners.writeProfileOwner(userHandle);
10241             Slogf.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
10242 
10243             mInjector.binderWithCleanCallingIdentity(() -> {
10244                 if (mUserManager.isManagedProfile(userHandle)) {
10245                     maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin);
10246                     ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
10247                             true /* newOwner */);
10248                 }
10249                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
10250                         userHandle);
10251             });
10252             mDeviceAdminServiceController.startServiceForAdmin(
10253                     who.getPackageName(), userHandle, "set-profile-owner");
10254             return true;
10255         }
10256     }
10257 
10258     private void toggleBackupServiceActive(int userId, boolean makeActive) {
10259         long ident = mInjector.binderClearCallingIdentity();
10260         try {
10261             if (mInjector.getIBackupManager() != null) {
10262                 mInjector.getIBackupManager()
10263                         .setBackupServiceActive(userId, makeActive);
10264             }
10265         } catch (RemoteException e) {
10266             throw new IllegalStateException(String.format("Failed %s backup service.",
10267                     makeActive ? "activating" : "deactivating"), e);
10268         } finally {
10269             mInjector.binderRestoreCallingIdentity(ident);
10270         }
10271 
10272     }
10273 
10274     @Override
10275     public void clearProfileOwner(ComponentName who) {
10276         if (!mHasFeature) {
10277             return;
10278         }
10279         Objects.requireNonNull(who, "ComponentName is null");
10280 
10281         final CallerIdentity caller = getCallerIdentity(who);
10282         final int userId = caller.getUserId();
10283         Preconditions.checkCallingUser(!isManagedProfile(userId));
10284         Preconditions.checkCallAuthorization(isProfileOwner(caller));
10285 
10286         enforceUserUnlocked(userId);
10287         synchronized (getLockObject()) {
10288             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
10289 
10290             mInjector.binderWithCleanCallingIdentity(() -> {
10291                 clearProfileOwnerLocked(admin, userId);
10292                 removeActiveAdminLocked(who, userId);
10293                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
10294                         userId);
10295             });
10296             Slogf.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
10297         }
10298     }
10299 
10300     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
10301         String ownersPackage = mOwners.getProfileOwnerPackage(userId);
10302         if (ownersPackage != null) {
10303             mDeviceAdminServiceController.stopServiceForAdmin(
10304                     ownersPackage, userId, "clear-profile-owner");
10305         }
10306 
10307         if (admin != null) {
10308             admin.disableCamera = false;
10309             admin.userRestrictions = null;
10310             admin.defaultEnabledRestrictionsAlreadySet.clear();
10311         }
10312         final DevicePolicyData policyData = getUserData(userId);
10313         policyData.mCurrentInputMethodSet = false;
10314         policyData.mOwnerInstalledCaCerts.clear();
10315         saveSettingsLocked(userId);
10316         clearUserPoliciesLocked(userId);
10317         clearApplicationRestrictions(userId);
10318         mOwners.removeProfileOwner(userId);
10319         mOwners.writeProfileOwner(userId);
10320         deleteTransferOwnershipBundleLocked(userId);
10321         toggleBackupServiceActive(userId, true);
10322         applyProfileRestrictionsIfDeviceOwnerLocked();
10323         setNetworkLoggingActiveInternal(false);
10324 
10325         mDevicePolicyEngine.removePoliciesForAdmin(
10326                 EnforcingAdmin.createEnterpriseEnforcingAdmin(
10327                         admin.info.getComponent(), userId, admin));
10328     }
10329 
10330     @Override
10331     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
10332         if (!mHasFeature) {
10333             return;
10334         }
10335         Objects.requireNonNull(who, "ComponentName is null");
10336 
10337         final CallerIdentity caller = getCallerIdentity(who);
10338         Preconditions.checkCallAuthorization(
10339                 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller));
10340 
10341         mInjector.binderWithCleanCallingIdentity(() ->
10342                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null));
10343 
10344         DevicePolicyEventLogger
10345                 .createEvent(DevicePolicyEnums.SET_DEVICE_OWNER_LOCK_SCREEN_INFO)
10346                 .setAdmin(caller.getComponentName())
10347                 .write();
10348     }
10349 
10350     @Override
10351     public CharSequence getDeviceOwnerLockScreenInfo() {
10352         final CallerIdentity caller = getCallerIdentity();
10353         Preconditions.checkCallAuthorization(
10354                 isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller));
10355         return mInjector.binderWithCleanCallingIdentity(() ->
10356             mLockPatternUtils.getDeviceOwnerInfo());
10357     }
10358 
10359     private void clearUserPoliciesLocked(int userId) {
10360         // Reset some of the user-specific policies.
10361         final DevicePolicyData policy = getUserData(userId);
10362         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
10363         // Clear delegations.
10364         policy.mDelegationMap.clear();
10365         policy.mStatusBarDisabled = false;
10366         policy.mSecondaryLockscreenEnabled = false;
10367         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
10368         policy.mAffiliationIds.clear();
10369         resetAffiliationCacheLocked();
10370         policy.mLockTaskPackages.clear();
10371         policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
10372         saveSettingsLocked(userId);
10373 
10374         try {
10375             mIPermissionManager.updatePermissionFlagsForAllApps(
10376                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
10377                     0  /* flagValues */, userId);
10378         } catch (RemoteException re) {
10379             // Shouldn't happen.
10380             Slogf.wtf(LOG_TAG, "Failing in updatePermissionFlagsForAllApps", re);
10381         }
10382     }
10383 
10384     @Override
10385     public boolean hasUserSetupCompleted() {
10386         return hasUserSetupCompleted(mInjector.userHandleGetCallingUserId());
10387     }
10388 
10389     // This checks only if the Setup Wizard has run.  Since Wear devices pair before
10390     // completing Setup Wizard, and pairing involves transferring user data, calling
10391     // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
10392     private boolean hasUserSetupCompleted(int userHandle) {
10393         if (!mHasFeature) {
10394             return true;
10395         }
10396         return mInjector.hasUserSetupCompleted(getUserData(userHandle));
10397     }
10398 
10399     @Override
10400     public int getUserProvisioningState(int userHandle) {
10401         if (!mHasFeature) {
10402             return DevicePolicyManager.STATE_USER_UNMANAGED;
10403         }
10404         final CallerIdentity caller = getCallerIdentity();
10405         Preconditions.checkCallAuthorization(canManageUsers(caller)
10406                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10407 
10408         if (userHandle != caller.getUserId()) {
10409             Preconditions.checkCallAuthorization(canManageUsers(caller)
10410                     || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
10411         }
10412 
10413         return getUserData(userHandle).mUserProvisioningState;
10414     }
10415 
10416     @Override
10417     public void setUserProvisioningState(int newState, int userId) {
10418         if (!mHasFeature) {
10419             logMissingFeatureAction("Cannot set provisioning state " + newState + " for user "
10420                     + userId);
10421             return;
10422         }
10423         Preconditions.checkCallAuthorization(
10424                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10425 
10426         final CallerIdentity caller = getCallerIdentity();
10427         final long id = mInjector.binderClearCallingIdentity();
10428         try {
10429             int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
10430             // NOTE: multiple if statements are nested below so it can log more info on error
10431             if (userId != deviceOwnerUserId) {
10432                 boolean hasProfileOwner = mOwners.hasProfileOwner(userId);
10433                 if (!hasProfileOwner) {
10434                     int managedUserId = getManagedUserId(userId);
10435                     if (managedUserId < 0 && newState != STATE_USER_UNMANAGED) {
10436                         // No managed device, user or profile, so setting provisioning state makes
10437                         // no sense.
10438                         String error = "Not allowed to change provisioning state unless a "
10439                                 + "device or profile owner is set.";
10440                         Slogf.w(LOG_TAG, "setUserProvisioningState(newState=%d, userId=%d) failed: "
10441                                 + "deviceOwnerId=%d, hasProfileOwner=%b, managedUserId=%d, err=%s",
10442                                 newState, userId, deviceOwnerUserId, hasProfileOwner,
10443                                 managedUserId, error);
10444                         throw new IllegalStateException(error);
10445                     }
10446                 }
10447             }
10448 
10449             synchronized (getLockObject()) {
10450                 boolean transitionCheckNeeded = true;
10451 
10452                 // Calling identity/permission checks.
10453                 if (isAdb(caller)) {
10454                     // ADB shell can only move directly from un-managed to finalized as part of
10455                     // directly setting profile-owner or device-owner.
10456                     if (getUserProvisioningState(userId)
10457                             != DevicePolicyManager.STATE_USER_UNMANAGED
10458                             || newState != STATE_USER_SETUP_FINALIZED) {
10459                         throw new IllegalStateException("Not allowed to change provisioning state "
10460                                 + "unless current provisioning state is unmanaged, and new state"
10461                                 + "is finalized.");
10462                     }
10463                     transitionCheckNeeded = false;
10464                 }
10465 
10466                 final DevicePolicyData policyData = getUserData(userId);
10467                 if (transitionCheckNeeded) {
10468                     // Optional state transition check for non-ADB case.
10469                     checkUserProvisioningStateTransition(policyData.mUserProvisioningState,
10470                             newState);
10471                 }
10472                 policyData.mUserProvisioningState = newState;
10473                 saveSettingsLocked(userId);
10474             }
10475         } finally {
10476             mInjector.binderRestoreCallingIdentity(id);
10477         }
10478     }
10479 
10480     private void checkUserProvisioningStateTransition(int currentState, int newState) {
10481         // Valid transitions for normal use-cases.
10482         switch (currentState) {
10483             case DevicePolicyManager.STATE_USER_UNMANAGED:
10484                 // Can move to any state from unmanaged (except itself as an edge case)..
10485                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
10486                     return;
10487                 }
10488                 break;
10489             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
10490             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
10491                 // Can only move to finalized from these states.
10492                 if (newState == STATE_USER_SETUP_FINALIZED) {
10493                     return;
10494                 }
10495                 break;
10496             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
10497                 // Current user has a managed-profile, but current user is not managed, so
10498                 // rather than moving to finalized state, go back to unmanaged once
10499                 // profile provisioning is complete.
10500                 if (newState == DevicePolicyManager.STATE_USER_PROFILE_FINALIZED) {
10501                     return;
10502                 }
10503                 break;
10504             case STATE_USER_SETUP_FINALIZED:
10505                 // Cannot transition out of finalized.
10506                 break;
10507             case DevicePolicyManager.STATE_USER_PROFILE_FINALIZED:
10508                 // Should only move to an unmanaged state after removing the work profile.
10509                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
10510                     return;
10511                 }
10512                 break;
10513         }
10514 
10515         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
10516         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
10517                 + "from state [" + currentState + "]");
10518     }
10519 
10520     @Override
10521     public void setProfileEnabled(ComponentName who) {
10522         if (!mHasFeature) {
10523             logMissingFeatureAction("Cannot enable profile for "
10524                     + ComponentName.flattenToShortString(who));
10525             return;
10526         }
10527         Objects.requireNonNull(who, "ComponentName is null");
10528 
10529         final CallerIdentity caller = getCallerIdentity(who);
10530         final int userId = caller.getUserId();
10531         Preconditions.checkCallAuthorization(
10532                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
10533         Preconditions.checkCallingUser(isManagedProfile(userId));
10534 
10535         synchronized (getLockObject()) {
10536             // Check if the profile is already enabled.
10537             UserInfo managedProfile = getUserInfo(userId);
10538             if (managedProfile.isEnabled()) {
10539                 Slogf.e(LOG_TAG,
10540                         "setProfileEnabled is called when the profile is already enabled");
10541                 return;
10542             }
10543             mInjector.binderWithCleanCallingIdentity(() -> {
10544                 mUserManager.setUserEnabled(userId);
10545                 UserInfo parent = mUserManager.getProfileParent(userId);
10546                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
10547                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
10548                 UserHandle parentHandle = new UserHandle(parent.id);
10549                 mLocalService.broadcastIntentToManifestReceivers(intent,
10550                         parentHandle, /* requiresPermission= */ true);
10551                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
10552                         Intent.FLAG_RECEIVER_FOREGROUND);
10553                 mContext.sendBroadcastAsUser(intent, parentHandle);
10554             });
10555         }
10556     }
10557 
10558     @Override
10559     public void setProfileName(ComponentName who, String profileName) {
10560         Objects.requireNonNull(who, "ComponentName is null");
10561 
10562         final CallerIdentity caller = getCallerIdentity(who);
10563         Preconditions.checkCallAuthorization(
10564                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
10565 
10566         final String truncatedProfileName =
10567                 profileName.substring(0, Math.min(profileName.length(), MAX_PROFILE_NAME_LENGTH));
10568         mInjector.binderWithCleanCallingIdentity(() -> {
10569             mUserManager.setUserName(caller.getUserId(), truncatedProfileName);
10570             DevicePolicyEventLogger
10571                     .createEvent(DevicePolicyEnums.SET_PROFILE_NAME)
10572                     .setAdmin(caller.getComponentName())
10573                     .write();
10574         });
10575     }
10576 
10577     @Override
10578     public ComponentName getProfileOwnerAsUser(int userId) {
10579         if (!mHasFeature) {
10580             return null;
10581         }
10582         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
10583 
10584         CallerIdentity caller = getCallerIdentity();
10585         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)
10586                 || hasFullCrossUsersPermission(caller, userId));
10587 
10588         synchronized (getLockObject()) {
10589             return mOwners.getProfileOwnerComponent(userId);
10590         }
10591     }
10592 
10593     // Returns the active profile owner for this user or null if the current user has no
10594     // profile owner.
10595     @VisibleForTesting
10596     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
10597         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
10598         if (profileOwner == null) {
10599             return null;
10600         }
10601         DevicePolicyData policy = getUserData(userHandle);
10602         final int n = policy.mAdminList.size();
10603         for (int i = 0; i < n; i++) {
10604             ActiveAdmin admin = policy.mAdminList.get(i);
10605             if (profileOwner.equals(admin.info.getComponent())) {
10606                 return admin;
10607             }
10608         }
10609         return null;
10610     }
10611 
10612     /**
10613      * Returns the ActiveAdmin associated with the PO or DO on the given user.
10614      */
10615     private @Nullable ActiveAdmin getDeviceOrProfileOwnerAdminLocked(int userHandle) {
10616         ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
10617         if (admin == null && getDeviceOwnerUserIdUncheckedLocked() == userHandle) {
10618             admin = getDeviceOwnerAdminLocked();
10619         }
10620         return admin;
10621     }
10622 
10623     @GuardedBy("getLockObject()")
10624     ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked(int userHandle) {
10625         return mInjector.binderWithCleanCallingIdentity(() -> {
10626             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
10627                 if (userInfo.isManagedProfile()) {
10628                     if (getProfileOwnerAsUser(userInfo.id) != null
10629                             && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
10630                         ComponentName who = getProfileOwnerAsUser(userInfo.id);
10631                         return getActiveAdminUncheckedLocked(who, userInfo.id);
10632                     }
10633                 }
10634             }
10635             return null;
10636         });
10637     }
10638 
10639     @GuardedBy("getLockObject()")
10640     ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked() {
10641         return mInjector.binderWithCleanCallingIdentity(() -> {
10642             for (UserInfo userInfo : mUserManager.getUsers()) {
10643                 if (userInfo.isManagedProfile()) {
10644                     if (getProfileOwnerAsUser(userInfo.id) != null
10645                             && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
10646                         ComponentName who = getProfileOwnerAsUser(userInfo.id);
10647                         return getActiveAdminUncheckedLocked(who, userInfo.id);
10648                     }
10649                 }
10650             }
10651             return null;
10652         });
10653     }
10654 
10655     /**
10656      * This API is cached: invalidate with invalidateBinderCaches().
10657      */
10658     @Override
10659     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
10660             @NonNull UserHandle userHandle) {
10661         if (!mHasFeature) {
10662             return null;
10663         }
10664         synchronized (getLockObject()) {
10665             final ComponentName doComponent = mOwners.getDeviceOwnerComponent();
10666             final ComponentName poComponent =
10667                     mOwners.getProfileOwnerComponent(userHandle.getIdentifier());
10668             // Return test only admin if configured to do so.
10669             // TODO(b/182994391): Replace with more generic solution to override the supervision
10670             // component.
10671             if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) {
10672                 if (isAdminTestOnlyLocked(doComponent, userHandle.getIdentifier())) {
10673                     return doComponent;
10674                 } else if (isAdminTestOnlyLocked(poComponent, userHandle.getIdentifier())) {
10675                     return poComponent;
10676                 }
10677             }
10678 
10679             // Check profile owner first as that is what most likely is set.
10680             if (isSupervisionComponentLocked(poComponent)) {
10681                 return poComponent;
10682             }
10683 
10684             if (isSupervisionComponentLocked(doComponent)) {
10685                 return doComponent;
10686             }
10687 
10688             return null;
10689         }
10690     }
10691 
10692     /**
10693      * Returns if the specified component is the supervision component.
10694      */
10695     @Override
10696     public boolean isSupervisionComponent(@NonNull ComponentName who) {
10697         if (!mHasFeature) {
10698             return false;
10699         }
10700         synchronized (getLockObject()) {
10701             if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) {
10702                 final CallerIdentity caller = getCallerIdentity();
10703                 if (isAdminTestOnlyLocked(who, caller.getUserId())) {
10704                     return true;
10705                 }
10706             }
10707             return isSupervisionComponentLocked(who);
10708         }
10709     }
10710 
10711     private boolean isSupervisionComponentLocked(@Nullable ComponentName who) {
10712         if (who == null) {
10713             return false;
10714         }
10715 
10716         final String configComponent = mContext.getResources().getString(
10717                 R.string.config_defaultSupervisionProfileOwnerComponent);
10718         if (configComponent != null) {
10719             final ComponentName componentName = ComponentName.unflattenFromString(configComponent);
10720             if (who.equals(componentName)) {
10721                 return true;
10722             }
10723         }
10724 
10725         // Check the system supervision role.
10726         final String configPackage = mContext.getResources().getString(
10727                 R.string.config_systemSupervision);
10728 
10729         return who.getPackageName().equals(configPackage);
10730     }
10731 
10732     // TODO(b/240562946): Remove api as owner name is not used.
10733     @Override
10734     public String getProfileOwnerName(int userHandle) {
10735         if (!mHasFeature) {
10736             return null;
10737         }
10738         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
10739                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10740         return getProfileOwnerNameUnchecked(userHandle);
10741     }
10742 
10743     private String getProfileOwnerNameUnchecked(int userHandle) {
10744         ComponentName profileOwner = getProfileOwnerAsUser(userHandle);
10745         if (profileOwner == null) {
10746             return null;
10747         }
10748         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
10749     }
10750 
10751     private @UserIdInt int getOrganizationOwnedProfileUserId() {
10752         for (UserInfo ui : mUserManagerInternal.getUserInfos()) {
10753             if (ui.isManagedProfile() && isProfileOwnerOfOrganizationOwnedDevice(ui.id)) {
10754                 return ui.id;
10755             }
10756         }
10757         return UserHandle.USER_NULL;
10758     }
10759 
10760     /**
10761      * This API is cached: invalidate with invalidateBinderCaches().
10762      */
10763     @Override
10764     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
10765         if (!mHasFeature) {
10766             return false;
10767         }
10768         return getOrganizationOwnedProfileUserId() != UserHandle.USER_NULL;
10769     }
10770 
10771     @Override
10772     public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) {
10773         final CallerIdentity caller = getCallerIdentity();
10774         ensureCallerIdentityMatchesIfNotSystem(packageName, pid, uid, caller);
10775 
10776         // Verify that the specified packages matches the provided uid.
10777         if (!doesPackageMatchUid(packageName, uid)) {
10778             return false;
10779         }
10780         // A device or profile owner must also have the READ_PHONE_STATE permission to access device
10781         // identifiers. If the package being checked does not have this permission then deny access.
10782         if (!hasPermission(permission.READ_PHONE_STATE, pid, uid)) {
10783             return false;
10784         }
10785         return hasDeviceIdAccessUnchecked(packageName, uid);
10786     }
10787 
10788     /**
10789      * Check if one the following conditions hold:
10790      * (1) The device has a Device Owner, and one of the following holds:
10791      *   (1.1) The caller is the Device Owner
10792      *   (1.2) The caller is another app in the same user as the device owner, AND
10793      *         The caller is the delegated certificate installer.
10794      *   (1.3) The caller is a Profile Owner and the calling user is affiliated.
10795      * (2) The user has a profile owner, AND:
10796      *   (2.1) The profile owner has been granted access to Device IDs and one of the following
10797      *         holds:
10798      *     (2.1.1) The caller is the profile owner.
10799      *     (2.1.2) The caller is from another app in the same user as the profile owner, AND
10800      *             the caller is the delegated cert installer.
10801      * (3) The caller holds the
10802      * {@link android.Manifest.permission#MANAGE_DEVICE_POLICY_CERTIFICATES} permission.
10803      *
10804      *  For the device owner case, simply check that the caller is the device owner or the
10805      *  delegated certificate installer.
10806      *
10807      *  For the profile owner case, first check that the caller is the profile owner or can
10808      *  manage the DELEGATION_CERT_INSTALL scope.
10809      *  If that check succeeds, ensure the profile owner was granted access to device
10810      *  identifiers. The grant is transitive: The delegated cert installer is implicitly allowed
10811      *  access to device identifiers in this case as part of the delegation.
10812      */
10813     @VisibleForTesting
10814     boolean hasDeviceIdAccessUnchecked(String packageName, int uid) {
10815         final int userId = UserHandle.getUserId(uid);
10816         // TODO(b/280048070): Introduce a permission to handle device ID access
10817         if (isPermissionCheckFlagEnabled()
10818                 && !(isUidProfileOwnerLocked(uid) || isUidDeviceOwnerLocked(uid))) {
10819             return hasPermission(MANAGE_DEVICE_POLICY_CERTIFICATES, packageName, userId);
10820         } else {
10821             ComponentName deviceOwner = getDeviceOwnerComponent(true);
10822             if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName)
10823                     || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) {
10824                 return true;
10825             }
10826             ComponentName profileOwner = getProfileOwnerAsUser(userId);
10827             final boolean isCallerProfileOwnerOrDelegate = profileOwner != null
10828                     && (profileOwner.getPackageName().equals(packageName)
10829                     || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL));
10830             if (isCallerProfileOwnerOrDelegate && (isProfileOwnerOfOrganizationOwnedDevice(userId)
10831                     || isUserAffiliatedWithDevice(userId))) {
10832                 return true;
10833             }
10834         }
10835         return false;
10836     }
10837 
10838     private boolean doesPackageMatchUid(String packageName, int uid) {
10839         final int userId = UserHandle.getUserId(uid);
10840         try {
10841             ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(packageName, 0, userId);
10842             // Since this call goes directly to PackageManagerService a NameNotFoundException is not
10843             // thrown but null data can be returned; if the appInfo for the specified package cannot
10844             // be found then return false to prevent crashing the app.
10845             if (appInfo == null) {
10846                 Slogf.w(LOG_TAG, "appInfo could not be found for package %s", packageName);
10847                 return false;
10848             } else if (uid != appInfo.uid) {
10849                 String message = String.format("Package %s (uid=%d) does not match provided uid %d",
10850                         packageName, appInfo.uid, uid);
10851                 Slogf.w(LOG_TAG, message);
10852                 throw new SecurityException(message);
10853             }
10854         } catch (RemoteException e) {
10855             // If an exception is caught obtaining the appInfo just return false to prevent crashing
10856             // apps due to an internal error.
10857             Slogf.e(LOG_TAG, e, "Exception caught obtaining appInfo for package %s", packageName);
10858             return false;
10859         }
10860         return true;
10861     }
10862 
10863     private void ensureCallerIdentityMatchesIfNotSystem(String packageName, int pid, int uid,
10864             CallerIdentity caller) {
10865         // If the caller is not a system app then it should only be able to check its own device
10866         // identifier access.
10867         int callingUid = caller.getUid();
10868         int callingPid = mInjector.binderGetCallingPid();
10869         if (UserHandle.getAppId(callingUid) >= Process.FIRST_APPLICATION_UID
10870                 && (callingUid != uid || callingPid != pid)) {
10871             String message = String.format(
10872                     "Calling uid %d, pid %d cannot check device identifier access for package %s "
10873                             + "(uid=%d, pid=%d)", callingUid, callingPid, packageName, uid, pid);
10874             Slogf.w(LOG_TAG, message);
10875             throw new SecurityException(message);
10876         }
10877     }
10878 
10879     /**
10880      * Canonical name for a given package.
10881      */
10882     private String getApplicationLabel(String packageName, @UserIdInt int userId) {
10883         return mInjector.binderWithCleanCallingIdentity(() -> {
10884             final Context userContext;
10885             try {
10886                 UserHandle userHandle = UserHandle.of(userId);
10887                 userContext = mContext.createPackageContextAsUser(packageName, /* flags= */ 0,
10888                         userHandle);
10889             } catch (PackageManager.NameNotFoundException nnfe) {
10890                 Slogf.w(LOG_TAG, nnfe, "%s is not installed for user %d", packageName, userId);
10891                 return null;
10892             }
10893             ApplicationInfo appInfo = userContext.getApplicationInfo();
10894             CharSequence result = null;
10895             if (appInfo != null) {
10896                 result = appInfo.loadUnsafeLabel(userContext.getPackageManager());
10897             }
10898             return result != null ? result.toString() : null;
10899         });
10900     }
10901 
10902     /**
10903      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
10904      * permission.
10905      * The profile owner can only be set before the user setup phase has completed,
10906      * except for:
10907      * - SYSTEM_UID
10908      * - adb unless hasIncompatibleAccountsOrNonAdb is true.
10909      */
10910     @GuardedBy("getLockObject()")
10911     private void enforceCanSetProfileOwnerLocked(
10912             CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int userId,
10913             boolean hasIncompatibleAccountsOrNonAdb) {
10914         UserInfo info = getUserInfo(userId);
10915         if (info == null) {
10916             // User doesn't exist.
10917             throw new IllegalArgumentException(
10918                     "Attempted to set profile owner for invalid userId: " + userId);
10919         }
10920         if (info.isGuest()) {
10921             throw new IllegalStateException("Cannot set a profile owner on a guest");
10922         }
10923         if (mOwners.hasProfileOwner(userId)) {
10924             StringBuilder errorMessage = new StringBuilder("Trying to set the profile owner");
10925             if (!hasIncompatibleAccountsOrNonAdb) {
10926                 append(errorMessage, owner).append(" on user ").append(userId);
10927             }
10928             errorMessage.append(", but profile owner");
10929             if (!hasIncompatibleAccountsOrNonAdb) {
10930                 appendProfileOwnerLocked(errorMessage, userId);
10931             }
10932 
10933             throw new IllegalStateException(errorMessage.append(" is already set.").toString());
10934         }
10935         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userId) {
10936             StringBuilder errorMessage = new StringBuilder("Trying to set the profile owner");
10937             if (!hasIncompatibleAccountsOrNonAdb) {
10938                 append(errorMessage, owner).append(" on user ").append(userId);
10939             }
10940             errorMessage.append(", but the user already has a device owner");
10941             if (!hasIncompatibleAccountsOrNonAdb) {
10942                 appendDeviceOwnerLocked(errorMessage);
10943             }
10944             throw new IllegalStateException(errorMessage.append('.').toString());
10945         }
10946         if (isAdb(caller)) {
10947             if ((mIsWatch || hasUserSetupCompleted(userId))
10948                     && hasIncompatibleAccountsOrNonAdb) {
10949                 StringBuilder errorMessage = new StringBuilder("Not allowed to set the profile "
10950                         + "owner");
10951                 if (!hasIncompatibleAccountsOrNonAdb) {
10952                     append(errorMessage, owner).append(" on user ").append(userId).append(' ');
10953                 }
10954                 throw new IllegalStateException(errorMessage.append(" because there are already "
10955                         + "some accounts on the profile.").toString());
10956             }
10957             return;
10958         }
10959         Preconditions.checkCallAuthorization(
10960                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10961 
10962         if ((mIsWatch || hasUserSetupCompleted(userId))) {
10963             Preconditions.checkState(isSystemUid(caller),
10964                     "Cannot set the profile owner on a user which is already set-up");
10965 
10966             if (!mIsWatch) {
10967                 if (!isSupervisionComponentLocked(owner)) {
10968                     throw new IllegalStateException("Unable to set non-default profile owner"
10969                             + " post-setup " + owner);
10970                 }
10971             }
10972         }
10973     }
10974 
10975     /**
10976      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
10977      * permission.
10978      */
10979     @GuardedBy("getLockObject()")
10980     private void enforceCanSetDeviceOwnerLocked(
10981             CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int deviceOwnerUserId,
10982             boolean hasIncompatibleAccountsOrNonAdb) {
10983         boolean showComponentOnError = false;
10984         if (!isAdb(caller)) {
10985             Preconditions.checkCallAuthorization(
10986                     hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
10987         } else {
10988             showComponentOnError = true;
10989         }
10990 
10991         final int code = checkDeviceOwnerProvisioningPreConditionLocked(owner,
10992                 /* deviceOwnerUserId= */ deviceOwnerUserId, /* callingUserId*/ caller.getUserId(),
10993                 isAdb(caller), hasIncompatibleAccountsOrNonAdb);
10994         if (code != STATUS_OK) {
10995             final String provisioningErrorStringLocked = computeProvisioningErrorStringLocked(code,
10996                     deviceOwnerUserId, owner, showComponentOnError);
10997             if (code == STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED) {
10998                 throw new ServiceSpecificException(code, provisioningErrorStringLocked);
10999             } else {
11000                 throw new IllegalStateException(provisioningErrorStringLocked);
11001             }
11002         }
11003     }
11004 
11005     private String computeProvisioningErrorString(int code, @UserIdInt int userId) {
11006         synchronized (getLockObject()) {
11007             return computeProvisioningErrorStringLocked(code, userId, /* newOwner= */ null,
11008                     /* showComponentOnError= */ false);
11009         }
11010     }
11011 
11012     @GuardedBy("getLockObject()")
11013     private String computeProvisioningErrorStringLocked(int code, @UserIdInt int userId,
11014             @Nullable ComponentName newOwner, boolean showComponentOnError) {
11015         switch (code) {
11016             case STATUS_OK:
11017                 return "OK";
11018             case STATUS_HAS_DEVICE_OWNER: {
11019                 StringBuilder error = new StringBuilder("Trying to set the device owner");
11020                 if (showComponentOnError && newOwner != null) {
11021                     append(error, newOwner);
11022                 }
11023                 error.append(", but device owner");
11024                 if (showComponentOnError) {
11025                     appendDeviceOwnerLocked(error);
11026                 }
11027                 return error.append(" is already set.").toString();
11028             }
11029             case STATUS_USER_HAS_PROFILE_OWNER: {
11030                 StringBuilder error = new StringBuilder("Trying to set the device owner");
11031                 if (showComponentOnError && newOwner != null) {
11032                     append(error, newOwner);
11033                 }
11034                 error.append(", but the user already has a profile owner");
11035                 if (showComponentOnError) {
11036                     appendProfileOwnerLocked(error, userId);
11037                 }
11038                 return error.append(".").toString();
11039             }
11040             case STATUS_USER_NOT_RUNNING:
11041                 return "User " + userId + " not running.";
11042             case STATUS_NOT_SYSTEM_USER:
11043                 return "User " + userId + " is not system user.";
11044             case STATUS_USER_SETUP_COMPLETED:
11045                 return  "Cannot set the device owner if the device is already set-up.";
11046             case STATUS_NONSYSTEM_USER_EXISTS:
11047                 return "Not allowed to set the device owner because there are already several"
11048                         + " users on the device.";
11049             case STATUS_ACCOUNTS_NOT_EMPTY:
11050                 return "Not allowed to set the device owner because there are already some accounts"
11051                         + " on the device.";
11052             case STATUS_HAS_PAIRED:
11053                 return "Not allowed to set the device owner because this device has already "
11054                         + "paired.";
11055             case STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED:
11056                 return "Cannot provision an unsupported DPC into DO on a"
11057                         + " headless device";
11058             default:
11059                 return "Unexpected @ProvisioningPreCondition: " + code;
11060         }
11061     }
11062 
11063     @GuardedBy("getLockObject()")
11064     private void appendDeviceOwnerLocked(StringBuilder string) {
11065         ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
11066         if (deviceOwner == null) {
11067             // Shouldn't happen, but it doesn't hurt to check...
11068             Slogf.wtf(LOG_TAG, "appendDeviceOwnerLocked(): device has no DO set");
11069             return;
11070         }
11071         append(string, deviceOwner);
11072     }
11073 
11074     @GuardedBy("getLockObject()")
11075     private void appendProfileOwnerLocked(StringBuilder string, @UserIdInt int userId) {
11076         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
11077         if (profileOwner == null) {
11078             // Shouldn't happen, but it doesn't hurt to check...
11079             Slogf.wtf(LOG_TAG, "profileOwner(%d): PO not set", userId);
11080             return;
11081         }
11082         append(string, profileOwner);
11083     }
11084 
11085     private static StringBuilder append(StringBuilder string, ComponentName component) {
11086         return string.append(" (").append(component.flattenToShortString()).append(')');
11087     }
11088 
11089     private void enforceUserUnlocked(int userId) {
11090         // Since we're doing this operation on behalf of an app, we only
11091         // want to use the actual "unlocked" state.
11092         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
11093                 "User must be running and unlocked");
11094     }
11095 
11096     private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
11097         if (parent) {
11098             enforceUserUnlocked(getProfileParentId(userId));
11099         } else {
11100             enforceUserUnlocked(userId);
11101         }
11102     }
11103 
11104     private boolean canManageUsers(CallerIdentity caller) {
11105         return hasCallingOrSelfPermission(permission.MANAGE_USERS);
11106     }
11107 
11108     private boolean canQueryAdminPolicy(CallerIdentity caller) {
11109         return hasCallingOrSelfPermission(permission.QUERY_ADMIN_POLICY);
11110     }
11111 
11112     private boolean hasPermission(String permission, int pid, int uid) {
11113         return mContext.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED;
11114     }
11115 
11116     private boolean hasCallingPermission(String permission) {
11117         return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED;
11118     }
11119 
11120     private boolean hasCallingOrSelfPermission(String permission) {
11121         return mContext.checkCallingOrSelfPermission(permission)
11122                 == PackageManager.PERMISSION_GRANTED;
11123     }
11124 
11125     private boolean hasPermissionForPreflight(CallerIdentity caller, String permission) {
11126         final int callingPid = mInjector.binderGetCallingPid();
11127         final String packageName = mContext.getPackageName();
11128 
11129         return PermissionChecker.checkPermissionForPreflight(mContext, permission, callingPid,
11130                 caller.getUid(), packageName) == PermissionChecker.PERMISSION_GRANTED;
11131     }
11132 
11133     private boolean hasFullCrossUsersPermission(CallerIdentity caller, int userHandle) {
11134         return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller)
11135                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL);
11136     }
11137 
11138     private boolean hasCrossUsersPermission(CallerIdentity caller, int userHandle) {
11139         return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller)
11140                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS);
11141     }
11142 
11143     private boolean canDPCManagedUserUseLockTaskLocked(int userId) {
11144         if (isUserAffiliatedWithDeviceLocked(userId)) {
11145             return true;
11146         }
11147 
11148         // Unaffiliated profile owners are not allowed to use lock when there is a device owner.
11149         if (mOwners.hasDeviceOwner()) {
11150             return false;
11151         }
11152 
11153         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
11154         if (profileOwner == null) {
11155             return false;
11156         }
11157         // Managed profiles are not allowed to use lock task
11158         if (isManagedProfile(userId)) {
11159             return false;
11160         }
11161 
11162         return true;
11163     }
11164     private void enforceCanQueryLockTaskLocked(ComponentName who, String callerPackageName) {
11165         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
11166         final int userId = caller.getUserId();
11167 
11168         enforceCanQuery(MANAGE_DEVICE_POLICY_LOCK_TASK, caller.getPackageName(), userId);
11169         if ((isDeviceOwner(caller) || isProfileOwner(caller))
11170                 && !canDPCManagedUserUseLockTaskLocked(userId)) {
11171             throw new SecurityException("User " + userId + " is not allowed to use lock task");
11172         }
11173     }
11174 
11175     private EnforcingAdmin enforceCanCallLockTaskLocked(ComponentName who,
11176             String callerPackageName) {
11177         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
11178         final int userId =  caller.getUserId();
11179 
11180         EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
11181                 who,
11182                 MANAGE_DEVICE_POLICY_LOCK_TASK,
11183                 caller.getPackageName(),
11184                 userId
11185         );
11186         if ((isDeviceOwner(caller) || isProfileOwner(caller))
11187                 && !canDPCManagedUserUseLockTaskLocked(userId)) {
11188             throw new SecurityException("User " + userId + " is not allowed to use lock task");
11189         }
11190         return enforcingAdmin;
11191     }
11192 
11193     private boolean isSystemUid(CallerIdentity caller) {
11194         return UserHandle.isSameApp(caller.getUid(), Process.SYSTEM_UID);
11195     }
11196 
11197     private boolean isRootUid(CallerIdentity caller) {
11198         return UserHandle.isSameApp(caller.getUid(), Process.ROOT_UID);
11199     }
11200 
11201     private boolean isShellUid(CallerIdentity caller) {
11202         return UserHandle.isSameApp(caller.getUid(), Process.SHELL_UID);
11203     }
11204 
11205     private boolean isCameraServerUid(CallerIdentity caller) {
11206         return UserHandle.isSameApp(caller.getUid(), Process.CAMERASERVER_UID);
11207     }
11208 
11209     private @UserIdInt int getCurrentForegroundUserId() {
11210         try {
11211             UserInfo currentUser = mInjector.getIActivityManager().getCurrentUser();
11212             if (currentUser == null) {
11213                 // TODO(b/206107460): should not happen on production, but it's happening on unit
11214                 // tests that are not properly setting the expectation (because they don't need it)
11215                 Slogf.wtf(LOG_TAG, "getCurrentForegroundUserId(): mInjector.getIActivityManager()"
11216                         + ".getCurrentUser() returned null, please ignore when running unit tests");
11217                 return ActivityManager.getCurrentUser();
11218             }
11219             return currentUser.id;
11220         } catch (RemoteException e) {
11221             Slogf.wtf(LOG_TAG, "cannot get current user", e);
11222         }
11223         return UserHandle.USER_NULL;
11224     }
11225 
11226     @Override
11227     public List<UserHandle> listForegroundAffiliatedUsers() {
11228         checkIsDeviceOwner(getCallerIdentity());
11229 
11230         return mInjector.binderWithCleanCallingIdentity(() -> {
11231             int userId = getCurrentForegroundUserId();
11232             boolean isAffiliated;
11233             synchronized (getLockObject()) {
11234                 isAffiliated = isUserAffiliatedWithDeviceLocked(userId);
11235             }
11236 
11237             if (!isAffiliated) return Collections.emptyList();
11238 
11239             List<UserHandle> users = new ArrayList<>(1);
11240             users.add(UserHandle.of(userId));
11241 
11242             return users;
11243         });
11244     }
11245 
11246     protected int getProfileParentId(int userHandle) {
11247         return mInjector.binderWithCleanCallingIdentity(() -> {
11248             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
11249             return parentUser != null ? parentUser.id : userHandle;
11250         });
11251     }
11252 
11253     private int getProfileParentUserIfRequested(int userHandle, boolean parent) {
11254         if (parent) {
11255             return getProfileParentId(userHandle);
11256         }
11257 
11258         return userHandle;
11259     }
11260 
11261     private int getCredentialOwner(final int userHandle, final boolean parent) {
11262         return mInjector.binderWithCleanCallingIdentity(() -> {
11263             int effectiveUserHandle = userHandle;
11264             if (parent) {
11265                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
11266                 if (parentProfile != null) {
11267                     effectiveUserHandle = parentProfile.id;
11268                 }
11269             }
11270             return mUserManager.getCredentialOwnerProfile(effectiveUserHandle);
11271         });
11272     }
11273 
11274     private boolean isManagedProfile(int userHandle) {
11275         final UserInfo user = getUserInfo(userHandle);
11276         return user != null && user.isManagedProfile();
11277     }
11278 
11279     private void enableIfNecessary(String packageName, int userId) {
11280         try {
11281             final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
11282                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
11283             if (ai.enabledSetting
11284                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
11285                 mIPackageManager.setApplicationEnabledSetting(packageName,
11286                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
11287                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
11288             }
11289         } catch (RemoteException e) {
11290         }
11291     }
11292 
11293     private void dumpPersonalAppInfoForSystemUserNoLock(IndentingPrintWriter pw) {
11294         wtfIfInLock();
11295         PersonalAppsSuspensionHelper.forUser(mContext, UserHandle.USER_SYSTEM).dump(pw);
11296     }
11297 
11298     private void dumpPerUserPolicyData(IndentingPrintWriter pw) {
11299         int userCount = mUserData.size();
11300         for (int i = 0; i < userCount; i++) {
11301             int userId = mUserData.keyAt(i);
11302             DevicePolicyData policy = getUserData(userId);
11303             policy.dump(pw);
11304             pw.println();
11305         }
11306     }
11307 
11308     @Override
11309     protected void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
11310         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, printWriter)) return;
11311 
11312         try (IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ")) {
11313             pw.println("Current Device Policy Manager state:");
11314             pw.increaseIndent();
11315 
11316             dumpImmutableState(pw);
11317             synchronized (getLockObject()) {
11318                 mOwners.dump(pw);
11319                 pw.println();
11320                 mDeviceAdminServiceController.dump(pw);
11321                 pw.println();
11322                 dumpPerUserPolicyData(pw);
11323                 pw.println();
11324                 mConstants.dump(pw);
11325                 pw.println();
11326                 mStatLogger.dump(pw);
11327                 pw.println();
11328                 if (Flags.dumpsysPolicyEngineMigrationEnabled()) {
11329                     mDevicePolicyEngine.dump(pw);
11330                     pw.println();
11331                 }
11332                 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
11333                 pw.println("Logout user: " + getLogoutUserIdUnchecked());
11334                 pw.println();
11335 
11336                 if (mPendingUserCreatedCallbackTokens.isEmpty()) {
11337                     pw.println("no pending user created callback tokens");
11338                 } else {
11339                     int size = mPendingUserCreatedCallbackTokens.size();
11340                     pw.printf("%d pending user created callback token%s\n", size,
11341                             (size == 1 ? "" : "s"));
11342                 }
11343                 pw.println();
11344 
11345                 mPolicyCache.dump(pw);
11346                 pw.println();
11347                 mStateCache.dump(pw);
11348                 pw.println();
11349             }
11350             dumpPersonalAppInfoForSystemUserNoLock(pw);
11351 
11352             synchronized (mSubscriptionsChangedListenerLock) {
11353                 pw.println("Subscription changed listener : " + mSubscriptionsChangedListener);
11354             }
11355 
11356             pw.println("DPM global setting ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS : "
11357                     + mInjector.settingsGlobalGetString(
11358                     Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS));
11359             mHandler.post(() -> handleDump(pw));
11360             dumpResources(pw);
11361         }
11362     }
11363 
11364     // Dump state that is guarded by the handler
11365     private void handleDump(IndentingPrintWriter pw) {
11366         if (mNetworkLoggingNotificationUserId != UserHandle.USER_NULL) {
11367             pw.println("mNetworkLoggingNotificationUserId:  " + mNetworkLoggingNotificationUserId);
11368         }
11369     }
11370 
11371     private void dumpImmutableState(IndentingPrintWriter pw) {
11372         pw.println("Immutable state:");
11373         pw.increaseIndent();
11374         pw.printf("mHasFeature=%b\n", mHasFeature);
11375         pw.printf("mIsWatch=%b\n", mIsWatch);
11376         pw.printf("mIsAutomotive=%b\n", mIsAutomotive);
11377         pw.printf("mHasTelephonyFeature=%b\n", mHasTelephonyFeature);
11378         pw.printf("mSafetyChecker=%s\n", mSafetyChecker);
11379         pw.decreaseIndent();
11380     }
11381 
11382     private void dumpResources(IndentingPrintWriter pw) {
11383         mOverlayPackagesProvider.dump(pw);
11384         pw.println();
11385 
11386         pw.println("Other overlayable app resources");
11387         pw.increaseIndent();
11388         dumpResources(pw, mContext, "cross_profile_apps", R.array.cross_profile_apps);
11389         dumpResources(pw, mContext, "vendor_cross_profile_apps", R.array.vendor_cross_profile_apps);
11390         dumpResources(pw, mContext, "config_packagesExemptFromSuspension",
11391                 R.array.config_packagesExemptFromSuspension);
11392         dumpResources(pw, mContext, "policy_exempt_apps", R.array.policy_exempt_apps);
11393         dumpResources(pw, mContext, "vendor_policy_exempt_apps", R.array.vendor_policy_exempt_apps);
11394         pw.decreaseIndent();
11395         pw.println();
11396     }
11397 
11398     static void dumpResources(IndentingPrintWriter pw, Context context, String resName, int resId) {
11399         dumpApps(pw, resName, context.getResources().getStringArray(resId));
11400     }
11401 
11402     static void dumpApps(IndentingPrintWriter pw, String name, String[] apps) {
11403         dumpApps(pw, name, Arrays.asList(apps));
11404     }
11405 
11406     static void dumpApps(IndentingPrintWriter pw, String name, List apps) {
11407         if (apps == null || apps.isEmpty()) {
11408             pw.printf("%s: empty\n", name);
11409             return;
11410         }
11411         int size = apps.size();
11412         pw.printf("%s: %d app%s\n", name, size, size == 1 ? "" : "s");
11413         pw.increaseIndent();
11414         for (int i = 0; i < size; i++) {
11415             pw.printf("%d: %s\n", i, apps.get(i));
11416         }
11417         pw.decreaseIndent();
11418     }
11419 
11420     @Override
11421     public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
11422             String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
11423         new DevicePolicyManagerServiceShellCommand(DevicePolicyManagerService.this).exec(
11424                 this, in, out, err, args, callback, resultReceiver);
11425 
11426     }
11427 
11428     private String getEncryptionStatusName(int encryptionStatus) {
11429         switch (encryptionStatus) {
11430             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
11431                 return "per-user";
11432             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
11433                 return "unsupported";
11434             default:
11435                 return "unknown";
11436         }
11437     }
11438 
11439     @Override
11440     public void addPersistentPreferredActivity(ComponentName who, String callerPackageName,
11441             IntentFilter filter, ComponentName activity) {
11442         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
11443 
11444         final int userId = caller.getUserId();
11445         EnforcingAdmin enforcingAdmin;
11446         if (who == null) {
11447             enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
11448                     who,
11449                     MANAGE_DEVICE_POLICY_LOCK_TASK,
11450                     caller.getPackageName(),
11451                     userId);
11452         } else {
11453             Preconditions.checkCallAuthorization(isProfileOwner(caller)
11454                     || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
11455             enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
11456         }
11457         if (!isPackageInstalledForUser(activity.getPackageName(), userId)) {
11458             // Fail early as packageManager doesn't persist the activity if its not installed.
11459             return;
11460         }
11461         mDevicePolicyEngine.setLocalPolicy(
11462                 PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
11463                 enforcingAdmin,
11464                 new ComponentNamePolicyValue(activity),
11465                 userId);
11466         final String activityPackage =
11467                 (activity != null ? activity.getPackageName() : null);
11468         DevicePolicyEventLogger
11469                 .createEvent(DevicePolicyEnums.ADD_PERSISTENT_PREFERRED_ACTIVITY)
11470                 .setAdmin(caller.getPackageName())
11471                 .setStrings(activityPackage, getIntentFilterActions(filter))
11472                 .write();
11473     }
11474 
11475     @Override
11476     public void clearPackagePersistentPreferredActivities(ComponentName who,
11477             String callerPackageName, String packageName) {
11478         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
11479         final int userId = caller.getUserId();
11480 
11481         EnforcingAdmin enforcingAdmin;
11482         if (who == null) {
11483             enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
11484                     who,
11485                     MANAGE_DEVICE_POLICY_LOCK_TASK,
11486                     caller.getPackageName(),
11487                     userId);
11488         } else {
11489             Preconditions.checkCallAuthorization(isProfileOwner(caller)
11490                     || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller));
11491             enforcingAdmin = getEnforcingAdminForCaller(who, callerPackageName);
11492         }
11493         clearPackagePersistentPreferredActivitiesFromPolicyEngine(
11494                 enforcingAdmin,
11495                 packageName,
11496                 userId);
11497     }
11498 
11499     /**
11500      * Remove all persistent intent handler preferences associated with the given package that were
11501      * set by this admin, note that is doesn't remove preferences set by other admins for the same
11502      * package.
11503      */
11504     private void clearPackagePersistentPreferredActivitiesFromPolicyEngine(
11505             EnforcingAdmin admin, String packageName, int userId) {
11506         Set<PolicyKey> keys = mDevicePolicyEngine.getLocalPolicyKeysSetByAdmin(
11507                 PolicyDefinition.GENERIC_PERSISTENT_PREFERRED_ACTIVITY,
11508                 admin,
11509                 userId);
11510         for (PolicyKey key : keys) {
11511             if (!(key instanceof IntentFilterPolicyKey)) {
11512                 throw new IllegalStateException("PolicyKey for PERSISTENT_PREFERRED_ACTIVITY is not"
11513                         + "of type IntentFilterPolicyKey");
11514             }
11515             IntentFilterPolicyKey parsedKey =
11516                     (IntentFilterPolicyKey) key;
11517             IntentFilter filter = Objects.requireNonNull(parsedKey.getIntentFilter());
11518 
11519             ComponentName preferredActivity = mDevicePolicyEngine.getLocalPolicySetByAdmin(
11520                     PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
11521                     admin,
11522                     userId);
11523             if (preferredActivity != null
11524                     && preferredActivity.getPackageName().equals(packageName)) {
11525                 mDevicePolicyEngine.removeLocalPolicy(
11526                         PolicyDefinition.PERSISTENT_PREFERRED_ACTIVITY(filter),
11527                         admin,
11528                         userId);
11529             }
11530         }
11531     }
11532 
11533     @Override
11534     public void setDefaultSmsApplication(ComponentName admin, String callerPackageName,
11535             String packageName, boolean parent) {
11536         CallerIdentity caller;
11537         if (isPermissionCheckFlagEnabled()) {
11538             caller = getCallerIdentity(admin, callerPackageName);
11539         } else {
11540             caller = getCallerIdentity(admin);
11541         }
11542 
11543         final int userId;
11544 
11545         if (isPermissionCheckFlagEnabled()) {
11546             enforcePermission(
11547                     MANAGE_DEVICE_POLICY_DEFAULT_SMS,
11548                     caller.getPackageName(),
11549                     getAffectedUser(parent));
11550         } else {
11551             Objects.requireNonNull(admin, "ComponentName is null");
11552             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
11553                     || isProfileOwnerOfOrganizationOwnedDevice(caller));
11554         }
11555 
11556         if (!parent && isManagedProfile(caller.getUserId())
11557                 && getManagedSubscriptionsPolicy().getPolicyType()
11558                 != ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
11559             throw new IllegalStateException(
11560                     "Default sms application can only be set on the profile, when "
11561                             + "ManagedSubscriptions policy is set");
11562         }
11563 
11564         if (parent) {
11565             userId = getProfileParentId(mInjector.userHandleGetCallingUserId());
11566             mInjector.binderWithCleanCallingIdentity(() -> enforcePackageIsSystemPackage(
11567                     packageName, userId));
11568         } else {
11569             userId = mInjector.userHandleGetCallingUserId();
11570         }
11571 
11572         mInjector.binderWithCleanCallingIdentity(() ->
11573                 SmsApplication.setDefaultApplicationAsUser(packageName, mContext, userId));
11574 
11575         synchronized (getLockObject()) {
11576             final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
11577                     getProfileOwnerOrDeviceOwnerLocked(caller.getUserId()), parent);
11578 
11579             if (isManagedProfile(userId)) {
11580                 mInjector.binderWithCleanCallingIdentity(
11581                         () -> updateDialerAndSmsManagedShortcutsOverrideCache());
11582             }
11583 
11584             if (!Objects.equals(activeAdmin.mSmsPackage, packageName)) {
11585                 activeAdmin.mSmsPackage = packageName;
11586                 saveSettingsLocked(caller.getUserId());
11587             }
11588         }
11589     }
11590 
11591     @Override
11592     public void setDefaultDialerApplication(String packageName) {
11593         if (!mHasFeature || !mHasTelephonyFeature) {
11594             return;
11595         }
11596 
11597         final CallerIdentity caller = getCallerIdentity();
11598         final int callerUserId = caller.getUserId();
11599         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
11600                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
11601         mInjector.binderWithCleanCallingIdentity(() -> {
11602             CompletableFuture<Void> future = new CompletableFuture<>();
11603             Consumer<Boolean> callback = successful -> {
11604                 if (successful) {
11605                     future.complete(null);
11606                 } else {
11607                     future.completeExceptionally(new IllegalArgumentException(
11608                             packageName +  " cannot be set as the dialer"));
11609                 }
11610             };
11611             mRoleManager.addRoleHolderAsUser(
11612                     RoleManager.ROLE_DIALER, packageName, 0, UserHandle.of(callerUserId),
11613                     AsyncTask.THREAD_POOL_EXECUTOR, callback);
11614             try {
11615                 future.get(20, TimeUnit.SECONDS);
11616             } catch (TimeoutException e) {
11617                 throw new IllegalArgumentException("Timeout when setting the app as the dialer", e);
11618             } catch (ExecutionException e) {
11619                 Throwable cause = e.getCause();
11620                 if (cause instanceof IllegalArgumentException) {
11621                     throw (IllegalArgumentException) cause;
11622                 } else {
11623                     throw new IllegalStateException(cause);
11624                 }
11625             }
11626         });
11627         // Only save the package when the setting the role succeeded without exception.
11628         synchronized (getLockObject()) {
11629             if (isManagedProfile(callerUserId)) {
11630                 mInjector.binderWithCleanCallingIdentity(
11631                         () -> updateDialerAndSmsManagedShortcutsOverrideCache());
11632             }
11633 
11634             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(callerUserId);
11635             if (!Objects.equals(admin.mDialerPackage, packageName)) {
11636                 admin.mDialerPackage = packageName;
11637                 saveSettingsLocked(callerUserId);
11638             }
11639         }
11640     }
11641 
11642     @Override
11643     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
11644             String packageName) {
11645         try {
11646             setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
11647         } catch (IllegalArgumentException e) {
11648             return false;
11649         }
11650         return true;
11651     }
11652 
11653     @Override
11654     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
11655         final List<String> delegatePackages = getDelegatePackages(admin,
11656                 DELEGATION_APP_RESTRICTIONS);
11657         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
11658     }
11659 
11660     @Override
11661     public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
11662         return isCallerDelegate(callerPackage, getCallerIdentity().getUid(),
11663                 DELEGATION_APP_RESTRICTIONS);
11664     }
11665 
11666     @Override
11667     public void setApplicationRestrictions(ComponentName who, String callerPackage,
11668             String packageName, Bundle restrictions, boolean parent) {
11669         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11670         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_RESTRICTIONS);
11671 
11672         // This check is eventually made in UMS, checking here to fail early.
11673         String validationResult =
11674                 FrameworkParsingPackageUtils.validateName(packageName, false, false);
11675         if (validationResult != null) {
11676             throw new IllegalArgumentException("Invalid package name: " + validationResult);
11677         }
11678 
11679         if (isUnicornFlagEnabled()) {
11680             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
11681                     who,
11682                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
11683                     caller.getPackageName(),
11684                     caller.getUserId()
11685             );
11686 
11687             if (restrictions == null || restrictions.isEmpty()) {
11688                 mDevicePolicyEngine.removeLocalPolicy(
11689                         PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
11690                         enforcingAdmin,
11691                         caller.getUserId());
11692             } else {
11693                 mDevicePolicyEngine.setLocalPolicy(
11694                         PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
11695                         enforcingAdmin,
11696                         new BundlePolicyValue(restrictions),
11697                         caller.getUserId());
11698             }
11699             setBackwardsCompatibleAppRestrictions(
11700                     caller, packageName, restrictions, caller.getUserHandle());
11701         } else if (Flags.dmrhSetAppRestrictions()) {
11702             final boolean isRoleHolder;
11703             if (who != null) {
11704                 // DO or PO
11705                 Preconditions.checkCallAuthorization(
11706                         (isProfileOwner(caller) || isDefaultDeviceOwner(caller)));
11707                 Preconditions.checkCallAuthorization(!parent,
11708                         "DO or PO cannot call this on parent");
11709                 // Caller has opted to be treated as DPC (by passing a non-null who), so don't
11710                 // consider it as the DMRH, even if the caller is both the DPC and the DMRH.
11711                 isRoleHolder = false;
11712             } else {
11713                 // Delegates, or the DMRH. Only DMRH can call this on COPE parent
11714                 isRoleHolder = isCallerDevicePolicyManagementRoleHolder(caller);
11715                 if (parent) {
11716                     Preconditions.checkCallAuthorization(isRoleHolder);
11717                     Preconditions.checkState(isOrganizationOwnedDeviceWithManagedProfile(),
11718                             "Role Holder can only operate parent app restriction on COPE devices");
11719                 } else {
11720                     Preconditions.checkCallAuthorization(isRoleHolder
11721                             || isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS));
11722                 }
11723             }
11724             // DMRH caller uses policy engine, others still use legacy code path
11725             if (isRoleHolder) {
11726                 EnforcingAdmin enforcingAdmin = getEnforcingAdminForCaller(/* who */ null,
11727                         caller.getPackageName());
11728                 int affectedUserId = parent
11729                         ? getProfileParentId(caller.getUserId()) : caller.getUserId();
11730                 if (restrictions == null || restrictions.isEmpty()) {
11731                     mDevicePolicyEngine.removeLocalPolicy(
11732                             PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
11733                             enforcingAdmin,
11734                             affectedUserId);
11735                 } else {
11736                     mDevicePolicyEngine.setLocalPolicy(
11737                             PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
11738                             enforcingAdmin,
11739                             new BundlePolicyValue(restrictions),
11740                             affectedUserId);
11741                 }
11742             } else {
11743                 mInjector.binderWithCleanCallingIdentity(() -> {
11744                     mUserManager.setApplicationRestrictions(packageName, restrictions,
11745                             caller.getUserHandle());
11746                 });
11747             }
11748         } else {
11749             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11750                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
11751                     || (caller.hasPackage() && isCallerDelegate(caller,
11752                     DELEGATION_APP_RESTRICTIONS)));
11753             mInjector.binderWithCleanCallingIdentity(() -> {
11754                 mUserManager.setApplicationRestrictions(packageName, restrictions,
11755                         caller.getUserHandle());
11756             });
11757         }
11758 
11759         DevicePolicyEventLogger
11760                 .createEvent(DevicePolicyEnums.SET_APPLICATION_RESTRICTIONS)
11761                 .setAdmin(caller.getPackageName())
11762                 .setBoolean(/* isDelegate */ isCallerDelegate(caller))
11763                 .setStrings(packageName)
11764                 .write();
11765     }
11766 
11767     /**
11768      * Set app restrictions in user manager for DPC callers only to keep backwards compatibility
11769      * for the old getApplicationRestrictions API.
11770      */
11771     private void setBackwardsCompatibleAppRestrictions(
11772             CallerIdentity caller, String packageName, Bundle restrictions, UserHandle userHandle) {
11773         if ((caller.hasAdminComponent() && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
11774                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS))) {
11775             Bundle restrictionsToApply = restrictions == null || restrictions.isEmpty()
11776                     ? getAppRestrictionsSetByAnyAdmin(packageName, userHandle)
11777                     : restrictions;
11778             mInjector.binderWithCleanCallingIdentity(() -> {
11779                 mUserManager.setApplicationRestrictions(packageName, restrictionsToApply,
11780                         userHandle);
11781             });
11782         } else {
11783             // Notify package of changes via an intent - only sent to explicitly registered
11784             // receivers. Sending here because For DPCs, this is being sent in UMS.
11785             final Intent changeIntent = new Intent(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
11786             changeIntent.setPackage(packageName);
11787             changeIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11788             mContext.sendBroadcastAsUser(changeIntent, userHandle);
11789         }
11790     }
11791 
11792     private Bundle getAppRestrictionsSetByAnyAdmin(String packageName, UserHandle userHandle) {
11793         LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
11794                 mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
11795                         PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
11796                         userHandle.getIdentifier());
11797         return policies.isEmpty()
11798                 ? null : policies.entrySet().stream().findAny().get().getValue().getValue();
11799     }
11800 
11801     private int getUidForPackage(String packageName, int userId) {
11802         return mInjector.binderWithCleanCallingIdentity(() -> {
11803             try {
11804                 return mContext.getPackageManager().getApplicationInfoAsUser(
11805                         packageName, /* flags= */ 0, userId).uid;
11806             } catch (NameNotFoundException exception) {
11807                 return -1;
11808             }
11809         });
11810     }
11811 
11812     @Override
11813     public void setTrustAgentConfiguration(
11814             ComponentName admin, String callerPackageName, ComponentName agent,
11815             PersistableBundle args, boolean parent) {
11816         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
11817             return;
11818         }
11819 
11820         if (!isPermissionCheckFlagEnabled()) {
11821             Objects.requireNonNull(admin, "admin is null");
11822         }
11823 
11824         Objects.requireNonNull(agent, "agent is null");
11825 
11826         PolicySizeVerifier.enforceMaxPackageNameLength(agent.getPackageName());
11827         final String agentAsString = agent.flattenToString();
11828         PolicySizeVerifier.enforceMaxStringLength(agentAsString, "agent name");
11829         if (args != null) {
11830             PolicySizeVerifier.enforceMaxStringLength(args, "args");
11831         }
11832 
11833         int userHandle = mInjector.userHandleGetCallingUserId();
11834         synchronized (getLockObject()) {
11835             ActiveAdmin ap;
11836             if (isPermissionCheckFlagEnabled()) {
11837                 CallerIdentity caller = getCallerIdentity(admin, callerPackageName);
11838                 int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
11839                 ap = enforcePermissionAndGetEnforcingAdmin(
11840                         admin,
11841                         /*permission=*/MANAGE_DEVICE_POLICY_KEYGUARD,
11842                         /*adminPolicy=*/DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES,
11843                         caller.getPackageName(), affectedUserId).getActiveAdmin();
11844             } else {
11845                 ap = getActiveAdminForCallerLocked(admin,
11846                         DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
11847             }
11848             checkCanExecuteOrThrowUnsafe(
11849                     DevicePolicyManager.OPERATION_SET_TRUST_AGENT_CONFIGURATION);
11850 
11851             ap.trustAgentInfos.put(agentAsString, new TrustAgentInfo(args));
11852             saveSettingsLocked(userHandle);
11853         }
11854     }
11855 
11856     @Override
11857     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
11858             ComponentName agent, int userHandle, boolean parent) {
11859         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
11860             return null;
11861         }
11862         Objects.requireNonNull(agent, "agent null");
11863         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
11864 
11865         final CallerIdentity caller = getCallerIdentity(admin);
11866         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
11867 
11868         synchronized (getLockObject()) {
11869             final String componentName = agent.flattenToString();
11870             if (admin != null) {
11871                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
11872                 if (ap == null) return null;
11873                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
11874                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
11875                 List<PersistableBundle> result = new ArrayList<>();
11876                 result.add(trustAgentInfo.options);
11877                 return result;
11878             }
11879 
11880             // Return strictest policy for this user and profiles that are visible from this user.
11881             List<PersistableBundle> result = null;
11882             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
11883             // of the options. If any admin doesn't have options, discard options for the rest
11884             // and return null.
11885             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
11886                     getProfileParentUserIfRequested(userHandle, parent));
11887             boolean allAdminsHaveOptions = true;
11888             final int N = admins.size();
11889             for (int i = 0; i < N; i++) {
11890                 final ActiveAdmin active = admins.get(i);
11891 
11892                 final boolean disablesTrust = (active.disabledKeyguardFeatures
11893                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
11894                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
11895                 if (info != null && info.options != null && !info.options.isEmpty()) {
11896                     if (disablesTrust) {
11897                         if (result == null) {
11898                             result = new ArrayList<>();
11899                         }
11900                         result.add(info.options);
11901                     } else {
11902                         Slogf.w(LOG_TAG, "Ignoring admin %s because it has trust options but "
11903                                 + "doesn't declare KEYGUARD_DISABLE_TRUST_AGENTS", active.info);
11904                     }
11905                 } else if (disablesTrust) {
11906                     allAdminsHaveOptions = false;
11907                     break;
11908                 }
11909             }
11910             return allAdminsHaveOptions ? result : null;
11911         }
11912     }
11913 
11914     @Override
11915     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
11916         Objects.requireNonNull(who, "ComponentName is null");
11917         final CallerIdentity caller = getCallerIdentity(who);
11918         Preconditions.checkCallAuthorization(
11919                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
11920         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_RESTRICTIONS_PROVIDER);
11921 
11922         synchronized (getLockObject()) {
11923             int userHandle = caller.getUserId();
11924             DevicePolicyData userData = getUserData(userHandle);
11925             userData.mRestrictionsProvider = permissionProvider;
11926             saveSettingsLocked(userHandle);
11927         }
11928     }
11929 
11930     @Override
11931     public ComponentName getRestrictionsProvider(int userHandle) {
11932         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
11933                 String.format(NOT_SYSTEM_CALLER_MSG, "query the permission provider"));
11934         synchronized (getLockObject()) {
11935             DevicePolicyData userData = getUserData(userHandle);
11936             return userData != null ? userData.mRestrictionsProvider : null;
11937         }
11938     }
11939 
11940     @Override
11941     public void addCrossProfileIntentFilter(ComponentName who, String callerPackageName,
11942             IntentFilter filter, int flags) {
11943         CallerIdentity caller;
11944         if (isPermissionCheckFlagEnabled()) {
11945             caller = getCallerIdentity(who, callerPackageName);
11946         } else {
11947             caller = getCallerIdentity(who);
11948         }
11949         int callingUserId = caller.getUserId();
11950 
11951         if (isPermissionCheckFlagEnabled()) {
11952             enforcePermission(
11953                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
11954                     caller.getPackageName(),
11955                     callingUserId);
11956         } else {
11957             Objects.requireNonNull(who, "ComponentName is null");
11958             Preconditions.checkCallAuthorization(
11959                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
11960         }
11961         synchronized (getLockObject()) {
11962             long id = mInjector.binderClearCallingIdentity();
11963             try {
11964                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
11965                 if (parent == null) {
11966                     Slogf.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
11967                             + "parent");
11968                     return;
11969                 }
11970                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
11971                     mIPackageManager.addCrossProfileIntentFilter(
11972                             filter, who.getPackageName(), callingUserId, parent.id, 0);
11973                 }
11974                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
11975                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
11976                             parent.id, callingUserId, 0);
11977                 }
11978             } catch (RemoteException re) {
11979                 // Shouldn't happen
11980                 Slogf.wtf(LOG_TAG, "Error adding cross profile intent filter", re);
11981             } finally {
11982                 mInjector.binderRestoreCallingIdentity(id);
11983             }
11984         }
11985         DevicePolicyEventLogger
11986                 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_INTENT_FILTER)
11987                 .setAdmin(caller.getPackageName())
11988                 .setStrings(getIntentFilterActions(filter))
11989                 .setInt(flags)
11990                 .write();
11991     }
11992 
11993     private static String[] getIntentFilterActions(IntentFilter filter) {
11994         if (filter == null) {
11995             return null;
11996         }
11997         final int actionsCount = filter.countActions();
11998         final String[] actions = new String[actionsCount];
11999         for (int i = 0; i < actionsCount; i++) {
12000             actions[i] = filter.getAction(i);
12001         }
12002         return actions;
12003     }
12004 
12005     @Override
12006     public void clearCrossProfileIntentFilters(ComponentName who, String callerPackageName) {
12007         CallerIdentity caller;
12008         if (isPermissionCheckFlagEnabled()) {
12009             caller = getCallerIdentity(who, callerPackageName);
12010         } else {
12011             caller = getCallerIdentity(who);
12012         }
12013         int callingUserId = caller.getUserId();
12014 
12015         if (isPermissionCheckFlagEnabled()) {
12016             enforcePermission(
12017                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
12018                     caller.getPackageName(),
12019                     callingUserId);
12020         } else {
12021             Objects.requireNonNull(who, "ComponentName is null");
12022             Preconditions.checkCallAuthorization(
12023                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
12024         }
12025 
12026         synchronized (getLockObject()) {
12027             long id = mInjector.binderClearCallingIdentity();
12028             try {
12029                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
12030                 if (parent == null) {
12031                     Slogf.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
12032                             + "parent");
12033                     return;
12034                 }
12035                 // Removing those that go from the managed profile to the parent.
12036                 mIPackageManager.clearCrossProfileIntentFilters(
12037                         callingUserId, who.getPackageName());
12038                 // And those that go from the parent to the managed profile.
12039                 // If we want to support multiple managed profiles, we will have to only remove
12040                 // those that have callingUserId as their target.
12041                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
12042             } catch (RemoteException re) {
12043                 // Shouldn't happen
12044                 Slogf.wtf(LOG_TAG, "Error clearing cross profile intent filters", re);
12045             } finally {
12046                 mInjector.binderRestoreCallingIdentity(id);
12047             }
12048         }
12049     }
12050 
12051     /**
12052      * @return true if all packages in enabledPackages are either in the list
12053      * permittedList or are a system app.
12054      */
12055     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
12056             List<String> permittedList, int userIdToCheck) {
12057         long id = mInjector.binderClearCallingIdentity();
12058         try {
12059             // If we have an enabled packages list for a managed profile the packages
12060             // we should check are installed for the parent user.
12061             UserInfo user = getUserInfo(userIdToCheck);
12062             if (user.isManagedProfile()) {
12063                 userIdToCheck = user.profileGroupId;
12064             }
12065 
12066             for (String enabledPackage : enabledPackages) {
12067                 boolean systemService = false;
12068                 try {
12069                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
12070                             enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
12071                             userIdToCheck);
12072 
12073                     if (applicationInfo == null) {
12074                         return false;
12075                     }
12076 
12077                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12078                 } catch (RemoteException e) {
12079                     Slogf.i(LOG_TAG, "Can't talk to package managed", e);
12080                 }
12081                 if (!systemService && !permittedList.contains(enabledPackage)) {
12082                     return false;
12083                 }
12084             }
12085         } finally {
12086             mInjector.binderRestoreCallingIdentity(id);
12087         }
12088         return true;
12089     }
12090 
12091     /**
12092      * Invoke a method in AccessibilityManager ensuring the client is removed.
12093      */
12094     private <T> T withAccessibilityManager(
12095             int userId, Function<AccessibilityManager, T> function) {
12096         // Not using AccessibilityManager.getInstance because that guesses
12097         // at the user you require based on callingUid and caches for a given
12098         // process.
12099         final IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
12100         final IAccessibilityManager service = iBinder == null
12101                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
12102         final AccessibilityManager am = new AccessibilityManager(mContext, service, userId);
12103         try {
12104             return function.apply(am);
12105         } finally {
12106             am.removeClient();
12107         }
12108     }
12109 
12110     @Override
12111     public boolean setPermittedAccessibilityServices(ComponentName who, List<String> packageList) {
12112         if (!mHasFeature) {
12113             return false;
12114         }
12115         Objects.requireNonNull(who, "ComponentName is null");
12116         final CallerIdentity caller = getCallerIdentity(who);
12117         Preconditions.checkCallAuthorization(
12118                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
12119 
12120         if (packageList != null) {
12121             for (String pkg : packageList) {
12122                 PolicySizeVerifier.enforceMaxPackageNameLength(pkg);
12123             }
12124 
12125             int userId = caller.getUserId();
12126             final List<AccessibilityServiceInfo> enabledServices;
12127             long id = mInjector.binderClearCallingIdentity();
12128             try {
12129                 UserInfo user = getUserInfo(userId);
12130                 if (user.isManagedProfile()) {
12131                     userId = user.profileGroupId;
12132                 }
12133                 enabledServices = withAccessibilityManager(userId,
12134                         am -> am.getEnabledAccessibilityServiceList(FEEDBACK_ALL_MASK));
12135             } finally {
12136                 mInjector.binderRestoreCallingIdentity(id);
12137             }
12138 
12139             if (enabledServices != null) {
12140                 List<String> enabledPackages = new ArrayList<>();
12141                 for (AccessibilityServiceInfo service : enabledServices) {
12142                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
12143                 }
12144                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
12145                         userId)) {
12146                     Slogf.e(LOG_TAG, "Cannot set permitted accessibility services, "
12147                             + "because it contains already enabled accesibility services.");
12148                     return false;
12149                 }
12150             }
12151         }
12152 
12153         synchronized (getLockObject()) {
12154             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
12155             admin.permittedAccessiblityServices = packageList;
12156             saveSettingsLocked(UserHandle.getCallingUserId());
12157         }
12158         final String[] packageArray =
12159                 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null;
12160         DevicePolicyEventLogger
12161                 .createEvent(DevicePolicyEnums.SET_PERMITTED_ACCESSIBILITY_SERVICES)
12162                 .setAdmin(who)
12163                 .setStrings(packageArray)
12164                 .write();
12165         return true;
12166     }
12167 
12168     @Override
12169     public List<String> getPermittedAccessibilityServices(ComponentName who) {
12170         if (!mHasFeature) {
12171             return null;
12172         }
12173         Objects.requireNonNull(who, "ComponentName is null");
12174         final CallerIdentity caller = getCallerIdentity(who);
12175         Preconditions.checkCallAuthorization(
12176                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
12177 
12178         synchronized (getLockObject()) {
12179             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
12180             return admin.permittedAccessiblityServices;
12181         }
12182     }
12183 
12184     @Override
12185     public List<String> getPermittedAccessibilityServicesForUser(int userId) {
12186         if (!mHasFeature) {
12187             return null;
12188         }
12189         final CallerIdentity caller = getCallerIdentity();
12190         Preconditions.checkCallAuthorization(canManageUsers(caller) || canQueryAdminPolicy(caller));
12191 
12192         List<String> result = null;
12193 
12194         synchronized (getLockObject()) {
12195             // If we have multiple profiles we return the intersection of the
12196             // permitted lists. This can happen in cases where we have a device
12197             // and profile owner.
12198             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
12199             for (int profileId : profileIds) {
12200                 // Just loop though all admins, only device or profiles
12201                 // owners can have permitted lists set.
12202                 DevicePolicyData policy = getUserDataUnchecked(profileId);
12203                 final int N = policy.mAdminList.size();
12204                 for (int j = 0; j < N; j++) {
12205                     ActiveAdmin admin = policy.mAdminList.get(j);
12206                     List<String> fromAdmin = admin.permittedAccessiblityServices;
12207                     if (fromAdmin != null) {
12208                         if (result == null) {
12209                             result = new ArrayList<>(fromAdmin);
12210                         } else {
12211                             result.retainAll(fromAdmin);
12212                         }
12213                     }
12214                 }
12215             }
12216         }
12217 
12218         // If we have a permitted list add all system accessibility services.
12219         if (result != null) {
12220             long id = mInjector.binderClearCallingIdentity();
12221             try {
12222                 UserInfo user = getUserInfo(userId);
12223                 if (user.isManagedProfile()) {
12224                     userId = user.profileGroupId;
12225                 }
12226                 // Move AccessibilityManager out of {@link getLockObject} to prevent potential
12227                 // deadlock.
12228                 final List<AccessibilityServiceInfo> installedServices =
12229                         withAccessibilityManager(userId,
12230                                 AccessibilityManager::getInstalledAccessibilityServiceList);
12231 
12232                 if (installedServices != null) {
12233                     for (AccessibilityServiceInfo service : installedServices) {
12234                         ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
12235                         ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
12236                         if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12237                             result.add(serviceInfo.packageName);
12238                         }
12239                     }
12240                 }
12241             } finally {
12242                 mInjector.binderRestoreCallingIdentity(id);
12243             }
12244         }
12245 
12246         return result;
12247     }
12248 
12249     @Override
12250     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
12251             int userHandle) {
12252         if (!mHasFeature) {
12253             return true;
12254         }
12255         Objects.requireNonNull(who, "ComponentName is null");
12256         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
12257         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
12258                 String.format(NOT_SYSTEM_CALLER_MSG,
12259                         "query if an accessibility service is disabled by admin"));
12260 
12261         synchronized (getLockObject()) {
12262             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
12263             if (admin == null) {
12264                 return false;
12265             }
12266             if (admin.permittedAccessiblityServices == null) {
12267                 return true;
12268             }
12269             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
12270                     admin.permittedAccessiblityServices, userHandle);
12271         }
12272     }
12273 
12274     @Override
12275     public boolean setPermittedInputMethods(ComponentName who, String callerPackageName,
12276             List<String> packageList, boolean calledOnParentInstance) {
12277         if (!mHasFeature) {
12278             return false;
12279         }
12280 
12281         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
12282 
12283         int userId = getProfileParentUserIfRequested(
12284                 caller.getUserId(), calledOnParentInstance);
12285         if (calledOnParentInstance) {
12286             Preconditions.checkArgument(packageList == null || packageList.isEmpty(),
12287                     "Permitted input methods must allow all input methods or only "
12288                             + "system input methods when called on the parent instance of an "
12289                             + "organization-owned device");
12290         }
12291 
12292         if (packageList != null) {
12293             if (!Flags.devicePolicySizeTrackingInternalBugFixEnabled()) {
12294                 for (String pkg : packageList) {
12295                     PolicySizeVerifier.enforceMaxPackageNameLength(pkg);
12296                 }
12297             }
12298 
12299             List<InputMethodInfo> enabledImes = mInjector.binderWithCleanCallingIdentity(() ->
12300                     InputMethodManagerInternal.get().getEnabledInputMethodListAsUser(userId));
12301             if (enabledImes != null) {
12302                 List<String> enabledPackages = new ArrayList<String>();
12303                 for (InputMethodInfo ime : enabledImes) {
12304                     enabledPackages.add(ime.getPackageName());
12305                 }
12306                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
12307                         userId)) {
12308                     Slogf.e(LOG_TAG, "Cannot set permitted input methods, because the list of "
12309                             + "permitted input methods excludes an already-enabled input method.");
12310                     return false;
12311                 }
12312             }
12313         }
12314 
12315         synchronized (getLockObject()) {
12316             EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
12317                     who, MANAGE_DEVICE_POLICY_INPUT_METHODS,
12318                     caller.getPackageName(), userId);
12319             if (packageList == null) {
12320                 mDevicePolicyEngine.removeLocalPolicy(
12321                         PolicyDefinition.PERMITTED_INPUT_METHODS,
12322                         admin,
12323                         userId);
12324             } else {
12325                 mDevicePolicyEngine.setLocalPolicy(
12326                         PolicyDefinition.PERMITTED_INPUT_METHODS,
12327                         admin,
12328                         new PackageSetPolicyValue(new HashSet<>(packageList)),
12329                         userId);
12330             }
12331         }
12332 
12333         DevicePolicyEventLogger
12334                 .createEvent(DevicePolicyEnums.SET_PERMITTED_INPUT_METHODS)
12335                 .setAdmin(caller.getPackageName())
12336                 .setStrings(getStringArrayForLogging(packageList, calledOnParentInstance))
12337                 .write();
12338         return true;
12339     }
12340 
12341     private String[] getStringArrayForLogging(List list, boolean calledOnParentInstance) {
12342         List<String> stringList = new ArrayList<String>();
12343         stringList.add(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT);
12344         if (list == null) {
12345             stringList.add(NULL_STRING_ARRAY);
12346         } else {
12347             stringList.addAll((List<String>) list);
12348         }
12349         return stringList.toArray(new String[0]);
12350     }
12351 
12352     @Override
12353     public List<String> getPermittedInputMethods(ComponentName who, String callerPackageName,
12354             boolean calledOnParentInstance) {
12355         if (!mHasFeature) {
12356             return null;
12357         }
12358 
12359         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
12360 
12361         synchronized (getLockObject()) {
12362             int affectedUser = calledOnParentInstance ? getProfileParentId(
12363                     caller.getUserId()) : caller.getUserId();
12364             Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
12365                     PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
12366             return policy == null ? null : new ArrayList<>(policy);
12367         }
12368     }
12369 
12370     @Override
12371     public @Nullable List<String> getPermittedInputMethodsAsUser(@UserIdInt int userId) {
12372         final CallerIdentity caller = getCallerIdentity();
12373         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
12374         Preconditions.checkCallAuthorization(canManageUsers(caller) || canQueryAdminPolicy(caller));
12375         final long callingIdentity = Binder.clearCallingIdentity();
12376         try {
12377             return getPermittedInputMethodsUnchecked(userId);
12378         } finally {
12379             Binder.restoreCallingIdentity(callingIdentity);
12380         }
12381     }
12382 
12383     private @Nullable List<String> getPermittedInputMethodsUnchecked(@UserIdInt int userId) {
12384         Set<String> policy = mDevicePolicyEngine.getResolvedPolicy(
12385                 PolicyDefinition.PERMITTED_INPUT_METHODS, userId);
12386         List<String> result = policy == null ? null : new ArrayList<>(policy);
12387 
12388         // If we have a permitted list add all system input methods.
12389         if (result != null) {
12390             List<InputMethodInfo> imes = InputMethodManagerInternal
12391                     .get().getInputMethodListAsUser(userId);
12392             if (imes != null) {
12393                 for (InputMethodInfo ime : imes) {
12394                     ServiceInfo serviceInfo = ime.getServiceInfo();
12395                     ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
12396                     if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12397                         result.add(serviceInfo.packageName);
12398                     }
12399                 }
12400             }
12401         }
12402         return result;
12403     }
12404 
12405     @Override
12406     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
12407             int userHandle, boolean calledOnParentInstance) {
12408         if (!mHasFeature) {
12409             return true;
12410         }
12411         Objects.requireNonNull(who, "ComponentName is null");
12412         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
12413         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
12414                 String.format(NOT_SYSTEM_CALLER_MSG,
12415                         "query if an input method is disabled by admin"));
12416 
12417         int affectedUser = calledOnParentInstance ? getProfileParentId(userHandle) : userHandle;
12418         Map<EnforcingAdmin, PolicyValue<Set<String>>> policies =
12419                 mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
12420                         PolicyDefinition.PERMITTED_INPUT_METHODS, affectedUser);
12421         for (EnforcingAdmin a : policies.keySet()) {
12422             if (a.getPackageName().equals(who.getPackageName())) {
12423                 if (policies.get(a).getValue() == null) {
12424                     return true;
12425                 } else {
12426                     return checkPackagesInPermittedListOrSystem(
12427                             Collections.singletonList(packageName),
12428                             new ArrayList<>(policies.get(a).getValue()), affectedUser);
12429                 }
12430             }
12431         }
12432         // Admin didn't set a policy
12433         return false;
12434     }
12435 
12436     @Override
12437     public boolean setPermittedCrossProfileNotificationListeners(
12438             ComponentName who, List<String> packageList) {
12439         if (!mHasFeature) {
12440             return false;
12441         }
12442         Objects.requireNonNull(who, "ComponentName is null");
12443         final CallerIdentity caller = getCallerIdentity(who);
12444 
12445         if (!isManagedProfile(caller.getUserId())) {
12446             return false;
12447         }
12448         Preconditions.checkCallAuthorization(isProfileOwner(caller));
12449         synchronized (getLockObject()) {
12450             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
12451             admin.permittedNotificationListeners = packageList;
12452             saveSettingsLocked(caller.getUserId());
12453         }
12454         return true;
12455     }
12456 
12457     @Override
12458     public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
12459         if (!mHasFeature) {
12460             return null;
12461         }
12462         Objects.requireNonNull(who, "ComponentName is null");
12463         final CallerIdentity caller = getCallerIdentity(who);
12464         Preconditions.checkCallAuthorization(
12465                 isDeviceOwner(caller) || isProfileOwner(caller));
12466 
12467         synchronized (getLockObject()) {
12468             // API contract is to return null if there are no permitted cross-profile notification
12469             // listeners, including in Device Owner mode.
12470             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
12471             return admin.permittedNotificationListeners;
12472         }
12473     }
12474 
12475     @Override
12476     public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
12477         if (!mHasFeature) {
12478             return true;
12479         }
12480 
12481         Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
12482         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
12483                 String.format(NOT_SYSTEM_CALLER_MSG,
12484                         "query if a notification listener service is permitted"));
12485 
12486         synchronized (getLockObject()) {
12487             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
12488             if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
12489                 return true;
12490             }
12491             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
12492                     profileOwner.permittedNotificationListeners, userId);
12493 
12494         }
12495     }
12496 
12497     private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
12498         DevicePolicyData policyData = getUserData(userHandle);
12499         if (policyData.mAdminBroadcastPending) {
12500             // Send the initialization data to profile owner and delete the data
12501             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
12502             boolean clearInitBundle = true;
12503             if (admin != null) {
12504                 PersistableBundle initBundle = policyData.mInitBundle;
12505                 clearInitBundle = sendAdminCommandLocked(admin,
12506                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
12507                         initBundle == null ? null : new Bundle(initBundle),
12508                         /* result= */ null ,
12509                         /* inForeground= */ true);
12510             }
12511             if (clearInitBundle) {
12512                 // If there's no admin or we've successfully called the admin, clear the init bundle
12513                 // otherwise, keep it around
12514                 policyData.mInitBundle = null;
12515                 policyData.mAdminBroadcastPending = false;
12516                 saveSettingsLocked(userHandle);
12517             }
12518         }
12519     }
12520 
12521     @Override
12522     public UserHandle createAndManageUser(ComponentName admin, String name,
12523             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
12524         Objects.requireNonNull(admin, "admin is null");
12525         Objects.requireNonNull(profileOwner, "profileOwner is null");
12526         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
12527             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
12528                     + admin + " are not in the same package");
12529         }
12530         final CallerIdentity caller = getCallerIdentity(admin);
12531 
12532         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12533         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CREATE_AND_MANAGE_USER);
12534 
12535         if (Flags.headlessDeviceOwnerSingleUserEnabled()) {
12536             // Block this method if the device is in headless main user mode
12537             Preconditions.checkCallAuthorization(
12538                     !mInjector.userManagerIsHeadlessSystemUserMode()
12539                             || getHeadlessDeviceOwnerModeForDeviceOwner()
12540                             != HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER,
12541                     "createAndManageUser was called while in headless single user mode");
12542         }
12543 
12544         // Only allow the system user to use this method
12545         Preconditions.checkCallAuthorization(caller.getUserHandle().isSystem(),
12546                 "createAndManageUser was called from non-system user");
12547 
12548         final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
12549         final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
12550                 && UserManager.isDeviceInDemoMode(mContext);
12551         final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
12552         final int targetSdkVersion;
12553 
12554         // Create user.
12555         UserHandle user = null;
12556         synchronized (getLockObject()) {
12557             final long id = mInjector.binderClearCallingIdentity();
12558             try {
12559                 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion(
12560                         caller.getUid());
12561 
12562                 // Return detail error code for checks inside
12563                 // UserManagerService.createUserInternalUnchecked.
12564                 DeviceStorageMonitorInternal deviceStorageMonitorInternal =
12565                         LocalServices.getService(DeviceStorageMonitorInternal.class);
12566                 if (deviceStorageMonitorInternal.isMemoryLow()) {
12567                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
12568                         throw new ServiceSpecificException(
12569                                 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage");
12570                     } else {
12571                         return null;
12572                     }
12573                 }
12574 
12575                 String userType = demo ? UserManager.USER_TYPE_FULL_DEMO
12576                         : UserManager.USER_TYPE_FULL_SECONDARY;
12577                 int userInfoFlags = ephemeral ? UserInfo.FLAG_EPHEMERAL : 0;
12578 
12579                 if (!mUserManager.canAddMoreUsers(userType)) {
12580                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
12581                         throw new ServiceSpecificException(
12582                                 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached");
12583                     } else {
12584                         return null;
12585                     }
12586                 }
12587 
12588                 String[] disallowedPackages = null;
12589                 if (!leaveAllSystemAppsEnabled) {
12590                     disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
12591                             UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
12592                             new String[0]);
12593                 }
12594 
12595                 Object token = new Object();
12596                 Slogf.d(LOG_TAG, "Adding new pending token: " + token);
12597                 mPendingUserCreatedCallbackTokens.add(token);
12598                 try {
12599                     UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
12600                             userType, userInfoFlags, disallowedPackages, token);
12601                     if (userInfo != null) {
12602                         user = userInfo.getUserHandle();
12603                     }
12604                 } catch (UserManager.CheckedUserOperationException e) {
12605                     Slogf.e(LOG_TAG, "Couldn't createUserEvenWhenDisallowed", e);
12606                 }
12607             } finally {
12608                 mInjector.binderRestoreCallingIdentity(id);
12609             }
12610         } // synchronized
12611 
12612         if (user == null) {
12613             if (targetSdkVersion >= Build.VERSION_CODES.P) {
12614                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
12615                         "failed to create user");
12616             } else {
12617                 return null;
12618             }
12619         }
12620 
12621         final int userHandle = user.getIdentifier();
12622         final long id = mInjector.binderClearCallingIdentity();
12623         try {
12624             maybeInstallDevicePolicyManagementRoleHolderInUser(userHandle);
12625 
12626             manageUserUnchecked(admin, profileOwner, userHandle, adminExtras,
12627                     /* showDisclaimer= */ true);
12628 
12629             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
12630                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
12631                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
12632             }
12633 
12634             sendProvisioningCompletedBroadcast(
12635                     userHandle, ACTION_PROVISION_MANAGED_USER, leaveAllSystemAppsEnabled);
12636 
12637             return user;
12638         } catch (Throwable re) {
12639             mUserManager.removeUser(userHandle);
12640             if (targetSdkVersion >= Build.VERSION_CODES.P) {
12641                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
12642                         re.getMessage());
12643             } else {
12644                 return null;
12645             }
12646         } finally {
12647             mInjector.binderRestoreCallingIdentity(id);
12648         }
12649     }
12650 
12651     private void sendProvisioningCompletedBroadcast(
12652             int user, String action, boolean leaveAllSystemAppsEnabled) {
12653         final Intent intent = new Intent(DevicePolicyManager.ACTION_PROVISIONING_COMPLETED)
12654                 .putExtra(Intent.EXTRA_USER_HANDLE, user)
12655                 .putExtra(Intent.EXTRA_USER, UserHandle.of(user))
12656                 .putExtra(
12657                         DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
12658                         leaveAllSystemAppsEnabled)
12659                 .putExtra(DevicePolicyManager.EXTRA_PROVISIONING_ACTION,
12660                         action)
12661                 .setPackage(getManagedProvisioningPackage(mContext))
12662                 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12663         mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
12664     }
12665 
12666     private void manageUserUnchecked(ComponentName admin, ComponentName profileOwner,
12667             @UserIdInt int userId, @Nullable PersistableBundle adminExtras,
12668             boolean showDisclaimer) {
12669         synchronized (getLockObject()) {
12670             if (VERBOSE_LOG) {
12671                 Slogf.v(LOG_TAG, "manageUserUnchecked(): admin=" + admin + ", po=" + profileOwner
12672                         + ", userId=" + userId + ", hasAdminExtras=" + (adminExtras != null)
12673                         + ", showDisclaimer=" + showDisclaimer);
12674             }
12675         }
12676         final String adminPkg = admin.getPackageName();
12677         mInjector.binderWithCleanCallingIdentity(() -> {
12678             try {
12679                 // Install the profile owner if not present.
12680                 if (!mIPackageManager.isPackageAvailable(adminPkg, userId)) {
12681                     mIPackageManager.installExistingPackageAsUser(adminPkg, userId,
12682                             PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
12683                             PackageManager.INSTALL_REASON_POLICY,
12684                             /* allowlistedRestrictedPermissions= */ null);
12685                 }
12686             } catch (RemoteException e) {
12687                 // Does not happen, same process
12688                 Slogf.wtf(LOG_TAG, e, "Failed to install admin package %s for user %d",
12689                         adminPkg, userId);
12690             }
12691         });
12692 
12693         // Set admin.
12694         setActiveAdmin(profileOwner, /* refreshing= */ true, userId);
12695         setProfileOwner(profileOwner, userId);
12696 
12697         synchronized (getLockObject()) {
12698             DevicePolicyData policyData = getUserData(userId);
12699             policyData.mInitBundle = adminExtras;
12700             policyData.mAdminBroadcastPending = true;
12701             policyData.mNewUserDisclaimer = showDisclaimer
12702                     ? DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED
12703                     : DevicePolicyData.NEW_USER_DISCLAIMER_NOT_NEEDED;
12704             saveSettingsLocked(userId);
12705 
12706         }
12707     }
12708 
12709     private void handleNewUserCreated(UserInfo user, @Nullable Object token) {
12710         if (VERBOSE_LOG) {
12711             Slogf.v(LOG_TAG, "handleNewUserCreated(): user=" + user.toFullString()
12712                     + ", token=" + token);
12713         }
12714 
12715         mDevicePolicyEngine.handleUserCreated(user);
12716 
12717         final int userId = user.id;
12718         if (token != null) {
12719             synchronized (getLockObject()) {
12720                 if (mPendingUserCreatedCallbackTokens.contains(token)) {
12721                     // Ignore because it was triggered by createAndManageUser()
12722                     Slogf.d(LOG_TAG, "handleNewUserCreated(): ignoring for user " + userId
12723                             + " due to token " + token);
12724                     mPendingUserCreatedCallbackTokens.remove(token);
12725                     return;
12726                 }
12727             }
12728         }
12729 
12730         if (!mOwners.hasDeviceOwner() || !user.isFull() || user.isManagedProfile()
12731                 || user.isGuest()) {
12732             return;
12733         }
12734 
12735         if (mInjector.userManagerIsHeadlessSystemUserMode()) {
12736             ComponentName admin = mOwners.getDeviceOwnerComponent();
12737             Slogf.i(LOG_TAG, "Automatically setting profile owner (" + admin + ") on new user "
12738                     + userId);
12739             manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin,
12740                     /* managedUser= */ userId, /* adminExtras= */ null, /* showDisclaimer= */ true);
12741         } else {
12742             Slogf.i(LOG_TAG, "User %d added on DO mode; setting ShowNewUserDisclaimer", userId);
12743             setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED);
12744         }
12745     }
12746 
12747     @Override
12748     public void acknowledgeNewUserDisclaimer(@UserIdInt int userId) {
12749         CallerIdentity callerIdentity = getCallerIdentity();
12750         Preconditions.checkCallAuthorization(canManageUsers(callerIdentity)
12751                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
12752 
12753         setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_ACKNOWLEDGED);
12754     }
12755 
12756     private void setShowNewUserDisclaimer(@UserIdInt int userId, String value) {
12757         Slogf.i(LOG_TAG, "Setting new user disclaimer for user " + userId + " as " + value);
12758         synchronized (getLockObject()) {
12759             DevicePolicyData policyData = getUserData(userId);
12760             policyData.mNewUserDisclaimer = value;
12761             saveSettingsLocked(userId);
12762         }
12763     }
12764 
12765     private void showNewUserDisclaimerIfNecessary(@UserIdInt int userId) {
12766         boolean mustShow;
12767         synchronized (getLockObject()) {
12768             DevicePolicyData policyData = getUserData(userId);
12769             if (VERBOSE_LOG) {
12770                 Slogf.v(LOG_TAG, "showNewUserDisclaimerIfNecessary(" + userId + "): "
12771                         + policyData.mNewUserDisclaimer + ")");
12772             }
12773             mustShow = DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED
12774                     .equals(policyData.mNewUserDisclaimer);
12775         }
12776         if (!mustShow) return;
12777 
12778         Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_NEW_USER_DISCLAIMER);
12779 
12780         // TODO(b/172691310): add CTS tests to make sure disclaimer is shown
12781         Slogf.i(LOG_TAG, "Dispatching ACTION_SHOW_NEW_USER_DISCLAIMER intent");
12782         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
12783     }
12784 
12785     @Override
12786     public boolean isNewUserDisclaimerAcknowledged(@UserIdInt int userId) {
12787         CallerIdentity callerIdentity = getCallerIdentity();
12788         Preconditions.checkCallAuthorization(canManageUsers(callerIdentity)
12789                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
12790         synchronized (getLockObject()) {
12791             DevicePolicyData policyData = getUserData(userId);
12792             return policyData.isNewUserDisclaimerAcknowledged();
12793         }
12794     }
12795 
12796     @Override
12797     public boolean removeUser(ComponentName who, UserHandle userHandle) {
12798         Objects.requireNonNull(who, "ComponentName is null");
12799         Objects.requireNonNull(userHandle, "UserHandle is null");
12800         final CallerIdentity caller = getCallerIdentity(who);
12801         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12802         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_USER);
12803 
12804         return mInjector.binderWithCleanCallingIdentity(() -> {
12805             String restriction = isManagedProfile(userHandle.getIdentifier())
12806                     ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
12807                     : UserManager.DISALLOW_REMOVE_USER;
12808             if (isAdminAffectedByRestriction(who, restriction, caller.getUserId())) {
12809                 Slogf.w(LOG_TAG, "The device owner cannot remove a user because %s is enabled, and "
12810                         + "was not set by the device owner", restriction);
12811                 return false;
12812             }
12813             return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
12814         });
12815     }
12816 
12817     private boolean isAdminAffectedByRestriction(
12818             @Nullable ComponentName admin, String userRestriction, int userId) {
12819         switch (mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
12820             case UserManager.RESTRICTION_NOT_SET:
12821                 return false;
12822             case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
12823             case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
12824                 return !(isDeviceOwner(admin, userId) || isProfileOwner(admin, userId));
12825             default:
12826                 return true;
12827         }
12828     }
12829 
12830     @Override
12831     public boolean switchUser(ComponentName who, UserHandle userHandle) {
12832         Objects.requireNonNull(who, "ComponentName is null");
12833         final CallerIdentity caller = getCallerIdentity(who);
12834         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12835         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SWITCH_USER);
12836 
12837         boolean switched = false;
12838         // Save previous logout user id in case of failure
12839         int logoutUserId = getLogoutUserIdUnchecked();
12840         synchronized (getLockObject()) {
12841             long id = mInjector.binderClearCallingIdentity();
12842             try {
12843                 int userId = UserHandle.USER_SYSTEM;
12844                 if (userHandle != null) {
12845                     userId = userHandle.getIdentifier();
12846                 }
12847                 Slogf.i(LOG_TAG, "Switching to user %d (logout user is %d)", userId, logoutUserId);
12848                 setLogoutUserIdLocked(UserHandle.USER_CURRENT);
12849                 switched = mInjector.getIActivityManager().switchUser(userId);
12850                 if (!switched) {
12851                     Slogf.w(LOG_TAG, "Failed to switch to user %d", userId);
12852                 } else {
12853                     Slogf.d(LOG_TAG, "Switched");
12854                 }
12855                 return switched;
12856             } catch (RemoteException e) {
12857                 Slogf.e(LOG_TAG, "Couldn't switch user", e);
12858                 return false;
12859             } finally {
12860                 mInjector.binderRestoreCallingIdentity(id);
12861                 if (!switched) {
12862                     setLogoutUserIdLocked(logoutUserId);
12863                 }
12864             }
12865         }
12866     }
12867 
12868     @Override
12869     public int getLogoutUserId() {
12870         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
12871                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
12872 
12873         return getLogoutUserIdUnchecked();
12874     }
12875 
12876     private @UserIdInt int getLogoutUserIdUnchecked() {
12877         synchronized (getLockObject()) {
12878             return mLogoutUserId;
12879         }
12880     }
12881 
12882     private void clearLogoutUser() {
12883         synchronized (getLockObject()) {
12884             setLogoutUserIdLocked(UserHandle.USER_NULL);
12885         }
12886     }
12887 
12888     @GuardedBy("getLockObject()")
12889     private void setLogoutUserIdLocked(@UserIdInt int userId) {
12890         if (userId == UserHandle.USER_CURRENT) {
12891             userId = getCurrentForegroundUserId();
12892         }
12893 
12894         Slogf.d(LOG_TAG, "setLogoutUserId(): %d -> %d", mLogoutUserId, userId);
12895         mLogoutUserId = userId;
12896     }
12897 
12898     @Override
12899     public int startUserInBackground(ComponentName who, UserHandle userHandle) {
12900         Objects.requireNonNull(who, "ComponentName is null");
12901         Objects.requireNonNull(userHandle, "UserHandle is null");
12902         final CallerIdentity caller = getCallerIdentity(who);
12903         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12904         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_START_USER_IN_BACKGROUND);
12905 
12906         final int userId = userHandle.getIdentifier();
12907         if (isManagedProfile(userId)) {
12908             Slogf.w(LOG_TAG, "Managed profile cannot be started in background");
12909             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
12910         }
12911 
12912         final long id = mInjector.binderClearCallingIdentity();
12913         try {
12914             if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) {
12915                 Slogf.w(LOG_TAG, "Cannot start user %d, too many users in background", userId);
12916                 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS;
12917             }
12918 
12919             Slogf.i(LOG_TAG, "Starting user %d in background", userId);
12920             if (mInjector.getIActivityManager().startUserInBackground(userId)) {
12921                 return UserManager.USER_OPERATION_SUCCESS;
12922             } else {
12923                 Slogf.w(LOG_TAG, "failed to start user %d in background", userId);
12924                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
12925             }
12926         } catch (RemoteException e) {
12927             // Same process, should not happen.
12928             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
12929         } finally {
12930             mInjector.binderRestoreCallingIdentity(id);
12931         }
12932     }
12933 
12934     @Override
12935     public int stopUser(ComponentName who, UserHandle userHandle) {
12936         Objects.requireNonNull(who, "ComponentName is null");
12937         Objects.requireNonNull(userHandle, "UserHandle is null");
12938         final CallerIdentity caller = getCallerIdentity(who);
12939         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
12940         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_STOP_USER);
12941 
12942         final int userId = userHandle.getIdentifier();
12943         if (isManagedProfile(userId)) {
12944             Slogf.w(LOG_TAG, "Managed profile cannot be stopped");
12945             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
12946         }
12947 
12948         return stopUserUnchecked(userId);
12949     }
12950 
12951     @Override
12952     public int logoutUser(ComponentName who) {
12953         Objects.requireNonNull(who, "ComponentName is null");
12954         final CallerIdentity caller = getCallerIdentity(who);
12955         Preconditions.checkCallAuthorization(
12956                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
12957         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOGOUT_USER);
12958 
12959         final int callingUserId = caller.getUserId();
12960         synchronized (getLockObject()) {
12961             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
12962                 throw new SecurityException("Admin " + who +
12963                         " is neither the device owner or affiliated user's profile owner.");
12964             }
12965         }
12966 
12967         if (isManagedProfile(callingUserId)) {
12968             Slogf.w(LOG_TAG, "Managed profile cannot be logout");
12969             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
12970         }
12971 
12972         if (callingUserId != mInjector
12973                 .binderWithCleanCallingIdentity(() -> getCurrentForegroundUserId())) {
12974             Slogf.d(LOG_TAG, "logoutUser(): user %d is in background, just stopping, not switching",
12975                     callingUserId);
12976             return stopUserUnchecked(callingUserId);
12977         }
12978 
12979         return logoutUserUnchecked(/* userIdToStop= */ callingUserId);
12980     }
12981 
12982     @Override
12983     public int logoutUserInternal() {
12984         CallerIdentity caller = getCallerIdentity();
12985         Preconditions.checkCallAuthorization(canManageUsers(caller)
12986                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
12987 
12988         int currentUserId = getCurrentForegroundUserId();
12989         if (VERBOSE_LOG) {
12990             Slogf.v(LOG_TAG, "logout() called by uid %d; current user is %d", caller.getUid(),
12991                     currentUserId);
12992         }
12993         int result = logoutUserUnchecked(currentUserId);
12994         if (VERBOSE_LOG) {
12995             Slogf.v(LOG_TAG, "Result of logout(): %d", result);
12996         }
12997         return result;
12998     }
12999 
13000     private int logoutUserUnchecked(@UserIdInt int userIdToStop) {
13001         int logoutUserId = getLogoutUserIdUnchecked();
13002         if (logoutUserId == UserHandle.USER_NULL) {
13003             // Could happen on devices using headless system user mode when called before calling
13004             // switchUser() or startUserInBackground() first
13005             Slogf.w(LOG_TAG, "logoutUser(): could not determine which user to switch to");
13006             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13007         }
13008         final long id = mInjector.binderClearCallingIdentity();
13009         try {
13010             Slogf.i(LOG_TAG, "logoutUser(): switching to user %d", logoutUserId);
13011             if (!mInjector.getIActivityManager().switchUser(logoutUserId)) {
13012                 Slogf.w(LOG_TAG, "Failed to switch to user %d", logoutUserId);
13013                 // This should never happen as target user is determined by getPreviousUserId()
13014                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13015             }
13016             clearLogoutUser();
13017         } catch (RemoteException e) {
13018             // Same process, should not happen.
13019             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13020         } finally {
13021             mInjector.binderRestoreCallingIdentity(id);
13022         }
13023 
13024         return stopUserUnchecked(userIdToStop);
13025     }
13026 
13027     private int stopUserUnchecked(@UserIdInt int userId) {
13028         Slogf.i(LOG_TAG, "Stopping user %d", userId);
13029         final long id = mInjector.binderClearCallingIdentity();
13030         try {
13031             switch (mInjector.getIActivityManager().stopUserWithCallback(userId, null)) {
13032                 case ActivityManager.USER_OP_SUCCESS:
13033                     return UserManager.USER_OPERATION_SUCCESS;
13034                 case ActivityManager.USER_OP_IS_CURRENT:
13035                     return UserManager.USER_OPERATION_ERROR_CURRENT_USER;
13036                 default:
13037                     return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13038             }
13039         } catch (RemoteException e) {
13040             // Same process, should not happen.
13041             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
13042         } finally {
13043             mInjector.binderRestoreCallingIdentity(id);
13044         }
13045     }
13046 
13047     @Override
13048     public List<UserHandle> getSecondaryUsers(ComponentName who) {
13049         Objects.requireNonNull(who, "ComponentName is null");
13050         final CallerIdentity caller = getCallerIdentity(who);
13051         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
13052 
13053         return mInjector.binderWithCleanCallingIdentity(() -> {
13054             final List<UserInfo> userInfos = mInjector.getUserManager().getAliveUsers();
13055             final List<UserHandle> userHandles = new ArrayList<>();
13056             for (UserInfo userInfo : userInfos) {
13057                 UserHandle userHandle = userInfo.getUserHandle();
13058                 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
13059                     userHandles.add(userInfo.getUserHandle());
13060                 }
13061             }
13062             return userHandles;
13063         });
13064     }
13065 
13066     @Override
13067     public boolean isEphemeralUser(ComponentName who) {
13068         Objects.requireNonNull(who, "ComponentName is null");
13069 
13070         final CallerIdentity caller = getCallerIdentity(who);
13071         Preconditions.checkCallAuthorization(
13072                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
13073 
13074         return mInjector.binderWithCleanCallingIdentity(
13075                 () -> mInjector.getUserManager().isUserEphemeral(caller.getUserId()));
13076     }
13077 
13078     @Override
13079     public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
13080             String packageName, boolean parent) {
13081         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
13082 
13083         if (isUnicornFlagEnabled()) {
13084             EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
13085                     who,
13086                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
13087                     caller.getPackageName(),
13088                     caller.getUserId()
13089             );
13090 
13091             LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
13092                     mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
13093                             PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
13094                             caller.getUserId());
13095             if (policies.isEmpty() || !policies.containsKey(enforcingAdmin)) {
13096                 return Bundle.EMPTY;
13097             }
13098             return policies.get(enforcingAdmin).getValue();
13099         } else if (Flags.dmrhSetAppRestrictions()) {
13100             final boolean isRoleHolder;
13101             if (who != null) {
13102                 // Caller is DO or PO. They cannot call this on parent
13103                 Preconditions.checkCallAuthorization(!parent
13104                         && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)));
13105                 // Caller has opted to be treated as DPC (by passing a non-null who), so don't
13106                 // consider it as the DMRH, even if the caller is both the DPC and the DMRH.
13107                 isRoleHolder = false;
13108             } else {
13109                 // Caller is delegates or the DMRH. Only DMRH can call this on parent
13110                 isRoleHolder = isCallerDevicePolicyManagementRoleHolder(caller);
13111                 if (parent) {
13112                     Preconditions.checkCallAuthorization(isRoleHolder);
13113                     Preconditions.checkState(isOrganizationOwnedDeviceWithManagedProfile(),
13114                             "Role Holder can only operate parent app restriction on COPE devices");
13115                 } else {
13116                     Preconditions.checkCallAuthorization(isRoleHolder
13117                             || isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS));
13118                 }
13119             }
13120             if (isRoleHolder) {
13121                 EnforcingAdmin enforcingAdmin = getEnforcingAdminForCaller(/* who */ null,
13122                         caller.getPackageName());
13123                 int affectedUserId = parent
13124                         ? getProfileParentId(caller.getUserId()) : caller.getUserId();
13125                 LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
13126                         mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
13127                                 PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
13128                                 affectedUserId);
13129                 if (!policies.containsKey(enforcingAdmin)) {
13130                     return Bundle.EMPTY;
13131                 }
13132                 return policies.get(enforcingAdmin).getValue();
13133             } else {
13134                 return mInjector.binderWithCleanCallingIdentity(() -> {
13135                     Bundle bundle = mUserManager.getApplicationRestrictions(packageName,
13136                             caller.getUserHandle());
13137                     // if no restrictions were saved, mUserManager.getApplicationRestrictions
13138                     // returns null, but DPM method should return an empty Bundle as per JavaDoc
13139                     return bundle != null ? bundle : Bundle.EMPTY;
13140                 });
13141             }
13142 
13143         } else {
13144             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13145                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
13146                     || (caller.hasPackage() && isCallerDelegate(caller,
13147                     DELEGATION_APP_RESTRICTIONS)));
13148             return mInjector.binderWithCleanCallingIdentity(() -> {
13149                 Bundle bundle = mUserManager.getApplicationRestrictions(packageName,
13150                         caller.getUserHandle());
13151                 // if no restrictions were saved, mUserManager.getApplicationRestrictions
13152                 // returns null, but DPM method should return an empty Bundle as per JavaDoc
13153                 return bundle != null ? bundle : Bundle.EMPTY;
13154             });
13155         }
13156     }
13157 
13158     /**
13159      * Returns the apps that are non-exempt from some policies (such as suspension), and populates
13160      * the given set with the apps that are exempt.
13161      *
13162      * @param packageNames apps to check
13163      * @param outputExemptApps will be populate with subset of {@code packageNames} that is exempt
13164      * from some policy restrictions
13165      *
13166      * @return subset of {@code packageNames} that is affected by some policy restrictions.
13167      */
13168     private String[] populateNonExemptAndExemptFromPolicyApps(String[] packageNames,
13169             Set<String> outputExemptApps) {
13170         Preconditions.checkArgument(outputExemptApps.isEmpty(), "outputExemptApps is not empty");
13171         List<String> exemptAppsList = listPolicyExemptAppsUnchecked(mContext);
13172         if (exemptAppsList.isEmpty()) {
13173             return packageNames;
13174         }
13175         // Using a set so contains() is O(1)
13176         Set<String> exemptApps = new HashSet<>(exemptAppsList);
13177         List<String> nonExemptApps = new ArrayList<>(packageNames.length);
13178         for (int i = 0; i < packageNames.length; i++) {
13179             String app = packageNames[i];
13180             if (exemptApps.contains(app)) {
13181                 outputExemptApps.add(app);
13182             } else {
13183                 nonExemptApps.add(app);
13184             }
13185         }
13186         String[] result = new String[nonExemptApps.size()];
13187         nonExemptApps.toArray(result);
13188         return result;
13189     }
13190 
13191     private String[] setPackagesSuspendedPreCoexistence(ComponentName who, String callerPackage,
13192             String[] packageNames, boolean suspended) {
13193         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
13194         ActiveAdmin admin;
13195 
13196         if (isUnicornFlagEnabled()) {
13197             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
13198                     who,
13199                     MANAGE_DEVICE_POLICY_PACKAGE_STATE,
13200                     caller.getPackageName(),
13201                     caller.getUserId());
13202             admin = enforcingAdmin.getActiveAdmin();
13203         } else {
13204             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13205                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
13206                     || (caller.hasPackage() && isCallerDelegate(caller,
13207                     DELEGATION_PACKAGE_ACCESS)));
13208             synchronized (getLockObject()) {
13209                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
13210             }
13211         }
13212         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PACKAGES_SUSPENDED);
13213 
13214         // Must remove the exempt apps from the input before calling PM, then add them back to
13215         // the array returned to the caller
13216         Set<String> exemptApps = new HashSet<>();
13217         packageNames = populateNonExemptAndExemptFromPolicyApps(packageNames, exemptApps);
13218 
13219         String[] nonSuspendedPackages = null;
13220         synchronized (getLockObject()) {
13221             long id = mInjector.binderClearCallingIdentity();
13222             try {
13223                 nonSuspendedPackages = mInjector.getPackageManagerInternal()
13224                         .setPackagesSuspendedByAdmin(caller.getUserId(), packageNames, suspended);
13225             } finally {
13226                 mInjector.binderRestoreCallingIdentity(id);
13227             }
13228         }
13229         DevicePolicyEventLogger
13230                 .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED)
13231                 .setAdmin(caller.getPackageName())
13232                 .setBoolean(/* isDelegate */ who == null)
13233                 .setStrings(packageNames)
13234                 .write();
13235 
13236         if (nonSuspendedPackages == null) {
13237             Slogf.w(LOG_TAG, "PM failed to suspend packages (%s)", Arrays.toString(packageNames));
13238             return packageNames;
13239         }
13240 
13241         ArraySet<String> changed = new ArraySet<>(packageNames);
13242         if (suspended) {
13243             // Only save those packages that are actually suspended. If a package is exempt or is
13244             // unsuspendable, it is skipped.
13245             changed.removeAll(List.of(nonSuspendedPackages));
13246         } else {
13247             // If an admin tries to unsuspend a package that is either exempt or is not
13248             // suspendable, drop it from the stored list assuming it must be already unsuspended.
13249             changed.addAll(exemptApps);
13250         }
13251 
13252         synchronized (getLockObject()) {
13253             ArraySet<String> current = new ArraySet<>(admin.suspendedPackages);
13254             if (suspended) {
13255                 current.addAll(changed);
13256             } else {
13257                 current.removeAll(changed);
13258             }
13259             admin.suspendedPackages = current.isEmpty() ? null : new ArrayList<>(current);
13260             saveSettingsLocked(caller.getUserId());
13261         }
13262 
13263         if (exemptApps.isEmpty()) {
13264             return nonSuspendedPackages;
13265         }
13266 
13267         String[] result = buildNonSuspendedPackagesUnionArray(nonSuspendedPackages, exemptApps);
13268         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Returning %s", Arrays.toString(result));
13269         return result;
13270     }
13271 
13272     @Override
13273     public String[] setPackagesSuspended(ComponentName who, String callerPackage,
13274             String[] packageNames, boolean suspended) {
13275         if (!Flags.unmanagedModeMigration()) {
13276             return setPackagesSuspendedPreCoexistence(who, callerPackage, packageNames, suspended);
13277         }
13278 
13279         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
13280 
13281         EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
13282                 who,
13283                 MANAGE_DEVICE_POLICY_PACKAGE_STATE,
13284                 caller.getPackageName(),
13285                 caller.getUserId());
13286         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PACKAGES_SUSPENDED);
13287 
13288         Set<String> packages = new ArraySet<>(packageNames);
13289         Set<String> suspendedPackagesBefore = mDevicePolicyEngine.getResolvedPolicy(
13290                 PolicyDefinition.PACKAGES_SUSPENDED, caller.getUserId());
13291 
13292         Set<String> currentPackages = mDevicePolicyEngine.getLocalPolicySetByAdmin(
13293                 PolicyDefinition.PACKAGES_SUSPENDED,
13294                 enforcingAdmin,
13295                 caller.getUserId());
13296         if (currentPackages == null) currentPackages = new ArraySet<>();
13297         if (suspended) {
13298             currentPackages.addAll(packages);
13299         } else {
13300             currentPackages.removeAll(packages);
13301         }
13302         if (currentPackages.isEmpty()) {
13303             mDevicePolicyEngine.removeLocalPolicy(
13304                     PolicyDefinition.PACKAGES_SUSPENDED,
13305                     enforcingAdmin,
13306                     caller.getUserId());
13307         } else {
13308             mDevicePolicyEngine.setLocalPolicy(
13309                     PolicyDefinition.PACKAGES_SUSPENDED,
13310                     enforcingAdmin,
13311                     new PackageSetPolicyValue(currentPackages),
13312                     caller.getUserId());
13313         }
13314 
13315         Set<String> suspendedPackagesAfter = mDevicePolicyEngine.getResolvedPolicy(
13316                 PolicyDefinition.PACKAGES_SUSPENDED, caller.getUserId());
13317 
13318         PackageSuspender suspender = new PackageSuspender(
13319                 suspendedPackagesBefore, suspendedPackagesAfter,
13320                 listPolicyExemptAppsUnchecked(mContext),
13321                 mInjector.getPackageManagerInternal(), caller.getUserId());
13322 
13323         String[] result;
13324         synchronized (getLockObject()) {
13325             long id = mInjector.binderClearCallingIdentity();
13326             try {
13327                 result = suspended ? suspender.suspend(packages) : suspender.unsuspend(packages);
13328             } finally {
13329                 mInjector.binderRestoreCallingIdentity(id);
13330             }
13331         }
13332 
13333         DevicePolicyEventLogger
13334                 .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED)
13335                 .setAdmin(caller.getPackageName())
13336                 .setBoolean(/* isDelegate */ who == null)
13337                 .setStrings(packageNames)
13338                 .write();
13339 
13340         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Returning %s", Arrays.toString(result));
13341         return result;
13342     }
13343 
13344     /**
13345      * Returns an array containing the union of the given non-suspended packages and
13346      * exempt apps. Assumes both parameters are non-null and non-empty.
13347      */
13348     private String[] buildNonSuspendedPackagesUnionArray(String[] nonSuspendedPackages,
13349             Set<String> exemptApps) {
13350         String[] result = new String[nonSuspendedPackages.length + exemptApps.size()];
13351         int index = 0;
13352         for (String app : nonSuspendedPackages) {
13353             result[index++] = app;
13354         }
13355         for (String app : exemptApps) {
13356             result[index++] = app;
13357         }
13358         return result;
13359     }
13360 
13361     @Override
13362     public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
13363         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
13364 
13365         if (Flags.unmanagedModeMigration()) {
13366             enforcePermission(
13367                     MANAGE_DEVICE_POLICY_PACKAGE_STATE,
13368                     caller.getPackageName(),
13369                     caller.getUserId());
13370         } else {
13371             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13372                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
13373                     || (caller.hasPackage() && isCallerDelegate(caller,
13374                     DELEGATION_PACKAGE_ACCESS)));
13375         }
13376 
13377         synchronized (getLockObject()) {
13378             long id = mInjector.binderClearCallingIdentity();
13379             try {
13380                 return mIPackageManager.isPackageSuspendedForUser(packageName, caller.getUserId());
13381             } catch (RemoteException re) {
13382                 // Shouldn't happen.
13383                 Slogf.e(LOG_TAG, "Failed talking to the package manager", re);
13384             } finally {
13385                 mInjector.binderRestoreCallingIdentity(id);
13386             }
13387             return false;
13388         }
13389     }
13390 
13391     @Override
13392     public List<String> listPolicyExemptApps() {
13393         CallerIdentity caller = getCallerIdentity();
13394         Preconditions.checkCallAuthorization(
13395                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)
13396                         || isDefaultDeviceOwner(caller) || isProfileOwner(caller));
13397 
13398         return listPolicyExemptAppsUnchecked(mContext);
13399     }
13400 
13401     private static List<String> listPolicyExemptAppsUnchecked(Context context) {
13402         // TODO(b/181238156): decide whether it should only list the apps set by the resources,
13403         // or also the "critical" apps defined by PersonalAppsSuspensionHelper (like SMS app).
13404         // If it's the latter, refactor PersonalAppsSuspensionHelper so it (or a superclass) takes
13405         // the resources on constructor.
13406         String[] core = context.getResources().getStringArray(R.array.policy_exempt_apps);
13407         String[] vendor = context.getResources().getStringArray(R.array.vendor_policy_exempt_apps);
13408 
13409         int size = core.length + vendor.length;
13410         Set<String> apps = new ArraySet<>(size);
13411         for (String app : core) {
13412             apps.add(app);
13413         }
13414         for (String app : vendor) {
13415             apps.add(app);
13416         }
13417 
13418         return new ArrayList<>(apps);
13419     }
13420 
13421     @Override
13422     public void setUserRestriction(
13423             ComponentName who, String callerPackage, String key, boolean enabledFromThisOwner,
13424             boolean parent) {
13425 
13426         CallerIdentity caller = getCallerIdentity(who, callerPackage);
13427         int userId = caller.getUserId();
13428         int affectedUserId = parent ? getProfileParentId(userId) : userId;
13429 
13430         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
13431 
13432         if (!isDeviceOwner(caller) && !isProfileOwner(caller)) {
13433             EnforcingAdmin admin = enforcePermissionForUserRestriction(
13434                     who,
13435                     key,
13436                     caller.getPackageName(),
13437                     affectedUserId);
13438             if (!mInjector.isChangeEnabled(ENABLE_COEXISTENCE_CHANGE, callerPackage, userId)) {
13439                 throw new IllegalStateException("Calling package is not targeting Android U.");
13440             }
13441             if (!UserRestrictionsUtils.isValidRestriction(key)) {
13442                 throw new IllegalArgumentException("Invalid restriction key: " + key);
13443             }
13444             PolicyDefinition<Boolean> policyDefinition =
13445                     PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
13446             if (enabledFromThisOwner) {
13447                 setLocalUserRestrictionInternal(
13448                         admin, key, /* enabled= */ true, affectedUserId);
13449             } else {
13450                 // Remove any local and global policy that was set by the admin
13451                 if (!policyDefinition.isLocalOnlyPolicy()) {
13452                     setGlobalUserRestrictionInternal(admin, key, /* enabled= */ false);
13453                 }
13454                 if (!policyDefinition.isGlobalOnlyPolicy()) {
13455                     setLocalUserRestrictionInternal(admin, key, /* enabled= */ false,
13456                             userId);
13457 
13458                     int parentUserId = getProfileParentId(userId);
13459                     if (parentUserId != userId) {
13460                         setLocalUserRestrictionInternal(
13461                                 admin, key, /* enabled= */ false, parentUserId);
13462                     }
13463                 }
13464             }
13465         } else {
13466             if (!UserRestrictionsUtils.isValidRestriction(key)) {
13467                 return;
13468             }
13469             Objects.requireNonNull(who, "ComponentName is null");
13470             EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
13471             checkAdminCanSetRestriction(caller, parent, key);
13472             setBackwardCompatibleUserRestriction(
13473                     caller, admin, key, enabledFromThisOwner, parent);
13474         }
13475         logUserRestrictionCall(key, enabledFromThisOwner, parent, caller);
13476     }
13477 
13478     private void checkAdminCanSetRestriction(CallerIdentity caller, boolean parent, String key) {
13479         boolean isProfileOwnerOfOrganizationOwnedDevice =
13480                 isProfileOwnerOfOrganizationOwnedDevice(caller);
13481         if (parent) {
13482             Preconditions.checkCallAuthorization(
13483                     isProfileOwnerOfOrganizationOwnedDevice);
13484         } else {
13485             Preconditions.checkCallAuthorization(
13486                     isDeviceOwner(caller) || isProfileOwner(caller));
13487         }
13488         synchronized (getLockObject()) {
13489             if (isDefaultDeviceOwner(caller)) {
13490                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
13491                     throw new SecurityException("Device owner cannot set user restriction "
13492                             + key);
13493                 }
13494                 Preconditions.checkArgument(!parent,
13495                         "Cannot use the parent instance in Device Owner mode");
13496             } else if (isFinancedDeviceOwner(caller)) {
13497                 if (!UserRestrictionsUtils.canFinancedDeviceOwnerChange(key)) {
13498                     throw new SecurityException("Cannot set user restriction " + key
13499                             + " when managing a financed device");
13500                 }
13501                 Preconditions.checkArgument(!parent,
13502                         "Cannot use the parent instance in Financed Device Owner"
13503                                 + " mode");
13504             } else {
13505                 boolean profileOwnerCanChangeOnItself = !parent
13506                         && UserRestrictionsUtils.canProfileOwnerChange(
13507                             key,
13508                             caller.getUserId() == getMainUserId(),
13509                             isProfileOwnerOfOrganizationOwnedDevice);
13510                 boolean orgOwnedProfileOwnerCanChangeGlobally = parent
13511                         && isProfileOwnerOfOrganizationOwnedDevice
13512                         && UserRestrictionsUtils
13513                             .canParentOfProfileOwnerOfOrganizationOwnedDeviceChange(key);
13514 
13515                 if (!profileOwnerCanChangeOnItself && !orgOwnedProfileOwnerCanChangeGlobally) {
13516                     throw new SecurityException("Profile owner cannot set user restriction "
13517                             + key);
13518                 }
13519             }
13520         }
13521     }
13522     private void setBackwardCompatibleUserRestriction(
13523             CallerIdentity caller, EnforcingAdmin admin, String key, boolean enabled,
13524             boolean parent) {
13525         synchronized (getLockObject()) {
13526 
13527             int ownerType;
13528             if (isDeviceOwner(caller)) {
13529                 ownerType = OWNER_TYPE_DEVICE_OWNER;
13530             } else if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
13531                 ownerType = OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;
13532             } else if (isProfileOwner(caller)) {
13533                 ownerType = OWNER_TYPE_PROFILE_OWNER;
13534             } else {
13535                 throw new IllegalStateException("Non-DO/Non-PO cannot set restriction " + key
13536                         + " while targetSdkVersion is less than UPSIDE_DOWN_CAKE");
13537             }
13538             setBackwardCompatibleUserRestrictionLocked(ownerType, admin, caller.getUserId(), key,
13539                     enabled, parent);
13540         }
13541     }
13542 
13543     private void setBackwardCompatibleUserRestrictionLocked(
13544             int ownerType, EnforcingAdmin admin, int userId, String key, boolean enabled,
13545             boolean parent) {
13546         if (ownerType == OWNER_TYPE_DEVICE_OWNER) {
13547             if (UserRestrictionsUtils.isGlobal(OWNER_TYPE_DEVICE_OWNER, key)) {
13548                 setGlobalUserRestrictionInternal(admin, key, enabled);
13549             } else {
13550                 setLocalUserRestrictionInternal(admin, key, enabled, userId);
13551             }
13552         } else if (ownerType == OWNER_TYPE_PROFILE_OWNER
13553                 || ownerType == OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE) {
13554             if (UserRestrictionsUtils.isGlobal(OWNER_TYPE_PROFILE_OWNER, key)
13555                     || (parent && ownerType == OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE
13556                     && UserRestrictionsUtils.isGlobal(
13557                     OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE, key))) {
13558                 setGlobalUserRestrictionInternal(admin, key, enabled);
13559             } else {
13560                 int affectedUserId = parent
13561                         ? getProfileParentId(userId) : userId;
13562                 setLocalUserRestrictionInternal(admin, key, enabled, affectedUserId);
13563             }
13564         } else {
13565             throw new IllegalStateException("Non-DO/Non-PO cannot set restriction " + key
13566                     + " while targetSdkVersion is less than UPSIDE_DOWN_CAKE");
13567         }
13568     }
13569 
13570     @Override
13571     public void setUserRestrictionGlobally(String callerPackage, String key) {
13572         final CallerIdentity caller = getCallerIdentity(callerPackage);
13573 
13574         EnforcingAdmin admin = enforcePermissionForUserRestriction(
13575                 /* who= */ null,
13576                 key,
13577                 caller.getPackageName(),
13578                 UserHandle.USER_ALL
13579         );
13580 
13581         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
13582 
13583         if (isDeviceOwner(caller) || isProfileOwner(caller)) {
13584             throw new SecurityException("Admins are not allowed to call this API.");
13585         }
13586         if (!mInjector.isChangeEnabled(
13587                 ENABLE_COEXISTENCE_CHANGE, callerPackage, caller.getUserId())) {
13588             throw new IllegalStateException("Calling package is not targeting Android U.");
13589         }
13590         if (!UserRestrictionsUtils.isValidRestriction(key)) {
13591             throw new IllegalArgumentException("Invalid restriction key: " + key);
13592         }
13593 
13594         setGlobalUserRestrictionInternal(admin, key, /* enabled= */ true);
13595 
13596         logUserRestrictionCall(key, /* enabled= */ true, /* parent= */ false, caller);
13597     }
13598     private void setLocalUserRestrictionInternal(
13599             EnforcingAdmin admin, String key, boolean enabled, int userId) {
13600         PolicyDefinition<Boolean> policyDefinition =
13601                 PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
13602         if (enabled) {
13603             mDevicePolicyEngine.setLocalPolicy(
13604                     policyDefinition,
13605                     admin,
13606                     new BooleanPolicyValue(true),
13607                     userId);
13608         } else {
13609             mDevicePolicyEngine.removeLocalPolicy(
13610                     policyDefinition,
13611                     admin,
13612                     userId);
13613         }
13614     }
13615     private void setGlobalUserRestrictionInternal(
13616             EnforcingAdmin admin, String key, boolean enabled) {
13617         PolicyDefinition<Boolean> policyDefinition =
13618                 PolicyDefinition.getPolicyDefinitionForUserRestriction(key);
13619         if (enabled) {
13620             mDevicePolicyEngine.setGlobalPolicy(
13621                     PolicyDefinition.getPolicyDefinitionForUserRestriction(key),
13622                     admin,
13623                     new BooleanPolicyValue(true));
13624         } else {
13625             mDevicePolicyEngine.removeGlobalPolicy(
13626                     policyDefinition,
13627                     admin);
13628         }
13629     }
13630 
13631     private void logUserRestrictionCall(
13632             String key, boolean enabled, boolean parent, CallerIdentity caller) {
13633         final int eventId = enabled
13634                 ? DevicePolicyEnums.ADD_USER_RESTRICTION
13635                 : DevicePolicyEnums.REMOVE_USER_RESTRICTION;
13636         DevicePolicyEventLogger
13637                 .createEvent(eventId)
13638                 .setAdmin(caller.getComponentName())
13639                 .setStrings(key, parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
13640                 .write();
13641         if (SecurityLog.isLoggingEnabled()) {
13642             final int eventTag = enabled
13643                     ? SecurityLog.TAG_USER_RESTRICTION_ADDED
13644                     : SecurityLog.TAG_USER_RESTRICTION_REMOVED;
13645             SecurityLog.writeEvent(eventTag, caller.getPackageName(), caller.getUserId(), key);
13646         }
13647 
13648         Slogf.i(LOG_TAG, "Changing user restriction %s to: %b caller: %s",
13649                 key, enabled, caller.toString());
13650     }
13651 
13652     @Override
13653     public Bundle getUserRestrictions(ComponentName who, String callerPackage, boolean parent) {
13654         if (!mHasFeature) {
13655             return null;
13656         }
13657         CallerIdentity caller = getCallerIdentity(who, callerPackage);
13658         int targetUserId = parent
13659                 ? getProfileParentId(caller.getUserId()) : caller.getUserId();
13660         EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
13661         if (isDeviceOwner(caller) || isProfileOwner(caller)) {
13662             Objects.requireNonNull(who, "ComponentName is null");
13663             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
13664                     || isFinancedDeviceOwner(caller)
13665                     || isProfileOwner(caller)
13666                     || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)));
13667 
13668             Bundle restrictions = getUserRestrictionsFromPolicyEngine(admin, targetUserId);
13669             // Add global restrictions set by the admin as well.
13670             restrictions.putAll(
13671                     getUserRestrictionsFromPolicyEngine(admin, UserHandle.USER_ALL));
13672             return restrictions;
13673         } else {
13674             if (!mInjector.isChangeEnabled(
13675                     ENABLE_COEXISTENCE_CHANGE, callerPackage, caller.getUserId())) {
13676                 throw new IllegalStateException("Calling package is not targeting Android U.");
13677             }
13678             return getUserRestrictionsFromPolicyEngine(admin, targetUserId);
13679         }
13680     }
13681 
13682     // Map of user restriction to permission.
13683     private static final HashMap<String, String[]> USER_RESTRICTION_PERMISSIONS = new HashMap<>();
13684     {
13685         USER_RESTRICTION_PERMISSIONS.put(
13686                 UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, new String[]{MANAGE_DEVICE_POLICY_PROFILES});
13687         USER_RESTRICTION_PERMISSIONS.put(
13688                 UserManager.DISALLOW_ADD_CLONE_PROFILE, new String[]{MANAGE_DEVICE_POLICY_PROFILES});
13689         USER_RESTRICTION_PERMISSIONS.put(
13690                 UserManager.DISALLOW_ADD_PRIVATE_PROFILE, new String[]{MANAGE_DEVICE_POLICY_PROFILES});
13691         USER_RESTRICTION_PERMISSIONS.put(
13692                 UserManager.DISALLOW_ADD_USER, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
13693         USER_RESTRICTION_PERMISSIONS.put(
13694                 UserManager.DISALLOW_ADD_WIFI_CONFIG, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13695         USER_RESTRICTION_PERMISSIONS.put(
13696                 UserManager.DISALLOW_ADJUST_VOLUME, new String[]{MANAGE_DEVICE_POLICY_AUDIO_OUTPUT});
13697         USER_RESTRICTION_PERMISSIONS.put(
13698                 UserManager.DISALLOW_AIRPLANE_MODE, new String[]{MANAGE_DEVICE_POLICY_AIRPLANE_MODE});
13699         USER_RESTRICTION_PERMISSIONS.put(
13700                 UserManager.DISALLOW_AMBIENT_DISPLAY, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
13701         USER_RESTRICTION_PERMISSIONS.put(
13702                 UserManager.DISALLOW_APPS_CONTROL, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
13703         USER_RESTRICTION_PERMISSIONS.put(
13704                 UserManager.DISALLOW_AUTOFILL, new String[]{MANAGE_DEVICE_POLICY_AUTOFILL});
13705         USER_RESTRICTION_PERMISSIONS.put(
13706                 UserManager.DISALLOW_BLUETOOTH, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
13707         USER_RESTRICTION_PERMISSIONS.put(
13708                 UserManager.DISALLOW_BLUETOOTH_SHARING, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
13709         USER_RESTRICTION_PERMISSIONS.put(
13710                 UserManager.DISALLOW_CAMERA, new String[]{MANAGE_DEVICE_POLICY_CAMERA});
13711         USER_RESTRICTION_PERMISSIONS.put(
13712                 UserManager.DISALLOW_CAMERA_TOGGLE, new String[]{MANAGE_DEVICE_POLICY_CAMERA_TOGGLE});
13713         USER_RESTRICTION_PERMISSIONS.put(
13714                 UserManager.DISALLOW_CELLULAR_2G, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13715         USER_RESTRICTION_PERMISSIONS.put(
13716                 UserManager.DISALLOW_CHANGE_WIFI_STATE, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13717         USER_RESTRICTION_PERMISSIONS.put(
13718                 UserManager.DISALLOW_CONFIG_BLUETOOTH, new String[]{MANAGE_DEVICE_POLICY_BLUETOOTH});
13719         USER_RESTRICTION_PERMISSIONS.put(
13720                 UserManager.DISALLOW_CONFIG_BRIGHTNESS, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
13721         USER_RESTRICTION_PERMISSIONS.put(
13722                 UserManager.DISALLOW_CONFIG_CELL_BROADCASTS, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13723         USER_RESTRICTION_PERMISSIONS.put(
13724                 UserManager.DISALLOW_CONFIG_CREDENTIALS, new String[]{MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS});
13725         USER_RESTRICTION_PERMISSIONS.put(
13726                 UserManager.DISALLOW_CONFIG_DATE_TIME, new String[]{MANAGE_DEVICE_POLICY_TIME});
13727         USER_RESTRICTION_PERMISSIONS.put(
13728                 UserManager.DISALLOW_CONFIG_DEFAULT_APPS, new String[]{MANAGE_DEFAULT_APPLICATIONS});
13729         USER_RESTRICTION_PERMISSIONS.put(
13730                 UserManager.DISALLOW_CONFIG_LOCALE, new String[]{MANAGE_DEVICE_POLICY_LOCALE});
13731         USER_RESTRICTION_PERMISSIONS.put(
13732                 UserManager.DISALLOW_CONFIG_LOCATION, new String[]{MANAGE_DEVICE_POLICY_LOCATION});
13733         USER_RESTRICTION_PERMISSIONS.put(
13734                 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13735         USER_RESTRICTION_PERMISSIONS.put(
13736                 UserManager.DISALLOW_CONFIG_PRIVATE_DNS, new String[]{MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS});
13737         USER_RESTRICTION_PERMISSIONS.put(
13738                 UserManager.DISALLOW_CONFIG_SCREEN_TIMEOUT, new String[]{MANAGE_DEVICE_POLICY_DISPLAY});
13739         USER_RESTRICTION_PERMISSIONS.put(
13740                 UserManager.DISALLOW_CONFIG_TETHERING, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13741         USER_RESTRICTION_PERMISSIONS.put(
13742                 UserManager.DISALLOW_CONFIG_VPN, new String[]{MANAGE_DEVICE_POLICY_VPN});
13743         USER_RESTRICTION_PERMISSIONS.put(
13744                 UserManager.DISALLOW_CONFIG_WIFI, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13745         USER_RESTRICTION_PERMISSIONS.put(
13746                 UserManager.DISALLOW_CONTENT_CAPTURE, new String[]{MANAGE_DEVICE_POLICY_SCREEN_CONTENT});
13747         USER_RESTRICTION_PERMISSIONS.put(
13748                 UserManager.DISALLOW_CONTENT_SUGGESTIONS, new String[]{MANAGE_DEVICE_POLICY_SCREEN_CONTENT});
13749         USER_RESTRICTION_PERMISSIONS.put(
13750                 UserManager.DISALLOW_CREATE_WINDOWS, new String[]{MANAGE_DEVICE_POLICY_WINDOWS});
13751         USER_RESTRICTION_PERMISSIONS.put(
13752                 UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE, new String[]{MANAGE_DEVICE_POLICY_PROFILE_INTERACTION});
13753         USER_RESTRICTION_PERMISSIONS.put(
13754                 UserManager.DISALLOW_DATA_ROAMING, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13755         USER_RESTRICTION_PERMISSIONS.put(
13756                 UserManager.DISALLOW_DEBUGGING_FEATURES, new String[]{MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES});
13757         USER_RESTRICTION_PERMISSIONS.put(
13758                 UserManager.DISALLOW_FACTORY_RESET, new String[]{MANAGE_DEVICE_POLICY_FACTORY_RESET});
13759         USER_RESTRICTION_PERMISSIONS.put(
13760                 UserManager.DISALLOW_FUN, new String[]{MANAGE_DEVICE_POLICY_FUN});
13761         USER_RESTRICTION_PERMISSIONS.put(
13762                 UserManager.DISALLOW_INSTALL_APPS, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
13763         USER_RESTRICTION_PERMISSIONS.put(
13764                 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});
13765         USER_RESTRICTION_PERMISSIONS.put(
13766                 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});
13767         USER_RESTRICTION_PERMISSIONS.put(
13768                 UserManager.DISALLOW_MICROPHONE_TOGGLE, new String[]{MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE});
13769         USER_RESTRICTION_PERMISSIONS.put(
13770                 UserManager.DISALLOW_MODIFY_ACCOUNTS, new String[]{MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT});
13771         USER_RESTRICTION_PERMISSIONS.put(
13772                 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, new String[]{MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA});
13773         USER_RESTRICTION_PERMISSIONS.put(
13774                 UserManager.DISALLOW_NETWORK_RESET, new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13775         USER_RESTRICTION_PERMISSIONS.put(
13776                 UserManager.DISALLOW_OUTGOING_BEAM, new String[]{MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION});
13777         USER_RESTRICTION_PERMISSIONS.put(
13778                 UserManager.DISALLOW_OUTGOING_CALLS, new String[]{MANAGE_DEVICE_POLICY_CALLS});
13779         USER_RESTRICTION_PERMISSIONS.put(
13780                 UserManager.DISALLOW_PRINTING, new String[]{MANAGE_DEVICE_POLICY_PRINTING});
13781         USER_RESTRICTION_PERMISSIONS.put(
13782                 UserManager.DISALLOW_REMOVE_USER, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
13783         USER_RESTRICTION_PERMISSIONS.put(
13784                 UserManager.DISALLOW_RUN_IN_BACKGROUND, new String[]{MANAGE_DEVICE_POLICY_RUN_IN_BACKGROUND});
13785         USER_RESTRICTION_PERMISSIONS.put(
13786                 UserManager.DISALLOW_SAFE_BOOT, new String[]{MANAGE_DEVICE_POLICY_SAFE_BOOT});
13787         USER_RESTRICTION_PERMISSIONS.put(
13788                 UserManager.DISALLOW_SET_USER_ICON, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
13789         USER_RESTRICTION_PERMISSIONS.put(
13790                 UserManager.DISALLOW_SET_WALLPAPER, new String[]{MANAGE_DEVICE_POLICY_WALLPAPER});
13791         USER_RESTRICTION_PERMISSIONS.put(
13792                 UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, new String[]{MANAGE_DEVICE_POLICY_PROFILE_INTERACTION});
13793         USER_RESTRICTION_PERMISSIONS.put(
13794                 UserManager.DISALLOW_SHARE_LOCATION, new String[]{MANAGE_DEVICE_POLICY_LOCATION});
13795         USER_RESTRICTION_PERMISSIONS.put(
13796                 UserManager.DISALLOW_SHARING_ADMIN_CONFIGURED_WIFI, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13797         USER_RESTRICTION_PERMISSIONS.put(
13798                 UserManager.DISALLOW_SMS, new String[]{MANAGE_DEVICE_POLICY_SMS});
13799         USER_RESTRICTION_PERMISSIONS.put(
13800                 UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS, new String[]{MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS});
13801         if (com.android.net.thread.platform.flags.Flags.threadUserRestrictionEnabled()) {
13802             USER_RESTRICTION_PERMISSIONS.put(
13803                     UserManager.DISALLOW_THREAD_NETWORK,
13804                     new String[]{MANAGE_DEVICE_POLICY_THREAD_NETWORK});
13805         }
13806         if (Flags.assistContentUserRestrictionEnabled()) {
13807             USER_RESTRICTION_PERMISSIONS.put(
13808                     UserManager.DISALLOW_ASSIST_CONTENT,
13809                     new String[]{MANAGE_DEVICE_POLICY_ASSIST_CONTENT});
13810         }
13811         USER_RESTRICTION_PERMISSIONS.put(
13812                 UserManager.DISALLOW_ULTRA_WIDEBAND_RADIO, new String[]{MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION});
13813         USER_RESTRICTION_PERMISSIONS.put(
13814                 UserManager.DISALLOW_UNIFIED_PASSWORD, new String[]{MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS});
13815         USER_RESTRICTION_PERMISSIONS.put(
13816                 UserManager.DISALLOW_UNINSTALL_APPS, new String[]{MANAGE_DEVICE_POLICY_APPS_CONTROL});
13817         USER_RESTRICTION_PERMISSIONS.put(
13818                 UserManager.DISALLOW_UNMUTE_DEVICE, new String[]{MANAGE_DEVICE_POLICY_AUDIO_OUTPUT});
13819         USER_RESTRICTION_PERMISSIONS.put(
13820                 UserManager.DISALLOW_UNMUTE_MICROPHONE, new String[]{MANAGE_DEVICE_POLICY_MICROPHONE});
13821         USER_RESTRICTION_PERMISSIONS.put(
13822                 UserManager.DISALLOW_USB_FILE_TRANSFER, new String[]{MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER});
13823         USER_RESTRICTION_PERMISSIONS.put(
13824                 UserManager.DISALLOW_USER_SWITCH, new String[]{MANAGE_DEVICE_POLICY_MODIFY_USERS});
13825         USER_RESTRICTION_PERMISSIONS.put(
13826                 UserManager.DISALLOW_WIFI_DIRECT, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13827         USER_RESTRICTION_PERMISSIONS.put(
13828                 UserManager.DISALLOW_WIFI_TETHERING, new String[]{MANAGE_DEVICE_POLICY_WIFI});
13829         USER_RESTRICTION_PERMISSIONS.put(
13830                 UserManager.ENSURE_VERIFY_APPS, new String[]{MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES});
13831         USER_RESTRICTION_PERMISSIONS.put(
13832                 UserManager.DISALLOW_SIM_GLOBALLY,
13833                 new String[]{MANAGE_DEVICE_POLICY_MOBILE_NETWORK});
13834 
13835         // Restrictions not allowed to be set by admins.
13836         USER_RESTRICTION_PERMISSIONS.put(
13837                 UserManager.DISALLOW_RECORD_AUDIO, null);
13838         USER_RESTRICTION_PERMISSIONS.put(
13839                 UserManager.DISALLOW_WALLPAPER, null);
13840     }
13841 
enforcePermissionForUserRestriction(ComponentName who, String userRestriction, String callerPackageName, int userId)13842     private EnforcingAdmin enforcePermissionForUserRestriction(ComponentName who,
13843             String userRestriction, String callerPackageName, int userId) {
13844         String[] permissions = USER_RESTRICTION_PERMISSIONS.get(userRestriction);
13845         if (permissions.length > 0) {
13846             try {
13847                 return enforcePermissionsAndGetEnforcingAdmin(who, permissions, callerPackageName,
13848                         userId);
13849             } catch (SecurityException e) {
13850                 throw new SecurityException("Caller does not hold the required permission for this "
13851                         + "user restriction: " + userRestriction + ".\n" + e.getMessage());
13852             }
13853          }
13854         throw new SecurityException("Admins are not permitted to set User Restriction: "
13855                 + userRestriction);
13856     }
13857 
13858     @Override
getUserRestrictionsGlobally(String callerPackage)13859     public Bundle getUserRestrictionsGlobally(String callerPackage) {
13860         if (!mHasFeature) {
13861             return null;
13862         }
13863         final CallerIdentity caller = getCallerIdentity(callerPackage);
13864         EnforcingAdmin admin = getEnforcingAdminForCaller(/*who=*/ null, caller.getPackageName());
13865 
13866         return getUserRestrictionsFromPolicyEngine(admin,
13867                 UserHandle.USER_ALL);
13868     }
13869 
13870     /**
13871      * Returns user restrictions set by the given admin for the provided {@code userId}.
13872      *
13873      * <p>Pass in {@link UserHandle#USER_ALL} for {@code userId} to get global restrictions set by
13874      * the admin
13875      */
getUserRestrictionsFromPolicyEngine(EnforcingAdmin admin, int userId)13876     private Bundle getUserRestrictionsFromPolicyEngine(EnforcingAdmin admin, int userId) {
13877         Set<UserRestrictionPolicyKey> restrictionKeys =
13878                 mDevicePolicyEngine.getUserRestrictionPolicyKeysForAdmin(
13879                         admin,
13880                         userId);
13881         Bundle restrictions = new Bundle();
13882         for (UserRestrictionPolicyKey key : restrictionKeys) {
13883             restrictions.putBoolean(key.getRestriction(), true);
13884         }
13885         return restrictions;
13886     }
13887 
13888     @Override
setApplicationHidden(ComponentName who, String callerPackage, String packageName, boolean hidden, boolean parent)13889     public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
13890             boolean hidden, boolean parent) {
13891         CallerIdentity caller = getCallerIdentity(who, callerPackage);
13892         final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
13893         enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
13894 
13895         List<String> exemptApps = listPolicyExemptAppsUnchecked(mContext);
13896         if (exemptApps.contains(packageName)) {
13897             Slogf.d(LOG_TAG, "setApplicationHidden(): ignoring %s as it's on policy-exempt list",
13898                     packageName);
13899             return false;
13900         }
13901 
13902         boolean result;
13903         synchronized (getLockObject()) {
13904             if (parent) {
13905                 // Ensure the package provided is a system package, this is to ensure that this
13906                 // API cannot be used to leak if certain non-system package exists in the person
13907                 // profile.
13908                 mInjector.binderWithCleanCallingIdentity(() ->
13909                         enforcePackageIsSystemPackage(packageName, userId));
13910             }
13911             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_HIDDEN);
13912 
13913             if (VERBOSE_LOG) {
13914                 Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)",
13915                         packageName, hidden, userId);
13916             }
13917             EnforcingAdmin admin = getEnforcingAdminForCaller(who, callerPackage);
13918             mDevicePolicyEngine.setLocalPolicy(
13919                     PolicyDefinition.APPLICATION_HIDDEN(packageName),
13920                     admin,
13921                     new BooleanPolicyValue(hidden),
13922                     userId);
13923             result = mInjector.binderWithCleanCallingIdentity(() -> {
13924                 try {
13925                     // This is a best effort to continue returning the same value that was
13926                     // returned before the policy engine migration.
13927                     return mInjector.getIPackageManager().getPackageInfo(
13928                             packageName, MATCH_UNINSTALLED_PACKAGES, userId) != null
13929                             && (mIPackageManager.getApplicationHiddenSettingAsUser(
13930                                     packageName, userId) == hidden);
13931                 } catch (RemoteException e) {
13932                     return false;
13933                 }
13934             });
13935         }
13936         DevicePolicyEventLogger
13937                 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN)
13938                 .setAdmin(caller.getPackageName())
13939                 .setBoolean(/* isDelegate */ isCallerDelegate(caller))
13940                 .setStrings(packageName, hidden ? "hidden" : "not_hidden",
13941                         parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
13942                 .write();
13943         return result;
13944     }
13945 
13946     @Override
isApplicationHidden(ComponentName who, String callerPackage, String packageName, boolean parent)13947     public boolean isApplicationHidden(ComponentName who, String callerPackage,
13948             String packageName, boolean parent) {
13949         CallerIdentity caller = getCallerIdentity(who, callerPackage);
13950         int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
13951         // TODO: Also support DELEGATION_PACKAGE_ACCESS
13952         enforcePermission(MANAGE_DEVICE_POLICY_PACKAGE_STATE, caller.getPackageName(), userId);
13953 
13954         synchronized (getLockObject()) {
13955             if (parent) {
13956                 // Ensure the package provided is a system package.
13957                 mInjector.binderWithCleanCallingIdentity(() ->
13958                         enforcePackageIsSystemPackage(packageName, userId));
13959             }
13960 
13961             return mInjector.binderWithCleanCallingIdentity(
13962                     () -> mIPackageManager.getApplicationHiddenSettingAsUser(packageName, userId));
13963         }
13964     }
13965 
enforcePackageIsSystemPackage(String packageName, int userId)13966     private void enforcePackageIsSystemPackage(String packageName, int userId)
13967             throws RemoteException {
13968         boolean isSystem;
13969         try {
13970             isSystem = isSystemApp(mIPackageManager, packageName, userId);
13971         } catch (IllegalArgumentException e) {
13972             isSystem = false;
13973         }
13974         if (!isSystem) {
13975             throw new IllegalArgumentException("The provided package is not a system package");
13976         }
13977     }
13978 
13979     @Override
enableSystemApp(ComponentName who, String callerPackage, String packageName)13980     public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
13981         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
13982         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13983                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
13984                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP)));
13985 
13986         final boolean isDemo = isCurrentUserDemo();
13987         int userId = caller.getUserId();
13988         long id = mInjector.binderClearCallingIdentity();
13989         try {
13990             if (VERBOSE_LOG) {
13991                 Slogf.v(LOG_TAG, "installing " + packageName + " for " + userId);
13992             }
13993 
13994             Preconditions.checkArgument(isDemo || isSystemApp(mIPackageManager, packageName,
13995                     getProfileParentId(userId)), "Only system apps can be enabled this way");
13996 
13997             // Install the app.
13998             mIPackageManager.installExistingPackageAsUser(packageName, userId,
13999                     PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
14000                     PackageManager.INSTALL_REASON_POLICY, null);
14001             if (isDemo) {
14002                 // Ensure the app is also ENABLED for demo users.
14003                 mIPackageManager.setApplicationEnabledSetting(packageName,
14004                         PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
14005                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
14006             }
14007         } catch (RemoteException re) {
14008             // shouldn't happen
14009             Slogf.wtf(LOG_TAG, "Failed to install " + packageName, re);
14010         } finally {
14011             mInjector.binderRestoreCallingIdentity(id);
14012         }
14013         DevicePolicyEventLogger
14014                 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP)
14015                 .setAdmin(caller.getPackageName())
14016                 .setBoolean(/* isDelegate */ who == null)
14017                 .setStrings(packageName)
14018                 .write();
14019     }
14020 
14021     @Override
enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent)14022     public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
14023         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
14024         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
14025                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
14026                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP)));
14027 
14028         int numberOfAppsInstalled = 0;
14029         long id = mInjector.binderClearCallingIdentity();
14030         try {
14031             final int parentUserId = getProfileParentId(caller.getUserId());
14032             List<ResolveInfo> activitiesToEnable = mIPackageManager
14033                     .queryIntentActivities(intent,
14034                             intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14035                             PackageManager.MATCH_DIRECT_BOOT_AWARE
14036                                     | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
14037                             parentUserId)
14038                     .getList();
14039 
14040             if (VERBOSE_LOG) {
14041                 Slogf.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
14042             }
14043             if (activitiesToEnable != null) {
14044                 for (ResolveInfo info : activitiesToEnable) {
14045                     if (info.activityInfo != null) {
14046                         String packageName = info.activityInfo.packageName;
14047                         if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
14048                             numberOfAppsInstalled++;
14049                             mIPackageManager.installExistingPackageAsUser(packageName,
14050                                     caller.getUserId(),
14051                                     PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
14052                                     PackageManager.INSTALL_REASON_POLICY, null);
14053                         } else {
14054                             Slogf.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
14055                                     + " system app");
14056                         }
14057                     }
14058                 }
14059             }
14060         } catch (RemoteException e) {
14061             // shouldn't happen
14062             Slogf.wtf(LOG_TAG, "Failed to resolve intent for: " + intent, e);
14063             return 0;
14064         } finally {
14065             mInjector.binderRestoreCallingIdentity(id);
14066         }
14067         DevicePolicyEventLogger
14068                 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP_WITH_INTENT)
14069                 .setAdmin(caller.getPackageName())
14070                 .setBoolean(/* isDelegate */ who == null)
14071                 .setStrings(intent.getAction())
14072                 .write();
14073         return numberOfAppsInstalled;
14074     }
14075 
isSystemApp(IPackageManager pm, String packageName, int userId)14076     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
14077             throws RemoteException {
14078         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
14079                 userId);
14080         if (appInfo == null) {
14081             throw new IllegalArgumentException("The application " + packageName +
14082                     " is not present on this device");
14083         }
14084         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14085     }
14086 
14087     @Override
installExistingPackage(ComponentName who, String callerPackage, String packageName)14088     public boolean installExistingPackage(ComponentName who, String callerPackage,
14089             String packageName) {
14090         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
14091         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
14092                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
14093                 || (caller.hasPackage()
14094                 && isCallerDelegate(caller, DELEGATION_INSTALL_EXISTING_PACKAGE)));
14095 
14096         boolean result;
14097         synchronized (getLockObject()) {
14098             Preconditions.checkCallAuthorization(
14099                     isUserAffiliatedWithDeviceLocked(caller.getUserId()),
14100                             "Admin %s is neither the device owner or "
14101                                     + "affiliated user's profile owner.", who);
14102             final long id = mInjector.binderClearCallingIdentity();
14103             try {
14104                 if (VERBOSE_LOG) {
14105                     Slogf.v(LOG_TAG, "installing " + packageName + " for " + caller.getUserId());
14106                 }
14107 
14108                 // Install the package.
14109                 result = mIPackageManager.installExistingPackageAsUser(packageName,
14110                         caller.getUserId(),
14111                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
14112                         PackageManager.INSTALL_REASON_POLICY, null)
14113                         == PackageManager.INSTALL_SUCCEEDED;
14114             } catch (RemoteException re) {
14115                 // shouldn't happen
14116                 Slogf.wtf(LOG_TAG, "Error installing package", re);
14117                 return false;
14118             } finally {
14119                 mInjector.binderRestoreCallingIdentity(id);
14120             }
14121         }
14122         if (result) {
14123             DevicePolicyEventLogger
14124                     .createEvent(DevicePolicyEnums.INSTALL_EXISTING_PACKAGE)
14125                     .setAdmin(caller.getPackageName())
14126                     .setBoolean(/* isDelegate */ who == null)
14127                     .setStrings(packageName)
14128                     .write();
14129         }
14130         return result;
14131     }
14132 
14133     @Override
setAccountManagementDisabled(ComponentName who, String callerPackageName, String accountType, boolean disabled, boolean parent)14134     public void setAccountManagementDisabled(ComponentName who, String callerPackageName,
14135             String accountType, boolean disabled, boolean parent) {
14136         if (!mHasFeature) {
14137             return;
14138         }
14139 
14140         if (!Flags.devicePolicySizeTrackingInternalBugFixEnabled()) {
14141             PolicySizeVerifier.enforceMaxStringLength(accountType, "account type");
14142         }
14143 
14144         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
14145         synchronized (getLockObject()) {
14146             int affectedUser = getAffectedUser(parent);
14147             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
14148                     who,
14149                     MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
14150                     caller.getPackageName(),
14151                     affectedUser
14152             );
14153             if (disabled) {
14154                 mDevicePolicyEngine.setLocalPolicy(
14155                         PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
14156                         enforcingAdmin,
14157                         new BooleanPolicyValue(disabled),
14158                         affectedUser);
14159             } else {
14160                 mDevicePolicyEngine.removeLocalPolicy(
14161                         PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
14162                         enforcingAdmin,
14163                         affectedUser);
14164             }
14165         }
14166     }
14167 
14168     @Override
getAccountTypesWithManagementDisabled(String callerPackageName)14169     public String[] getAccountTypesWithManagementDisabled(String callerPackageName) {
14170         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId(),
14171                 callerPackageName, false);
14172     }
14173 
14174     @Override
getAccountTypesWithManagementDisabledAsUser(int userId, String callerPackageName, boolean parent)14175     public String[] getAccountTypesWithManagementDisabledAsUser(int userId,
14176             String callerPackageName, boolean parent) {
14177         if (!mHasFeature) {
14178             return null;
14179         }
14180         CallerIdentity caller = getCallerIdentity(callerPackageName);
14181         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14182         final ArraySet<String> resultSet = new ArraySet<>();
14183         int affectedUser = parent ? getProfileParentId(userId) : userId;
14184         if (!hasPermission(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
14185                 callerPackageName, affectedUser)
14186                 && !hasFullCrossUsersPermission(caller, userId)) {
14187             throw new SecurityException("Caller does not have permission to call this on user: "
14188                     + affectedUser);
14189         }
14190         Set<PolicyKey> keys = mDevicePolicyEngine.getLocalPolicyKeysSetByAllAdmins(
14191                 PolicyDefinition.GENERIC_ACCOUNT_MANAGEMENT_DISABLED,
14192                 affectedUser);
14193 
14194         for (PolicyKey key : keys) {
14195             if (!(key instanceof AccountTypePolicyKey)) {
14196                 throw new IllegalStateException("PolicyKey for "
14197                         + "MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT is not of type "
14198                         + "AccountTypePolicyKey");
14199             }
14200             AccountTypePolicyKey parsedKey =
14201                     (AccountTypePolicyKey) key;
14202             String accountType = Objects.requireNonNull(parsedKey.getAccountType());
14203 
14204             Boolean disabled = mDevicePolicyEngine.getResolvedPolicy(
14205                     PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
14206                     affectedUser);
14207             if (disabled != null && disabled) {
14208                 resultSet.add(accountType);
14209             }
14210         }
14211         return resultSet.toArray(new String[resultSet.size()]);
14212     }
14213 
14214     @Override
setUninstallBlocked(ComponentName who, String callerPackage, String packageName, boolean uninstallBlocked)14215     public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
14216             boolean uninstallBlocked) {
14217         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
14218 
14219         EnforcingAdmin enforcingAdmin = enforcePermissionsAndGetEnforcingAdmin(
14220                 who,
14221                 new String[]{
14222                         MANAGE_DEVICE_POLICY_APPS_CONTROL,
14223                         MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL
14224                 },
14225                 caller.getPackageName(),
14226                 caller.getUserId());
14227         mDevicePolicyEngine.setLocalPolicy(
14228                 PolicyDefinition.PACKAGE_UNINSTALL_BLOCKED(packageName),
14229                 enforcingAdmin,
14230                 new BooleanPolicyValue(uninstallBlocked),
14231                 caller.getUserId());
14232 
14233         DevicePolicyEventLogger
14234                 .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED)
14235                 .setAdmin(caller.getPackageName())
14236                 .setBoolean(/* isDelegate */ isCallerDelegate(caller))
14237                 .setStrings(packageName)
14238                 .write();
14239     }
14240 
setUninstallBlockedUnchecked( String packageName, boolean uninstallBlocked, int userId)14241     static void setUninstallBlockedUnchecked(
14242             String packageName, boolean uninstallBlocked, int userId) {
14243         Binder.withCleanCallingIdentity(() -> {
14244             try {
14245                 AppGlobals.getPackageManager().setBlockUninstallForUser(
14246                         packageName, uninstallBlocked, userId);
14247             } catch (RemoteException re) {
14248                 // Shouldn't happen.
14249                 Slogf.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
14250             }
14251         });
14252         if (uninstallBlocked) {
14253             final PackageManagerInternal pmi = LocalServices.getService(
14254                     PackageManagerInternal.class);
14255             pmi.removeNonSystemPackageSuspensions(packageName, userId);
14256             pmi.removeDistractingPackageRestrictions(packageName, userId);
14257             pmi.flushPackageRestrictions(userId);
14258         }
14259     }
14260 
14261     @Override
isUninstallBlocked(String packageName)14262     public boolean isUninstallBlocked(String packageName) {
14263         // This function should return true if and only if the package is blocked by
14264         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
14265         // when the package is a system app, or when it is an active device admin.
14266         final int userId = UserHandle.getCallingUserId();
14267 
14268         synchronized (getLockObject()) {
14269             try {
14270                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
14271             } catch (RemoteException re) {
14272                 // Shouldn't happen.
14273                 Slogf.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
14274             }
14275         }
14276         return false;
14277     }
14278 
14279     @Override
setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled)14280     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
14281         if (!mHasFeature) {
14282             return;
14283         }
14284         Objects.requireNonNull(who, "ComponentName is null");
14285         final CallerIdentity caller = getCallerIdentity(who);
14286         Preconditions.checkCallAuthorization(isProfileOwner(caller));
14287 
14288         synchronized (getLockObject()) {
14289             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14290             if (disabled) {
14291                 admin.mManagedProfileCallerIdAccess =
14292                         new PackagePolicy(PackagePolicy.PACKAGE_POLICY_ALLOWLIST);
14293             } else {
14294                 admin.mManagedProfileCallerIdAccess =
14295                         new PackagePolicy(PackagePolicy.PACKAGE_POLICY_BLOCKLIST);
14296             }
14297             saveSettingsLocked(caller.getUserId());
14298         }
14299         DevicePolicyEventLogger
14300                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALLER_ID_DISABLED)
14301                 .setAdmin(who)
14302                 .setBoolean(disabled)
14303                 .write();
14304     }
14305 
14306     @Override
getCrossProfileCallerIdDisabled(ComponentName who)14307     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
14308         if (!mHasFeature) {
14309             return false;
14310         }
14311         Objects.requireNonNull(who, "ComponentName is null");
14312         final CallerIdentity caller = getCallerIdentity(who);
14313         Preconditions.checkCallAuthorization(isProfileOwner(caller));
14314 
14315         synchronized (getLockObject()) {
14316             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14317             if (admin == null) {
14318                 return false;
14319             }
14320 
14321             if (admin.mManagedProfileCallerIdAccess == null) {
14322                 return admin.disableCallerId;
14323             }
14324 
14325             if (admin.mManagedProfileCallerIdAccess.getPolicyType()
14326                     == PackagePolicy.PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM) {
14327                 Slogf.w(LOG_TAG, "Denying callerId due to PACKAGE_POLICY_SYSTEM policyType");
14328             }
14329 
14330             return admin.mManagedProfileCallerIdAccess.getPolicyType()
14331                     != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
14332         }
14333     }
14334 
14335     @Override
getCrossProfileCallerIdDisabledForUser(int userId)14336     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
14337         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14338 
14339         final CallerIdentity caller = getCallerIdentity();
14340         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14341 
14342         synchronized (getLockObject()) {
14343             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14344             if (admin == null) {
14345                 return false;
14346             }
14347 
14348             if (admin.mManagedProfileCallerIdAccess == null) {
14349                 return admin.disableCallerId;
14350             }
14351 
14352             return admin.mManagedProfileCallerIdAccess.getPolicyType()
14353                     == PackagePolicy.PACKAGE_POLICY_ALLOWLIST;
14354         }
14355     }
14356 
14357     @Override
setManagedProfileCallerIdAccessPolicy(PackagePolicy policy)14358     public void setManagedProfileCallerIdAccessPolicy(PackagePolicy policy) {
14359         if (!mHasFeature) {
14360             return;
14361         }
14362         final CallerIdentity caller = getCallerIdentity();
14363         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14364                 && isManagedProfile(caller.getUserId())));
14365         synchronized (getLockObject()) {
14366             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14367             admin.disableCallerId = false;
14368             admin.mManagedProfileCallerIdAccess = policy;
14369             saveSettingsLocked(caller.getUserId());
14370         }
14371     }
14372 
14373     @Override
getManagedProfileCallerIdAccessPolicy()14374     public PackagePolicy getManagedProfileCallerIdAccessPolicy() {
14375         if (!mHasFeature) {
14376             return null;
14377         }
14378         final CallerIdentity caller = getCallerIdentity();
14379         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14380                 && isManagedProfile(caller.getUserId())));
14381         synchronized (getLockObject()) {
14382             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14383             return (admin != null) ? admin.mManagedProfileCallerIdAccess : null;
14384         }
14385     }
14386 
14387     @Override
hasManagedProfileCallerIdAccess(int userId, String packageName)14388     public boolean hasManagedProfileCallerIdAccess(int userId, String packageName) {
14389         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14390 
14391         final CallerIdentity caller = getCallerIdentity();
14392         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14393 
14394         synchronized (getLockObject()) {
14395             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14396             if (admin != null) {
14397                 if (admin.mManagedProfileCallerIdAccess == null) {
14398                     return !admin.disableCallerId;
14399                 }
14400                 return admin.mManagedProfileCallerIdAccess.isPackageAllowed(packageName,
14401                         mContactSystemRoleHolders);
14402             }
14403         }
14404         return true;
14405     }
14406 
14407     @Override
setManagedProfileContactsAccessPolicy(PackagePolicy policy)14408     public void setManagedProfileContactsAccessPolicy(PackagePolicy policy) {
14409         if (!mHasFeature) {
14410             return;
14411         }
14412         final CallerIdentity caller = getCallerIdentity();
14413         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14414                 && isManagedProfile(caller.getUserId())));
14415 
14416         synchronized (getLockObject()) {
14417             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14418             admin.disableContactsSearch = false;
14419             admin.mManagedProfileContactsAccess = policy;
14420             saveSettingsLocked(caller.getUserId());
14421         }
14422     }
14423 
14424     @Override
getManagedProfileContactsAccessPolicy()14425     public PackagePolicy getManagedProfileContactsAccessPolicy() {
14426         if (!mHasFeature) {
14427             return null;
14428         }
14429 
14430         final CallerIdentity caller = getCallerIdentity();
14431         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14432                 && isManagedProfile(caller.getUserId())));
14433 
14434         synchronized (getLockObject()) {
14435             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14436             return (admin != null) ? admin.mManagedProfileContactsAccess : null;
14437         }
14438     }
14439 
14440     @Override
hasManagedProfileContactsAccess(int userId, String packageName)14441     public boolean hasManagedProfileContactsAccess(int userId, String packageName) {
14442         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14443 
14444         final CallerIdentity caller = getCallerIdentity();
14445         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14446 
14447         synchronized (getLockObject()) {
14448             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14449             if (admin != null) {
14450                 if (admin.mManagedProfileContactsAccess == null) {
14451                     return !admin.disableContactsSearch;
14452                 }
14453 
14454                 return admin.mManagedProfileContactsAccess.isPackageAllowed(packageName,
14455                         mContactSystemRoleHolders);
14456             }
14457         }
14458         return true;
14459     }
14460 
14461     @Override
setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled)14462     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
14463         if (!mHasFeature) {
14464             return;
14465         }
14466         Objects.requireNonNull(who, "ComponentName is null");
14467         final CallerIdentity caller = getCallerIdentity(who);
14468         Preconditions.checkCallAuthorization(isProfileOwner(caller));
14469 
14470         synchronized (getLockObject()) {
14471             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14472             if (disabled) {
14473                 admin.mManagedProfileContactsAccess =
14474                         new PackagePolicy(PackagePolicy.PACKAGE_POLICY_ALLOWLIST);
14475             } else {
14476                 admin.mManagedProfileContactsAccess =
14477                         new PackagePolicy(PackagePolicy.PACKAGE_POLICY_BLOCKLIST);
14478             }
14479             saveSettingsLocked(caller.getUserId());
14480         }
14481         DevicePolicyEventLogger
14482                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED)
14483                 .setAdmin(who)
14484                 .setBoolean(disabled)
14485                 .write();
14486     }
14487 
14488     @Override
getCrossProfileContactsSearchDisabled(ComponentName who)14489     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
14490         if (!mHasFeature) {
14491             return false;
14492         }
14493         Objects.requireNonNull(who, "ComponentName is null");
14494         final CallerIdentity caller = getCallerIdentity(who);
14495         Preconditions.checkCallAuthorization(isProfileOwner(caller));
14496 
14497         synchronized (getLockObject()) {
14498             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
14499             if (admin == null) {
14500                 return false;
14501             }
14502             if (admin.mManagedProfileContactsAccess == null) {
14503                 return admin.disableContactsSearch;
14504             }
14505             return admin.mManagedProfileContactsAccess.getPolicyType()
14506                     != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
14507         }
14508     }
14509 
14510     @Override
getCrossProfileContactsSearchDisabledForUser(int userId)14511     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
14512         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14513 
14514         final CallerIdentity caller = getCallerIdentity();
14515         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14516 
14517         synchronized (getLockObject()) {
14518             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14519             if (admin == null) {
14520                 return false;
14521             }
14522 
14523             if (admin.mManagedProfileContactsAccess == null) {
14524                 return admin.disableContactsSearch;
14525             }
14526             if (admin.mManagedProfileContactsAccess.getPolicyType()
14527                     == PackagePolicy.PACKAGE_POLICY_ALLOWLIST_AND_SYSTEM) {
14528                 Slogf.w(LOG_TAG, "Denying contacts due to PACKAGE_POLICY_SYSTEM policyType");
14529             }
14530             return admin.mManagedProfileContactsAccess.getPolicyType()
14531                     != PackagePolicy.PACKAGE_POLICY_BLOCKLIST;
14532         }
14533     }
14534 
14535     @Override
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent)14536     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
14537             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
14538         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
14539                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
14540         final int callingUserId = UserHandle.getCallingUserId();
14541 
14542         mInjector.binderWithCleanCallingIdentity(() -> {
14543             synchronized (getLockObject()) {
14544                 final int managedUserId = getManagedUserId(callingUserId);
14545                 if (managedUserId < 0) {
14546                     return;
14547                 }
14548                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
14549                     if (VERBOSE_LOG) {
14550                         Slogf.v(LOG_TAG, "Cross-profile contacts access disabled for user %d",
14551                                 managedUserId);
14552                     }
14553                     return;
14554                 }
14555                 ContactsInternal.startQuickContactWithErrorToastForUser(
14556                         mContext, intent, new UserHandle(managedUserId));
14557             }
14558         });
14559     }
14560 
14561     /**
14562      * @return true if cross-profile QuickContact is disabled
14563      */
isCrossProfileQuickContactDisabled(@serIdInt int userId)14564     private boolean isCrossProfileQuickContactDisabled(@UserIdInt int userId) {
14565         return getCrossProfileCallerIdDisabledForUser(userId)
14566                 && getCrossProfileContactsSearchDisabledForUser(userId);
14567     }
14568 
14569     /**
14570      * @return the user ID of the managed user that is linked to the current user, if any.
14571      * Otherwise UserHandle.USER_NULL (-10000).
14572      */
getManagedUserId(@serIdInt int callingUserId)14573     public int getManagedUserId(@UserIdInt int callingUserId) {
14574         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "getManagedUserId: callingUserId=%d", callingUserId);
14575 
14576         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
14577             if (ui.id == callingUserId || !ui.isManagedProfile()) {
14578                 continue; // Caller user self, or not a managed profile.  Skip.
14579             }
14580             if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Managed user=%d", ui.id);
14581             return ui.id;
14582         }
14583         if (VERBOSE_LOG)  Slogf.v(LOG_TAG, "Managed user not found.");
14584         return UserHandle.USER_NULL;
14585     }
14586 
14587     /**
14588      * Returns the userId of the managed profile on the device.
14589      * If none exists, return {@link UserHandle#USER_NULL}.
14590      *
14591      * We assume there is only one managed profile across all users
14592      * on the device, which is true for now (HSUM or not) but could
14593      * change in future.
14594      */
getManagedUserId()14595     private @UserIdInt int getManagedUserId() {
14596         // On HSUM, there is only one main user and only the main user
14597         // can have a managed profile (for now). On non-HSUM, only user 0
14598         // can host the managed profile and user 0 is the main user.
14599         // So in both cases, we could just get the main user and
14600         // search for the profile user under it.
14601         UserHandle mainUser = mUserManager.getMainUser();
14602         if (mainUser == null) return UserHandle.USER_NULL;
14603         return getManagedUserId(mainUser.getIdentifier());
14604     }
14605 
14606     @Override
setBluetoothContactSharingDisabled(ComponentName who, boolean disabled)14607     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
14608         if (!mHasFeature) {
14609             return;
14610         }
14611         Objects.requireNonNull(who, "ComponentName is null");
14612 
14613         final CallerIdentity caller = getCallerIdentity(who);
14614         Preconditions.checkCallAuthorization(
14615                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
14616 
14617         synchronized (getLockObject()) {
14618             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
14619             if (admin.disableBluetoothContactSharing != disabled) {
14620                 admin.disableBluetoothContactSharing = disabled;
14621                 saveSettingsLocked(caller.getUserId());
14622             }
14623         }
14624         DevicePolicyEventLogger
14625                 .createEvent(DevicePolicyEnums.SET_BLUETOOTH_CONTACT_SHARING_DISABLED)
14626                 .setAdmin(who)
14627                 .setBoolean(disabled)
14628                 .write();
14629     }
14630 
14631     @Override
getBluetoothContactSharingDisabled(ComponentName who)14632     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
14633         if (!mHasFeature) {
14634             return false;
14635         }
14636         Objects.requireNonNull(who, "ComponentName is null");
14637 
14638         final CallerIdentity caller = getCallerIdentity(who);
14639         Preconditions.checkCallAuthorization(
14640                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
14641 
14642         synchronized (getLockObject()) {
14643             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
14644             return admin.disableBluetoothContactSharing;
14645         }
14646     }
14647 
14648     @Override
getBluetoothContactSharingDisabledForUser(int userId)14649     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
14650         // TODO: Should there be a check to make sure this relationship is
14651         // within a profile group?
14652         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
14653         synchronized (getLockObject()) {
14654             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14655             return (admin != null) ? admin.disableBluetoothContactSharing : false;
14656         }
14657     }
14658 
14659     @Override
setSecondaryLockscreenEnabled(ComponentName who, boolean enabled)14660     public void setSecondaryLockscreenEnabled(ComponentName who, boolean enabled) {
14661         Objects.requireNonNull(who, "ComponentName is null");
14662 
14663         // Check can set secondary lockscreen enabled
14664         final CallerIdentity caller = getCallerIdentity(who);
14665         Preconditions.checkCallAuthorization(
14666                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
14667         Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
14668                 "User %d is not allowed to call setSecondaryLockscreenEnabled",
14669                         caller.getUserId());
14670 
14671         synchronized (getLockObject()) {
14672             // Allow testOnly admins to bypass supervision config requirement.
14673             Preconditions.checkCallAuthorization(isAdminTestOnlyLocked(who, caller.getUserId())
14674                     || isSupervisionComponentLocked(caller.getComponentName()), "Admin %s is not "
14675                     + "the default supervision component", caller.getComponentName());
14676             DevicePolicyData policy = getUserData(caller.getUserId());
14677             policy.mSecondaryLockscreenEnabled = enabled;
14678             saveSettingsLocked(caller.getUserId());
14679         }
14680     }
14681 
14682     @Override
isSecondaryLockscreenEnabled(@onNull UserHandle userHandle)14683     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
14684         synchronized (getLockObject()) {
14685             return getUserData(userHandle.getIdentifier()).mSecondaryLockscreenEnabled;
14686         }
14687     }
14688 
isManagedProfileOwner(CallerIdentity caller)14689     private boolean isManagedProfileOwner(CallerIdentity caller) {
14690         return isProfileOwner(caller) && isManagedProfile(caller.getUserId());
14691     }
14692 
14693     @Override
setPreferentialNetworkServiceConfigs( List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs)14694     public void setPreferentialNetworkServiceConfigs(
14695             List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
14696         if (!mHasFeature) {
14697             return;
14698         }
14699         final CallerIdentity caller = getCallerIdentity();
14700         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14701                         && isManagedProfile(caller.getUserId()))
14702                         || isDefaultDeviceOwner(caller),
14703                 "Caller is not managed profile owner or device owner;"
14704                         + " only managed profile owner or device owner may control the preferential"
14705                         + " network service");
14706 
14707         try {
14708             updateNetworkPreferenceForUser(caller.getUserId(), preferentialNetworkServiceConfigs);
14709             synchronized (getLockObject()) {
14710                 final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
14711                         caller.getUserId());
14712                 if (!requiredAdmin.mPreferentialNetworkServiceConfigs.equals(
14713                         preferentialNetworkServiceConfigs)) {
14714                     requiredAdmin.mPreferentialNetworkServiceConfigs =
14715                             new ArrayList<>(preferentialNetworkServiceConfigs);
14716                     saveSettingsLocked(caller.getUserId());
14717                 }
14718             }
14719         } catch (Exception e) {
14720             Slogf.e(LOG_TAG, "Failed to set preferential network service configs");
14721             throw e;
14722         }
14723         DevicePolicyEventLogger
14724                 .createEvent(DevicePolicyEnums.SET_PREFERENTIAL_NETWORK_SERVICE_ENABLED)
14725                 .setBoolean(preferentialNetworkServiceConfigs
14726                         .stream().anyMatch(c -> c.isEnabled()))
14727                 .write();
14728     }
14729 
14730     @Override
getPreferentialNetworkServiceConfigs()14731     public List<PreferentialNetworkServiceConfig> getPreferentialNetworkServiceConfigs() {
14732         if (!mHasFeature) {
14733             return List.of(PreferentialNetworkServiceConfig.DEFAULT);
14734         }
14735 
14736         final CallerIdentity caller = getCallerIdentity();
14737         Preconditions.checkCallAuthorization((isProfileOwner(caller)
14738                         && isManagedProfile(caller.getUserId()))
14739                         || isDefaultDeviceOwner(caller),
14740                 "Caller is not managed profile owner or device owner;"
14741                         + " only managed profile owner or device owner may retrieve the "
14742                         + "preferential network service configurations");
14743         synchronized (getLockObject()) {
14744             final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
14745                     caller.getUserId());
14746             return requiredAdmin.mPreferentialNetworkServiceConfigs;
14747         }
14748     }
14749 
14750     @Override
setLockTaskPackages(ComponentName who, String callerPackageName, String[] packages)14751     public void setLockTaskPackages(ComponentName who, String callerPackageName, String[] packages)
14752             throws SecurityException {
14753         Objects.requireNonNull(packages, "packages is null");
14754         if (!Flags.devicePolicySizeTrackingInternalBugFixEnabled()) {
14755             for (String pkg : packages) {
14756                 PolicySizeVerifier.enforceMaxPackageNameLength(pkg);
14757             }
14758         }
14759 
14760         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
14761         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_PACKAGES);
14762 
14763         EnforcingAdmin enforcingAdmin;
14764         synchronized (getLockObject()) {
14765             enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
14766         }
14767         LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
14768                 PolicyDefinition.LOCK_TASK,
14769                 enforcingAdmin,
14770                 caller.getUserId());
14771         LockTaskPolicy policy;
14772         if (currentPolicy == null) {
14773             policy = new LockTaskPolicy(Set.of(packages));
14774         } else {
14775             policy = new LockTaskPolicy(currentPolicy);
14776             policy.setPackages(Set.of(packages));
14777         }
14778         if (policy.getPackages().isEmpty()) {
14779             mDevicePolicyEngine.removeLocalPolicy(
14780                     PolicyDefinition.LOCK_TASK,
14781                     enforcingAdmin,
14782                     caller.getUserId());
14783         } else {
14784             mDevicePolicyEngine.setLocalPolicy(
14785                     PolicyDefinition.LOCK_TASK,
14786                     enforcingAdmin,
14787                     policy,
14788                     caller.getUserId());
14789         }
14790     }
14791 
14792     @Override
getLockTaskPackages(ComponentName who, String callerPackageName)14793     public String[] getLockTaskPackages(ComponentName who, String callerPackageName) {
14794         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
14795         final int userHandle = caller.getUserId();
14796 
14797         synchronized (getLockObject()) {
14798             enforceCanQueryLockTaskLocked(who, caller.getPackageName());
14799         }
14800         LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
14801                 PolicyDefinition.LOCK_TASK, userHandle);
14802         if (policy == null) {
14803             return new String[0];
14804         } else {
14805             return policy.getPackages().toArray(new String[policy.getPackages().size()]);
14806         }
14807     }
14808 
14809     @Override
isLockTaskPermitted(String pkg)14810     public boolean isLockTaskPermitted(String pkg) {
14811         // Check policy-exempt apps first, as it doesn't require the lock
14812         if (listPolicyExemptAppsUnchecked(mContext).contains(pkg)) {
14813             if (VERBOSE_LOG) {
14814                 Slogf.v(LOG_TAG, "isLockTaskPermitted(%s): returning true for policy-exempt app",
14815                             pkg);
14816             }
14817             return true;
14818         }
14819 
14820         final int userId = mInjector.userHandleGetCallingUserId();
14821         LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
14822                 PolicyDefinition.LOCK_TASK, userId);
14823         if (policy == null) {
14824             return false;
14825         }
14826         return policy.getPackages().contains(pkg);
14827     }
14828 
14829     @Override
setLockTaskFeatures(ComponentName who, String callerPackageName, int flags)14830     public void setLockTaskFeatures(ComponentName who, String callerPackageName, int flags) {
14831         // Throw if Overview is used without Home.
14832         boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0;
14833         boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0;
14834         Preconditions.checkArgument(hasHome || !hasOverview,
14835                 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME");
14836         boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0;
14837         Preconditions.checkArgument(hasHome || !hasNotification,
14838             "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");
14839 
14840         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
14841         synchronized (getLockObject()) {
14842             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_FEATURES);
14843         }
14844 
14845         EnforcingAdmin enforcingAdmin;
14846         synchronized (getLockObject()) {
14847             enforcingAdmin = enforceCanCallLockTaskLocked(who, caller.getPackageName());
14848             enforceCanSetLockTaskFeaturesOnFinancedDevice(caller, flags);
14849         }
14850         LockTaskPolicy currentPolicy = mDevicePolicyEngine.getLocalPolicySetByAdmin(
14851                 PolicyDefinition.LOCK_TASK,
14852                 enforcingAdmin,
14853                 caller.getUserId());
14854         LockTaskPolicy policy;
14855         if (currentPolicy == null) {
14856             policy = new LockTaskPolicy(flags);
14857         } else {
14858             policy = new LockTaskPolicy(currentPolicy);
14859             policy.setFlags(flags);
14860         }
14861         if (policy.getPackages().isEmpty()
14862                 && policy.getFlags() == DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
14863             mDevicePolicyEngine.removeLocalPolicy(
14864                     PolicyDefinition.LOCK_TASK,
14865                     enforcingAdmin,
14866                     caller.getUserId());
14867         } else {
14868             mDevicePolicyEngine.setLocalPolicy(
14869                     PolicyDefinition.LOCK_TASK,
14870                     enforcingAdmin,
14871                     policy,
14872                     caller.getUserId());
14873         }
14874     }
14875 
14876     @Override
getLockTaskFeatures(ComponentName who, String callerPackageName)14877     public int getLockTaskFeatures(ComponentName who, String callerPackageName) {
14878         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
14879         final int userHandle = caller.getUserId();
14880 
14881         synchronized (getLockObject()) {
14882             enforceCanQueryLockTaskLocked(who, caller.getPackageName());
14883         }
14884         LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
14885                 PolicyDefinition.LOCK_TASK, userHandle);
14886         if (policy == null) {
14887             // We default on the power button menu, in order to be consistent with pre-P
14888             // behaviour.
14889             return DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
14890         }
14891         return policy.getFlags();
14892     }
14893 
maybeClearLockTaskPolicyLocked()14894     private void maybeClearLockTaskPolicyLocked() {
14895         mInjector.binderWithCleanCallingIdentity(() -> {
14896             final List<UserInfo> userInfos = mUserManager.getAliveUsers();
14897             for (int i = userInfos.size() - 1; i >= 0; i--) {
14898                 int userId = userInfos.get(i).id;
14899                 if (canDPCManagedUserUseLockTaskLocked(userId)) {
14900                     continue;
14901                 }
14902                 Map<EnforcingAdmin, PolicyValue<LockTaskPolicy>> policies =
14903                         mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
14904                                 PolicyDefinition.LOCK_TASK, userId);
14905                 Set<EnforcingAdmin> admins = new HashSet<>(policies.keySet());
14906                 for (EnforcingAdmin admin : admins) {
14907                     if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
14908                         mDevicePolicyEngine.removeLocalPolicy(
14909                                 PolicyDefinition.LOCK_TASK, admin, userId);
14910                     }
14911                 }
14912             }
14913         });
14914     }
14915 
enforceCanSetLockTaskFeaturesOnFinancedDevice(CallerIdentity caller, int flags)14916     private void enforceCanSetLockTaskFeaturesOnFinancedDevice(CallerIdentity caller, int flags) {
14917         int allowedFlags = LOCK_TASK_FEATURE_SYSTEM_INFO | LOCK_TASK_FEATURE_KEYGUARD
14918                 | LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_GLOBAL_ACTIONS
14919                 | LOCK_TASK_FEATURE_NOTIFICATIONS | LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK;
14920 
14921         if (!isFinancedDeviceOwner(caller)) {
14922             return;
14923         }
14924 
14925         if ((flags & ~(allowedFlags)) != 0) {
14926             throw new SecurityException(
14927                     "Permitted lock task features when managing a financed device: "
14928                             + "LOCK_TASK_FEATURE_SYSTEM_INFO, LOCK_TASK_FEATURE_KEYGUARD, "
14929                             + "LOCK_TASK_FEATURE_HOME, LOCK_TASK_FEATURE_GLOBAL_ACTIONS, "
14930                             + "LOCK_TASK_FEATURE_NOTIFICATIONS"
14931                             + " or LOCK_TASK_FEATURE_BLOCK_ACTIVITY_START_IN_TASK");
14932         }
14933     }
14934 
14935     @Override
notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle)14936     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
14937         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
14938                 String.format(NOT_SYSTEM_CALLER_MSG, "call notifyLockTaskModeChanged"));
14939         synchronized (getLockObject()) {
14940             final DevicePolicyData policy = getUserData(userHandle);
14941 
14942             if (policy.mStatusBarDisabled) {
14943                 // Status bar is managed by LockTaskController during LockTask, so we cancel this
14944                 // policy when LockTask starts, and reapply it when LockTask ends
14945                 setStatusBarDisabledInternal(!isEnabled, userHandle);
14946             }
14947 
14948             Bundle adminExtras = new Bundle();
14949             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
14950             for (ActiveAdmin admin : policy.mAdminList) {
14951                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
14952                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
14953                 // TODO(b/281738975): Should we be logging this for all admins?
14954                 if (ownsDevice || ownsProfile) {
14955                     if (isEnabled) {
14956                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
14957                                 adminExtras, null);
14958                     } else {
14959                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
14960                     }
14961                     DevicePolicyEventLogger
14962                             .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED)
14963                             .setAdmin(admin.info == null ? null : admin.info.getPackageName())
14964                             .setBoolean(isEnabled)
14965                             .setStrings(pkg)
14966                             .write();
14967                 }
14968             }
14969         }
14970         // TODO(b/281738975): Should we be logging this for all admins?
14971         for(EnforcingAdmin admin : mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
14972                 PolicyDefinition.LOCK_TASK, userHandle).keySet()) {
14973             if (admin.hasAuthority(EnforcingAdmin.DPC_AUTHORITY)) {
14974                 // already handled above
14975                 continue;
14976             }
14977             DevicePolicyEventLogger
14978                     .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED)
14979                     .setAdmin(admin.getPackageName())
14980                     .setBoolean(isEnabled)
14981                     .setStrings(pkg)
14982                     .write();
14983         }
14984     }
14985 
14986     @Override
setGlobalSetting(ComponentName who, String setting, String value)14987     public void setGlobalSetting(ComponentName who, String setting, String value) {
14988         final CallerIdentity caller = getCallerIdentity(who);
14989         if (Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS.equals(setting)) {
14990             Preconditions.checkCallAuthorization(isCallerDevicePolicyManagementRoleHolder(caller));
14991             mInjector.binderWithCleanCallingIdentity(
14992                     () -> mInjector.settingsGlobalPutString(setting, value));
14993             return;
14994         }
14995         Objects.requireNonNull(who, "ComponentName is null");
14996         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
14997 
14998         DevicePolicyEventLogger
14999                 .createEvent(DevicePolicyEnums.SET_GLOBAL_SETTING)
15000                 .setAdmin(who)
15001                 .setStrings(setting, value)
15002                 .write();
15003 
15004         synchronized (getLockObject()) {
15005             // Some settings are no supported any more. However we do not want to throw a
15006             // SecurityException to avoid breaking apps.
15007             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
15008                 Slogf.i(LOG_TAG, "Global setting no longer supported: %s", setting);
15009                 return;
15010             }
15011 
15012             if (!GLOBAL_SETTINGS_ALLOWLIST.contains(setting)
15013                     && !UserManager.isDeviceInDemoMode(mContext)) {
15014                 throw new SecurityException(String.format(
15015                         "Permission denial: device owners cannot update %1$s", setting));
15016             }
15017 
15018             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
15019                 // ignore if it contradicts an existing policy
15020                 long timeMs = getMaximumTimeToLock(
15021                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
15022                 if (timeMs > 0 && timeMs < Long.MAX_VALUE) {
15023                     return;
15024                 }
15025             }
15026 
15027             mInjector.binderWithCleanCallingIdentity(
15028                     () -> mInjector.settingsGlobalPutString(setting, value));
15029         }
15030     }
15031 
15032     @Override
setSystemSetting(ComponentName who, String setting, String value, boolean parent)15033     public void setSystemSetting(ComponentName who, String setting, String value, boolean parent) {
15034         Objects.requireNonNull(who, "ComponentName is null");
15035         Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
15036         final CallerIdentity caller = getCallerIdentity(who);
15037         Preconditions.checkCallAuthorization(
15038                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15039         if (Flags.allowScreenBrightnessControlOnCope() && parent) {
15040             Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
15041         }
15042         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_SETTING);
15043 
15044         synchronized (getLockObject()) {
15045             if (!SYSTEM_SETTINGS_ALLOWLIST.contains(setting)) {
15046                 throw new SecurityException(String.format(
15047                         "Permission denial: device owners cannot update %1$s", setting));
15048             }
15049             int affectedUser;
15050             if (Flags.allowScreenBrightnessControlOnCope() && parent) {
15051                 affectedUser = getProfileParentId(caller.getUserId());
15052             } else {
15053                 affectedUser = caller.getUserId();
15054             }
15055             mInjector.binderWithCleanCallingIdentity(() ->
15056                     mInjector.settingsSystemPutStringForUser(setting, value, affectedUser));
15057         }
15058     }
15059 
15060     @Override
setConfiguredNetworksLockdownState( ComponentName who, String callerPackageName, boolean lockdown)15061     public void setConfiguredNetworksLockdownState(
15062             ComponentName who, String callerPackageName, boolean lockdown) {
15063         if (!mHasFeature) {
15064             return;
15065         }
15066         CallerIdentity caller;
15067 
15068         if (isPermissionCheckFlagEnabled()) {
15069             caller = getCallerIdentity(who, callerPackageName);
15070             enforcePermission(MANAGE_DEVICE_POLICY_WIFI, caller.getPackageName(),
15071                     UserHandle.USER_ALL);
15072         } else {
15073             caller = getCallerIdentity(who);
15074             Preconditions.checkNotNull(who, "ComponentName is null");
15075             Preconditions.checkCallAuthorization(
15076                     isDefaultDeviceOwner(caller)
15077                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
15078         }
15079 
15080         mInjector.binderWithCleanCallingIdentity(() ->
15081                 mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN,
15082                         lockdown ? 1 : 0));
15083 
15084         DevicePolicyEventLogger
15085                 .createEvent(DevicePolicyEnums.ALLOW_MODIFICATION_OF_ADMIN_CONFIGURED_NETWORKS)
15086                 .setAdmin(caller.getPackageName())
15087                 .setBoolean(lockdown)
15088                 .write();
15089     }
15090 
15091     @Override
hasLockdownAdminConfiguredNetworks(ComponentName who)15092     public boolean hasLockdownAdminConfiguredNetworks(ComponentName who) {
15093         if (!mHasFeature) {
15094             return false;
15095         }
15096         CallerIdentity caller = getCallerIdentity(who);
15097         if (isPermissionCheckFlagEnabled()) {
15098             enforcePermission(MANAGE_DEVICE_POLICY_WIFI, who.getPackageName(),
15099                     UserHandle.USER_ALL);
15100         } else {
15101             Preconditions.checkNotNull(who, "ComponentName is null");
15102 
15103             Preconditions.checkCallAuthorization(
15104                     isDefaultDeviceOwner(caller)
15105                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
15106         }
15107 
15108         return mInjector.binderWithCleanCallingIdentity(() ->
15109                 mInjector.settingsGlobalGetInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) > 0);
15110     }
15111 
15112     @Override
setLocationEnabled(ComponentName who, boolean locationEnabled)15113     public void setLocationEnabled(ComponentName who, boolean locationEnabled) {
15114         Preconditions.checkNotNull(who, "ComponentName is null");
15115 
15116         final CallerIdentity caller = getCallerIdentity(who);
15117         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
15118 
15119         UserHandle userHandle = caller.getUserHandle();
15120         if (mIsAutomotive && !locationEnabled) {
15121             Slogf.i(LOG_TAG, "setLocationEnabled(%s, %b): ignoring for user %s on automotive build",
15122                     who.flattenToShortString(), locationEnabled, userHandle);
15123             return;
15124         }
15125 
15126         mInjector.binderWithCleanCallingIdentity(() -> {
15127             boolean wasLocationEnabled = mInjector.getLocationManager().isLocationEnabledForUser(
15128                     userHandle);
15129             Slogf.v(LOG_TAG, "calling locationMgr.setLocationEnabledForUser(%b, %s) when it was %b",
15130                     locationEnabled, userHandle, wasLocationEnabled);
15131             mInjector.getLocationManager().setLocationEnabledForUser(locationEnabled, userHandle);
15132 
15133             // make a best effort to only show the notification if the admin is actually enabling
15134             // location. this is subject to race conditions with settings changes, but those are
15135             // unlikely to realistically interfere
15136             if (locationEnabled && !wasLocationEnabled) {
15137                 showLocationSettingsEnabledNotification(userHandle);
15138             }
15139         });
15140 
15141         DevicePolicyEventLogger
15142                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
15143                 .setAdmin(who)
15144                 .setStrings(Settings.Secure.LOCATION_MODE, Integer.toString(
15145                         locationEnabled ? Settings.Secure.LOCATION_MODE_ON
15146                                 : Settings.Secure.LOCATION_MODE_OFF))
15147                 .write();
15148     }
15149 
showLocationSettingsEnabledNotification(UserHandle user)15150     private void showLocationSettingsEnabledNotification(UserHandle user) {
15151         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
15152                 .addFlags(FLAG_ACTIVITY_NEW_TASK);
15153         // Fill the component explicitly to prevent the PendingIntent from being intercepted
15154         // and fired with crafted target. b/155183624
15155         ActivityInfo targetInfo = intent.resolveActivityInfo(
15156                 mInjector.getPackageManager(user.getIdentifier()),
15157                 PackageManager.MATCH_SYSTEM_ONLY);
15158         if (targetInfo != null) {
15159             intent.setComponent(targetInfo.getComponentName());
15160         } else {
15161             Slogf.wtf(LOG_TAG, "Failed to resolve intent for location settings");
15162         }
15163 
15164         // Simple notification clicks are immutable
15165         PendingIntent locationSettingsIntent = mInjector.pendingIntentGetActivityAsUser(mContext, 0,
15166                 intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE, null,
15167                 user);
15168         Notification notification = new Notification.Builder(mContext,
15169                 SystemNotificationChannels.DEVICE_ADMIN)
15170                 .setSmallIcon(R.drawable.ic_info_outline)
15171                 .setContentTitle(getLocationChangedTitle())
15172                 .setContentText(getLocationChangedText())
15173                 .setColor(mContext.getColor(R.color.system_notification_accent_color))
15174                 .setShowWhen(true)
15175                 .setContentIntent(locationSettingsIntent)
15176                 .setAutoCancel(true)
15177                 .build();
15178         mHandler.post(() -> mInjector.getNotificationManager().notify(
15179                 SystemMessage.NOTE_LOCATION_CHANGED, notification));
15180     }
15181 
getLocationChangedTitle()15182     private String getLocationChangedTitle() {
15183         return getUpdatableString(
15184                 LOCATION_CHANGED_TITLE, R.string.location_changed_notification_title);
15185     }
15186 
getLocationChangedText()15187     private String getLocationChangedText() {
15188         return getUpdatableString(
15189                 LOCATION_CHANGED_MESSAGE, R.string.location_changed_notification_text);
15190     }
15191 
15192     @Override
setTime(@ullable ComponentName who, String callerPackageName, long millis)15193     public boolean setTime(@Nullable ComponentName who, String callerPackageName, long millis) {
15194         CallerIdentity caller;
15195         if (isPermissionCheckFlagEnabled()) {
15196             caller = getCallerIdentity(who, callerPackageName);
15197             // This is a global action.
15198             enforcePermission(SET_TIME, caller.getPackageName(), UserHandle.USER_ALL);
15199         } else {
15200             caller = getCallerIdentity(who);
15201             Objects.requireNonNull(who, "ComponentName is null");
15202             Preconditions.checkCallAuthorization(
15203                     isDefaultDeviceOwner(caller)
15204                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
15205         }
15206 
15207         // Don't allow set time when auto time is on.
15208         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
15209             return false;
15210         }
15211         DevicePolicyEventLogger
15212                 .createEvent(DevicePolicyEnums.SET_TIME)
15213                 .setAdmin(caller.getPackageName())
15214                 .write();
15215         mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
15216         return true;
15217     }
15218 
15219     @Override
setTimeZone(@ullable ComponentName who, String callerPackageName, String timeZone)15220     public boolean setTimeZone(@Nullable ComponentName who, String callerPackageName,
15221             String timeZone) {
15222         CallerIdentity caller;
15223         if (isPermissionCheckFlagEnabled()) {
15224             caller = getCallerIdentity(who, callerPackageName);
15225             // This is a global action.
15226             enforcePermission(SET_TIME_ZONE, caller.getPackageName(), UserHandle.USER_ALL);
15227         } else {
15228             caller = getCallerIdentity(who);
15229             Objects.requireNonNull(who, "ComponentName is null");
15230             Preconditions.checkCallAuthorization(
15231                     isDefaultDeviceOwner(caller)
15232                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
15233         }
15234 
15235         // Don't allow set timezone when auto timezone is on.
15236         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
15237             return false;
15238         }
15239         String logInfo = "DevicePolicyManager.setTimeZone()";
15240         mInjector.binderWithCleanCallingIdentity(() ->
15241                 mInjector.getAlarmManagerInternal()
15242                         .setTimeZone(timeZone, TIME_ZONE_CONFIDENCE_HIGH, logInfo));
15243 
15244         DevicePolicyEventLogger
15245                 .createEvent(DevicePolicyEnums.SET_TIME_ZONE)
15246                 .setAdmin(caller.getPackageName())
15247                 .write();
15248         return true;
15249     }
15250 
15251     @Override
setSecureSetting(ComponentName who, String setting, String value)15252     public void setSecureSetting(ComponentName who, String setting, String value) {
15253         Objects.requireNonNull(who, "ComponentName is null");
15254         final CallerIdentity caller = getCallerIdentity(who);
15255         Preconditions.checkCallAuthorization(
15256                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15257 
15258         int callingUserId = caller.getUserId();
15259         synchronized (getLockObject()) {
15260             if (isDeviceOwner(who, callingUserId)) {
15261                 if (!SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.contains(setting)
15262                         && !isCurrentUserDemo()) {
15263                     throw new SecurityException(String.format(
15264                             "Permission denial: Device owners cannot update %1$s", setting));
15265                 }
15266             } else if (!SECURE_SETTINGS_ALLOWLIST.contains(setting) && !isCurrentUserDemo()) {
15267                 throw new SecurityException(String.format(
15268                         "Permission denial: Profile owners cannot update %1$s", setting));
15269             }
15270             if (setting.equals(Settings.Secure.LOCATION_MODE)
15271                     && isSetSecureSettingLocationModeCheckEnabled(who.getPackageName(),
15272                     callingUserId)) {
15273                 throw new UnsupportedOperationException(Settings.Secure.LOCATION_MODE + " is "
15274                         + "deprecated. Please use setLocationEnabled() instead.");
15275             }
15276             if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
15277                 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
15278                     throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
15279                             + " is deprecated. Please use one of the user restrictions "
15280                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
15281                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY + " instead.");
15282                 }
15283                 if (!mUserManager.isManagedProfile(callingUserId)) {
15284                     Slogf.e(LOG_TAG, "Ignoring setSecureSetting request for "
15285                             + setting + ". User restriction "
15286                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
15287                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY
15288                             + " should be used instead.");
15289                 } else {
15290                     try {
15291                         setUserRestriction(who, who.getPackageName(),
15292                                 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
15293                                 (Integer.parseInt(value) == 0) ? true : false, /* parent */ false);
15294                         DevicePolicyEventLogger
15295                                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
15296                                 .setAdmin(who)
15297                                 .setStrings(setting, value)
15298                                 .write();
15299                     } catch (NumberFormatException exc) {
15300                         Slogf.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
15301                     }
15302                 }
15303                 return;
15304             }
15305             mInjector.binderWithCleanCallingIdentity(() -> {
15306                 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
15307                     final String currentValue = mInjector.settingsSecureGetStringForUser(
15308                             Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
15309                     if (!TextUtils.equals(currentValue, value)) {
15310                         // Tell the content observer that the next change will be due to the owner
15311                         // changing the value. There is a small race condition here that we cannot
15312                         // avoid: Change notifications are sent asynchronously, so it is possible
15313                         // that there are prior notifications queued up before the one we are about
15314                         // to trigger. This is a corner case that will have no impact in practice.
15315                         mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
15316                     }
15317                     getUserData(callingUserId).mCurrentInputMethodSet = true;
15318                     saveSettingsLocked(callingUserId);
15319                 }
15320                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
15321                 // Notify the user if it's the location mode setting that's been set, to any value
15322                 // other than 'off'.
15323                 if (setting.equals(Settings.Secure.LOCATION_MODE)
15324                         && (Integer.parseInt(value) != 0)) {
15325                     showLocationSettingsEnabledNotification(UserHandle.of(callingUserId));
15326                 }
15327             });
15328         }
15329         DevicePolicyEventLogger
15330                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
15331                 .setAdmin(who)
15332                 .setStrings(setting, value)
15333                 .write();
15334     }
15335 
isSetSecureSettingLocationModeCheckEnabled(String packageName, int userId)15336     private boolean isSetSecureSettingLocationModeCheckEnabled(String packageName, int userId) {
15337         return mInjector.isChangeEnabled(USE_SET_LOCATION_ENABLED, packageName, userId);
15338     }
15339 
15340     @Override
setMasterVolumeMuted(ComponentName who, boolean on)15341     public void setMasterVolumeMuted(ComponentName who, boolean on) {
15342         Objects.requireNonNull(who, "ComponentName is null");
15343         final CallerIdentity caller = getCallerIdentity(who);
15344         Preconditions.checkCallAuthorization(
15345                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15346         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_MASTER_VOLUME_MUTED);
15347 
15348         synchronized (getLockObject()) {
15349             setUserRestriction(who, who.getPackageName(), UserManager.DISALLOW_UNMUTE_DEVICE, on,
15350                     /* parent */ false);
15351             DevicePolicyEventLogger
15352                     .createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED)
15353                     .setAdmin(who)
15354                     .setBoolean(on)
15355                     .write();
15356         }
15357     }
15358 
15359     @Override
isMasterVolumeMuted(ComponentName who)15360     public boolean isMasterVolumeMuted(ComponentName who) {
15361         Objects.requireNonNull(who, "ComponentName is null");
15362         final CallerIdentity caller = getCallerIdentity(who);
15363         Preconditions.checkCallAuthorization(
15364                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15365 
15366         synchronized (getLockObject()) {
15367             AudioManager audioManager =
15368                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
15369             return audioManager.isMasterMute();
15370         }
15371     }
15372 
15373     @Override
setUserIcon(ComponentName who, Bitmap icon)15374     public void setUserIcon(ComponentName who, Bitmap icon) {
15375         Objects.requireNonNull(who, "ComponentName is null");
15376         final CallerIdentity caller = getCallerIdentity(who);
15377         Preconditions.checkCallAuthorization(
15378                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15379 
15380         synchronized (getLockObject()) {
15381             mInjector.binderWithCleanCallingIdentity(
15382                     () -> mUserManagerInternal.setUserIcon(caller.getUserId(), icon));
15383         }
15384         DevicePolicyEventLogger
15385                 .createEvent(DevicePolicyEnums.SET_USER_ICON)
15386                 .setAdmin(who)
15387                 .write();
15388     }
15389 
15390     @Override
setKeyguardDisabled(ComponentName who, boolean disabled)15391     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
15392         Objects.requireNonNull(who, "ComponentName is null");
15393         final CallerIdentity caller = getCallerIdentity(who);
15394         Preconditions.checkCallAuthorization(
15395                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15396 
15397         final int userId = caller.getUserId();
15398         synchronized (getLockObject()) {
15399             Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
15400                     String.format(
15401                             "Admin %s is neither the device owner or affiliated user's profile "
15402                                     + "owner.", who));
15403         }
15404         if (isManagedProfile(userId)) {
15405             throw new SecurityException("Managed profile cannot disable keyguard");
15406         }
15407         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEYGUARD_DISABLED);
15408 
15409         long ident = mInjector.binderClearCallingIdentity();
15410         try {
15411             // disallow disabling the keyguard if a password is currently set
15412             if (disabled && mLockPatternUtils.isSecure(userId)) {
15413                 return false;
15414             }
15415             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
15416             if (disabled) {
15417                 mInjector
15418                         .getIWindowManager()
15419                         .dismissKeyguard(null /* callback */, null /* message */);
15420             }
15421             DevicePolicyEventLogger
15422                     .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED)
15423                     .setAdmin(who)
15424                     .setBoolean(disabled)
15425                     .write();
15426         } catch (RemoteException e) {
15427             // Same process, does not happen.
15428         } finally {
15429             mInjector.binderRestoreCallingIdentity(ident);
15430         }
15431         return true;
15432     }
15433 
15434     @Override
setStatusBarDisabled(ComponentName who, String callerPackageName, boolean disabled)15435     public boolean setStatusBarDisabled(ComponentName who, String callerPackageName,
15436             boolean disabled) {
15437         CallerIdentity caller;
15438         if (isUnicornFlagEnabled()) {
15439             caller = getCallerIdentity(who, callerPackageName);
15440         } else {
15441             caller = getCallerIdentity(who);
15442         }
15443         if (isUnicornFlagEnabled()) {
15444             enforcePermission(MANAGE_DEVICE_POLICY_STATUS_BAR, caller.getPackageName(),
15445                     UserHandle.USER_ALL);
15446         } else {
15447             Objects.requireNonNull(who, "ComponentName is null");
15448             Preconditions.checkCallAuthorization(
15449                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15450         }
15451 
15452         int userId = caller.getUserId();
15453         synchronized (getLockObject()) {
15454             if (!isUnicornFlagEnabled()) {
15455                 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
15456                         "Admin " + who + " is neither the device owner or affiliated "
15457                                 + "user's profile owner.");
15458                 if (isManagedProfile(userId)) {
15459                     throw new SecurityException("Managed profile cannot disable status bar");
15460                 }
15461             }
15462             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_STATUS_BAR_DISABLED);
15463 
15464             DevicePolicyData policy = getUserData(userId);
15465             if (policy.mStatusBarDisabled != disabled) {
15466                 boolean isLockTaskMode = false;
15467                 try {
15468                     isLockTaskMode = mInjector.getIActivityTaskManager().getLockTaskModeState()
15469                             != LOCK_TASK_MODE_NONE;
15470                 } catch (RemoteException e) {
15471                     Slogf.e(LOG_TAG, "Failed to get LockTask mode");
15472                 }
15473                 if (!isLockTaskMode) {
15474                     if (!setStatusBarDisabledInternal(disabled, userId)) {
15475                         return false;
15476                     }
15477                 }
15478                 policy.mStatusBarDisabled = disabled;
15479                 saveSettingsLocked(userId);
15480             }
15481         }
15482         DevicePolicyEventLogger
15483                 .createEvent(DevicePolicyEnums.SET_STATUS_BAR_DISABLED)
15484                 .setAdmin(caller.getPackageName())
15485                 .setBoolean(disabled)
15486                 .write();
15487         return true;
15488     }
15489 
setStatusBarDisabledInternal(boolean disabled, int userId)15490     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
15491         long ident = mInjector.binderClearCallingIdentity();
15492         try {
15493             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
15494                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
15495             if (statusBarService != null) {
15496                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
15497                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
15498                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
15499                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
15500                 return true;
15501             }
15502         } catch (RemoteException e) {
15503             Slogf.e(LOG_TAG, "Failed to disable the status bar", e);
15504         } finally {
15505             mInjector.binderRestoreCallingIdentity(ident);
15506         }
15507         return false;
15508     }
15509 
15510     @Override
isStatusBarDisabled(String callerPackage)15511     public boolean isStatusBarDisabled(String callerPackage) {
15512         final CallerIdentity caller = getCallerIdentity(callerPackage);
15513         if (isUnicornFlagEnabled()) {
15514             enforceCanQuery(
15515                     MANAGE_DEVICE_POLICY_STATUS_BAR, caller.getPackageName(), caller.getUserId());
15516         } else {
15517             Preconditions.checkCallAuthorization(
15518                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
15519         }
15520 
15521         int userId = caller.getUserId();
15522         synchronized (getLockObject()) {
15523             if (!isUnicornFlagEnabled()) {
15524                 Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
15525                         "Admin " + callerPackage
15526                                 + " is neither the device owner or affiliated user's profile owner.");
15527                 if (isManagedProfile(userId)) {
15528                     throw new SecurityException("Managed profile cannot disable status bar");
15529                 }
15530             }
15531             DevicePolicyData policy = getUserData(userId);
15532             return policy.mStatusBarDisabled;
15533         }
15534     }
15535 
15536     /**
15537      * We need to update the internal state of whether a user has completed setup or a
15538      * device has paired once. After that, we ignore any changes that reset the
15539      * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
15540      * as we don't trust any apps that might try to reset them.
15541      * <p>
15542      * Unfortunately, we don't know which user's setup state was changed, so we write all of
15543      * them.
15544      */
updateUserSetupCompleteAndPaired()15545     void updateUserSetupCompleteAndPaired() {
15546         List<UserInfo> users = mUserManager.getAliveUsers();
15547         final int N = users.size();
15548         for (int i = 0; i < N; i++) {
15549             int userHandle = users.get(i).id;
15550             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
15551                     userHandle) != 0) {
15552                 DevicePolicyData policy = getUserData(userHandle);
15553                 if (!policy.mUserSetupComplete) {
15554                     policy.mUserSetupComplete = true;
15555                     if (userHandle == UserHandle.USER_SYSTEM) {
15556                         mStateCache.setDeviceProvisioned(true);
15557                     }
15558                     synchronized (getLockObject()) {
15559                         saveSettingsLocked(userHandle);
15560                     }
15561                 }
15562             }
15563             if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
15564                     userHandle) != 0) {
15565                 DevicePolicyData policy = getUserData(userHandle);
15566                 if (!policy.mPaired) {
15567                     policy.mPaired = true;
15568                     synchronized (getLockObject()) {
15569                         saveSettingsLocked(userHandle);
15570                     }
15571                 }
15572             }
15573         }
15574     }
15575 
15576     private class SetupContentObserver extends ContentObserver {
15577         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
15578                 Settings.Secure.USER_SETUP_COMPLETE);
15579         private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
15580         private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
15581                 Settings.Secure.DEFAULT_INPUT_METHOD);
15582 
15583         @GuardedBy("getLockObject()")
15584         private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
15585 
SetupContentObserver(Handler handler)15586         public SetupContentObserver(Handler handler) {
15587             super(handler);
15588         }
15589 
register()15590         void register() {
15591             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
15592             if (mIsWatch) {
15593                 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
15594             }
15595             mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
15596         }
15597 
15598         @GuardedBy("getLockObject()")
addPendingChangeByOwnerLocked(int userId)15599         private void addPendingChangeByOwnerLocked(int userId) {
15600             mUserIdsWithPendingChangesByOwner.add(userId);
15601         }
15602 
15603         @Override
onChange(boolean selfChange, Uri uri, int userId)15604         public void onChange(boolean selfChange, Uri uri, int userId) {
15605             if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
15606                 updateUserSetupCompleteAndPaired();
15607             } else if (mDefaultImeChanged.equals(uri)) {
15608                 synchronized (getLockObject()) {
15609                     if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
15610                         // This change notification was triggered by the owner changing the current
15611                         // IME. Ignore it.
15612                         mUserIdsWithPendingChangesByOwner.remove(userId);
15613                     } else {
15614                         // This change notification was triggered by the user manually changing the
15615                         // current IME.
15616                         getUserData(userId).mCurrentInputMethodSet = false;
15617                         saveSettingsLocked(userId);
15618                     }
15619                 }
15620             }
15621         }
15622     }
15623 
15624     private class DevicePolicyConstantsObserver extends ContentObserver {
15625         final Uri mConstantsUri =
15626                 Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS);
15627 
DevicePolicyConstantsObserver(Handler handler)15628         DevicePolicyConstantsObserver(Handler handler) {
15629             super(handler);
15630         }
15631 
register()15632         void register() {
15633             mInjector.registerContentObserver(
15634                     mConstantsUri, /* notifyForDescendents= */ false, this, UserHandle.USER_ALL);
15635         }
15636 
15637         @Override
onChange(boolean selfChange, Uri uri, int userId)15638         public void onChange(boolean selfChange, Uri uri, int userId) {
15639             mConstants = loadConstants();
15640             invalidateBinderCaches();
15641 
15642             mInjector.binderWithCleanCallingIdentity(() -> {
15643                 final Intent intent = new Intent(
15644                         DevicePolicyManager.ACTION_DEVICE_POLICY_CONSTANTS_CHANGED);
15645                 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
15646                 final List<UserInfo> users = mUserManager.getAliveUsers();
15647                 for (int i = 0; i < users.size(); i++) {
15648                     mContext.sendBroadcastAsUser(intent, UserHandle.of(users.get(i).id));
15649                 }
15650             });
15651         }
15652     }
15653 
15654     @VisibleForTesting
15655     final class LocalService extends DevicePolicyManagerInternal
15656             implements DevicePolicyManagerLiteInternal {
15657         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
15658 
15659         @Override
getCrossProfileWidgetProviders(int profileId)15660         public List<String> getCrossProfileWidgetProviders(int profileId) {
15661             synchronized (getLockObject()) {
15662                 if (mOwners == null) {
15663                     return Collections.emptyList();
15664                 }
15665                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
15666                 if (ownerComponent == null) {
15667                     return Collections.emptyList();
15668                 }
15669 
15670                 DevicePolicyData policy = getUserDataUnchecked(profileId);
15671                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
15672 
15673                 if (admin == null || admin.crossProfileWidgetProviders == null
15674                         || admin.crossProfileWidgetProviders.isEmpty()) {
15675                     return Collections.emptyList();
15676                 }
15677 
15678                 return admin.crossProfileWidgetProviders;
15679             }
15680         }
15681 
15682         @Override
addOnCrossProfileWidgetProvidersChangeListener( OnCrossProfileWidgetProvidersChangeListener listener)15683         public void addOnCrossProfileWidgetProvidersChangeListener(
15684                 OnCrossProfileWidgetProvidersChangeListener listener) {
15685             synchronized (getLockObject()) {
15686                 if (mWidgetProviderListeners == null) {
15687                     mWidgetProviderListeners = new ArrayList<>();
15688                 }
15689                 if (!mWidgetProviderListeners.contains(listener)) {
15690                     mWidgetProviderListeners.add(listener);
15691                 }
15692             }
15693         }
15694 
15695         @Override
getProfileOwnerOrDeviceOwnerSupervisionComponent( @onNull UserHandle userHandle)15696         public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
15697                 @NonNull UserHandle userHandle) {
15698             return DevicePolicyManagerService.this.getProfileOwnerOrDeviceOwnerSupervisionComponent(
15699                     userHandle);
15700         }
15701 
15702         @Override
isActiveDeviceOwner(int uid)15703         public boolean isActiveDeviceOwner(int uid) {
15704             return isDefaultDeviceOwner(new CallerIdentity(uid, null, null));
15705         }
15706 
15707         @Override
isActiveProfileOwner(int uid)15708         public boolean isActiveProfileOwner(int uid) {
15709             return isProfileOwner(new CallerIdentity(uid, null, null));
15710         }
15711 
15712         @Override
isActiveSupervisionApp(int uid)15713         public boolean isActiveSupervisionApp(int uid) {
15714             if (!isProfileOwner(new CallerIdentity(uid, null, null))) {
15715                 return false;
15716             }
15717             synchronized (getLockObject()) {
15718                 final ActiveAdmin admin = getProfileOwnerAdminLocked(UserHandle.getUserId(uid));
15719                 if (admin == null) {
15720                     return false;
15721                 }
15722 
15723                 return isSupervisionComponentLocked(admin.info.getComponent());
15724             }
15725         }
15726 
notifyCrossProfileProvidersChanged(int userId, List<String> packages)15727         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
15728             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
15729             synchronized (getLockObject()) {
15730                 listeners = new ArrayList<>(mWidgetProviderListeners);
15731             }
15732             final int listenerCount = listeners.size();
15733             for (int i = 0; i < listenerCount; i++) {
15734                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
15735                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
15736             }
15737         }
15738 
15739         @Override
createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin)15740         public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
15741             // This method is called from AM with its lock held, so don't take the DPMS lock.
15742             // b/29242568
15743 
15744             if (getEnforcingAdminAndUserDetailsInternal(userId, null) != null
15745                     || useDefaultIfNoAdmin) {
15746                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(userId);
15747             }
15748             return null;
15749         }
15750 
15751         @Override
createUserRestrictionSupportIntent(int userId, String userRestriction)15752         public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
15753             Intent intent = null;
15754             if (getEnforcingAdminAndUserDetailsInternal(userId, userRestriction) != null) {
15755                 intent = DevicePolicyManagerService.this.createShowAdminSupportIntent(userId);
15756                 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, userRestriction);
15757             }
15758             return intent;
15759         }
15760 
15761         @Override
isUserAffiliatedWithDevice(int userId)15762         public boolean isUserAffiliatedWithDevice(int userId) {
15763             return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
15764         }
15765 
15766         @Override
canSilentlyInstallPackage(String callerPackage, int callerUid)15767         public boolean canSilentlyInstallPackage(String callerPackage, int callerUid) {
15768             if (callerPackage == null) {
15769                 return false;
15770             }
15771 
15772             CallerIdentity caller = new CallerIdentity(callerUid, null, null);
15773             if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid))
15774                     && (isActiveProfileOwner(callerUid)
15775                     || isDefaultDeviceOwner(caller) || isFinancedDeviceOwner(caller))) {
15776                 // device owner or a profile owner affiliated with the device owner
15777                 return true;
15778             }
15779             return false;
15780         }
15781 
15782         @Override
reportSeparateProfileChallengeChanged(@serIdInt int userId)15783         public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) {
15784             mInjector.binderWithCleanCallingIdentity(() -> {
15785                 synchronized (getLockObject()) {
15786                     updateMaximumTimeToLockLocked(userId);
15787                     updatePasswordQualityCacheForUserGroup(userId);
15788                 }
15789             });
15790             DevicePolicyEventLogger
15791                     .createEvent(DevicePolicyEnums.SEPARATE_PROFILE_CHALLENGE_CHANGED)
15792                     .setBoolean(isSeparateProfileChallengeEnabled(userId))
15793                     .write();
15794             invalidateBinderCaches();
15795         }
15796 
15797         @Override
getPrintingDisabledReasonForUser(@serIdInt int userId)15798         public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) {
15799             synchronized (getLockObject()) {
15800                 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING,
15801                         UserHandle.of(userId))) {
15802                     Slogf.e(LOG_TAG, "printing is enabled for user %d", userId);
15803                     return null;
15804                 }
15805                 String ownerPackage = mOwners.getProfileOwnerPackage(userId);
15806                 if (ownerPackage == null) {
15807                     ownerPackage = mOwners.getDeviceOwnerPackageName();
15808                 }
15809                 final String packageName = ownerPackage;
15810                 PackageManager pm = mInjector.getPackageManager();
15811                 PackageInfo packageInfo = mInjector.binderWithCleanCallingIdentity(() -> {
15812                     try {
15813                         return pm.getPackageInfo(packageName, 0);
15814                     } catch (NameNotFoundException e) {
15815                         Slogf.e(LOG_TAG, "getPackageInfo error", e);
15816                         return null;
15817                     }
15818                 });
15819                 if (packageInfo == null) {
15820                     Slogf.e(LOG_TAG, "packageInfo is inexplicably null");
15821                     return null;
15822                 }
15823                 ApplicationInfo appInfo = packageInfo.applicationInfo;
15824                 if (appInfo == null) {
15825                     Slogf.e(LOG_TAG, "appInfo is inexplicably null");
15826                     return null;
15827                 }
15828                 CharSequence appLabel = pm.getApplicationLabel(appInfo);
15829                 if (appLabel == null) {
15830                     Slogf.e(LOG_TAG, "appLabel is inexplicably null");
15831                     return null;
15832                 }
15833                 return getUpdatableString(
15834                         PRINTING_DISABLED_NAMED_ADMIN,
15835                         R.string.printing_disabled_by,
15836                         appLabel);
15837             }
15838         }
15839 
15840         @Override
getDevicePolicyCache()15841         protected DevicePolicyCache getDevicePolicyCache() {
15842             return mPolicyCache;
15843         }
15844 
15845         @Override
getDeviceStateCache()15846         protected DeviceStateCache getDeviceStateCache() {
15847             return mStateCache;
15848         }
15849 
15850         @Override
getAllCrossProfilePackages(int userId)15851         public List<String> getAllCrossProfilePackages(int userId) {
15852             return DevicePolicyManagerService.this.getAllCrossProfilePackages(userId);
15853         }
15854 
15855         @Override
getDefaultCrossProfilePackages()15856         public List<String> getDefaultCrossProfilePackages() {
15857             return DevicePolicyManagerService.this.getDefaultCrossProfilePackages();
15858         }
15859 
15860         @Override
broadcastIntentToManifestReceivers( Intent intent, UserHandle parentHandle, boolean requiresPermission)15861         public void broadcastIntentToManifestReceivers(
15862                 Intent intent, UserHandle parentHandle, boolean requiresPermission) {
15863             Objects.requireNonNull(intent);
15864             Objects.requireNonNull(parentHandle);
15865             Slogf.i(LOG_TAG, "Sending %s broadcast to manifest receivers.", intent.getAction());
15866             broadcastIntentToCrossProfileManifestReceivers(
15867                     intent, parentHandle, requiresPermission);
15868             broadcastExplicitIntentToRoleHolder(
15869                     intent, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, parentHandle);
15870         }
15871 
15872         @Override
enforcePermission(String callerPackage, String permission, int targetUserId)15873         public void enforcePermission(String callerPackage, String permission, int targetUserId) {
15874             DevicePolicyManagerService.this.enforcePermission(permission, callerPackage,
15875                     targetUserId);
15876         }
15877 
15878         @Override
hasPermission(String callerPackage, String permission, int targetUserId)15879         public boolean hasPermission(String callerPackage, String permission, int targetUserId) {
15880             return DevicePolicyManagerService.this.hasPermission(permission, callerPackage,
15881                     targetUserId);
15882         }
15883 
broadcastIntentToCrossProfileManifestReceivers( Intent intent, UserHandle userHandle, boolean requiresPermission)15884         private void broadcastIntentToCrossProfileManifestReceivers(
15885                 Intent intent, UserHandle userHandle, boolean requiresPermission) {
15886             final int userId = userHandle.getIdentifier();
15887             try {
15888                 final List<ResolveInfo> receivers = mIPackageManager.queryIntentReceivers(
15889                         intent, /* resolvedType= */ null,
15890                         STOCK_PM_FLAGS, userId).getList();
15891                 for (ResolveInfo receiver : receivers) {
15892                     final String packageName = receiver.getComponentInfo().packageName;
15893                     if (checkCrossProfilePackagePermissions(packageName, userId,
15894                             requiresPermission)
15895                             || checkModifyQuietModePermission(packageName, userId)) {
15896                         Slogf.i(LOG_TAG, "Sending %s broadcast to %s.", intent.getAction(),
15897                                 packageName);
15898                         final Intent packageIntent = new Intent(intent)
15899                                 .setComponent(receiver.getComponentInfo().getComponentName())
15900                                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
15901                         mContext.sendBroadcastAsUser(packageIntent, userHandle);
15902                     }
15903                 }
15904             } catch (RemoteException ex) {
15905                 Slogf.w(LOG_TAG, "Cannot get list of broadcast receivers for %s because: %s.",
15906                         intent.getAction(), ex);
15907             }
15908         }
15909 
15910         /**
15911          * Checks whether the package {@code packageName} has the {@code MODIFY_QUIET_MODE}
15912          * permission granted for the user {@code userId}.
15913          */
checkModifyQuietModePermission(String packageName, @UserIdInt int userId)15914         private boolean checkModifyQuietModePermission(String packageName, @UserIdInt int userId) {
15915             try {
15916                 final int uid = Objects.requireNonNull(
15917                         mInjector.getPackageManager().getApplicationInfoAsUser(
15918                                 Objects.requireNonNull(packageName), /* flags= */ 0, userId)).uid;
15919                 return PackageManager.PERMISSION_GRANTED
15920                         == ActivityManager.checkComponentPermission(
15921                         android.Manifest.permission.MODIFY_QUIET_MODE, uid, /* owningUid= */
15922                         -1, /* exported= */ true);
15923             } catch (NameNotFoundException ex) {
15924                 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
15925                         packageName);
15926                 return false;
15927             }
15928         }
15929 
15930         /**
15931          * Checks whether the package {@code packageName} has the required permissions to receive
15932          * cross-profile broadcasts on behalf of the user {@code userId}.
15933          */
checkCrossProfilePackagePermissions(String packageName, @UserIdInt int userId, boolean requiresPermission)15934         private boolean checkCrossProfilePackagePermissions(String packageName,
15935                 @UserIdInt int userId, boolean requiresPermission) {
15936             final PackageManagerInternal pmInternal = LocalServices.getService(
15937                     PackageManagerInternal.class);
15938             final AndroidPackage androidPackage = pmInternal.getPackage(packageName);
15939             if (androidPackage == null || !androidPackage.isCrossProfile()) {
15940                 return false;
15941             }
15942             if (!requiresPermission) {
15943                 return true;
15944             }
15945             if (!isPackageEnabled(packageName, userId)) {
15946                 return false;
15947             }
15948             try {
15949                 final CrossProfileAppsInternal crossProfileAppsService = LocalServices.getService(
15950                         CrossProfileAppsInternal.class);
15951                 return crossProfileAppsService.verifyPackageHasInteractAcrossProfilePermission(
15952                         packageName, userId);
15953             } catch (NameNotFoundException ex) {
15954                 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
15955                         packageName);
15956                 return false;
15957             }
15958         }
15959 
isPackageEnabled(String packageName, @UserIdInt int userId)15960         private boolean isPackageEnabled(String packageName, @UserIdInt int userId) {
15961             final int callingUid = Binder.getCallingUid();
15962             final long ident = Binder.clearCallingIdentity();
15963             try {
15964                 final PackageInfo info = mInjector.getPackageManagerInternal()
15965                         .getPackageInfo(
15966                                 packageName,
15967                                 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
15968                                 callingUid,
15969                                 userId);
15970                 return info != null && info.applicationInfo.enabled;
15971             } finally {
15972                 Binder.restoreCallingIdentity(ident);
15973             }
15974         }
15975 
15976         @Override
getProfileOwnerAsUser(@serIdInt int userId)15977         public ComponentName getProfileOwnerAsUser(@UserIdInt int userId) {
15978             return DevicePolicyManagerService.this.getProfileOwnerAsUser(userId);
15979         }
15980 
15981         @Override
getDeviceOwnerComponent(boolean callingUserOnly)15982         public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
15983             return DevicePolicyManagerService.this.getDeviceOwnerComponent(callingUserOnly);
15984         }
15985 
15986         @Override
getDeviceOwnerUserId()15987         public int getDeviceOwnerUserId() {
15988             return DevicePolicyManagerService.this.getDeviceOwnerUserId();
15989         }
15990 
15991         @Override
isDeviceOrProfileOwnerInCallingUser(String packageName)15992         public boolean isDeviceOrProfileOwnerInCallingUser(String packageName) {
15993             return isDeviceOwnerInCallingUser(packageName)
15994                     || isProfileOwnerInCallingUser(packageName);
15995         }
15996 
isDeviceOwnerInCallingUser(String packageName)15997         private boolean isDeviceOwnerInCallingUser(String packageName) {
15998             final ComponentName deviceOwnerInCallingUser =
15999                     DevicePolicyManagerService.this.getDeviceOwnerComponent(
16000                             /* callingUserOnly= */ true);
16001             return deviceOwnerInCallingUser != null
16002                     && packageName.equals(deviceOwnerInCallingUser.getPackageName());
16003         }
16004 
isProfileOwnerInCallingUser(String packageName)16005         private boolean isProfileOwnerInCallingUser(String packageName) {
16006             final ComponentName profileOwnerInCallingUser =
16007                     getProfileOwnerAsUser(UserHandle.getCallingUserId());
16008             return profileOwnerInCallingUser != null
16009                     && packageName.equals(profileOwnerInCallingUser.getPackageName());
16010         }
16011 
16012         @Override
supportsResetOp(int op)16013         public boolean supportsResetOp(int op) {
16014             return op == AppOpsManager.OP_INTERACT_ACROSS_PROFILES
16015                     && LocalServices.getService(CrossProfileAppsInternal.class) != null;
16016         }
16017 
16018         @Override
resetOp(int op, String packageName, @UserIdInt int userId)16019         public void resetOp(int op, String packageName, @UserIdInt int userId) {
16020             if (op != AppOpsManager.OP_INTERACT_ACROSS_PROFILES) {
16021                 throw new IllegalArgumentException("Unsupported op for DPM reset: " + op);
16022             }
16023             LocalServices.getService(CrossProfileAppsInternal.class)
16024                     .setInteractAcrossProfilesAppOp(
16025                             packageName, findInteractAcrossProfilesResetMode(packageName), userId);
16026         }
16027 
16028         @Override
notifyUnsafeOperationStateChanged(DevicePolicySafetyChecker checker, int reason, boolean isSafe)16029         public void notifyUnsafeOperationStateChanged(DevicePolicySafetyChecker checker, int reason,
16030                 boolean isSafe) {
16031             // TODO(b/178494483): use EventLog instead
16032             // TODO(b/178494483): log metrics?
16033             if (VERBOSE_LOG) {
16034                 Slogf.v(LOG_TAG, "notifyUnsafeOperationStateChanged(): %s=%b",
16035                         DevicePolicyManager.operationSafetyReasonToString(reason), isSafe);
16036             }
16037             Preconditions.checkArgument(mSafetyChecker == checker,
16038                     "invalid checker: should be %s, was %s", mSafetyChecker, checker);
16039 
16040             Bundle extras = new Bundle();
16041             extras.putInt(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_REASON, reason);
16042             extras.putBoolean(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_STATE, isSafe);
16043 
16044             if (mOwners.hasDeviceOwner()) {
16045                 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying DO");
16046                 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED,
16047                         extras);
16048             }
16049             for (int profileOwnerId : mOwners.getProfileOwnerKeys()) {
16050                 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying PO for user " + profileOwnerId);
16051                 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED,
16052                         extras, profileOwnerId);
16053             }
16054         }
16055 
findInteractAcrossProfilesResetMode(String packageName)16056         private @Mode int findInteractAcrossProfilesResetMode(String packageName) {
16057             return getDefaultCrossProfilePackages().contains(packageName)
16058                     ? AppOpsManager.MODE_ALLOWED
16059                     : AppOpsManager.opToDefaultMode(AppOpsManager.OP_INTERACT_ACROSS_PROFILES);
16060         }
16061 
16062         @Override
isUserOrganizationManaged(@serIdInt int userHandle)16063         public boolean isUserOrganizationManaged(@UserIdInt int userHandle) {
16064             return getDeviceStateCache().isUserOrganizationManaged(userHandle);
16065         }
16066 
16067         @Override
getApplicationRestrictionsPerAdminForUser( String packageName, @UserIdInt int userId)16068         public List<Bundle> getApplicationRestrictionsPerAdminForUser(
16069                 String packageName, @UserIdInt int userId) {
16070             if (UserHandle.getCallingUserId() != userId
16071                     || !UserHandle.isSameApp(
16072                     Binder.getCallingUid(), getUidForPackage(packageName, userId))) {
16073                 final int uid = Binder.getCallingUid();
16074                 if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
16075                     throw new SecurityException("Only system may: get application restrictions for "
16076                             + "other user/app " + packageName);
16077                 }
16078             }
16079             LinkedHashMap<EnforcingAdmin, PolicyValue<Bundle>> policies =
16080                     mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
16081                             PolicyDefinition.APPLICATION_RESTRICTIONS(packageName),
16082                             userId);
16083             List<Bundle> restrictions = new ArrayList<>();
16084             for (PolicyValue<Bundle> policyValue: policies.values()) {
16085                 Bundle value = policyValue.getValue();
16086                 // Probably not necessary since setApplicationRestrictions only sets non-empty
16087                 // Bundle, but just in case.
16088                 if (value != null && !value.isEmpty()) {
16089                     restrictions.add(value);
16090                 }
16091             }
16092 
16093             return mInjector.binderWithCleanCallingIdentity(() -> {
16094                 // Could be a device that has a DPC that hasn't migrated yet, so also return any
16095                 // restrictions saved in userManager.
16096                 Bundle bundle = mUserManager.getApplicationRestrictions(
16097                         packageName, UserHandle.of(userId));
16098                 if (bundle != null && !bundle.isEmpty()) {
16099                     restrictions.add(bundle);
16100                 }
16101                 return restrictions;
16102             });
16103         }
16104 
getUserRestrictionSources(String restriction, @UserIdInt int userId)16105         public List<EnforcingUser> getUserRestrictionSources(String restriction,
16106                 @UserIdInt int userId) {
16107             PolicyDefinition<Boolean> policy =
16108                     PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction);
16109 
16110             Set<EnforcingAdmin> localAdmins =
16111                     mDevicePolicyEngine.getLocalPoliciesSetByAdmins(policy, userId).keySet();
16112 
16113             Set<EnforcingAdmin> globalAdmins =
16114                     mDevicePolicyEngine.getGlobalPoliciesSetByAdmins(policy).keySet();
16115 
16116             List<EnforcingUser> enforcingUsers = new ArrayList();
16117             enforcingUsers.addAll(getEnforcingUsers(localAdmins));
16118             enforcingUsers.addAll(getEnforcingUsers(globalAdmins));
16119             return enforcingUsers;
16120         }
16121 
16122         @Override
enforceSecurityLoggingPolicy(boolean enabled)16123         public void enforceSecurityLoggingPolicy(boolean enabled) {
16124             if (!Flags.securityLogV2Enabled()) {
16125                 return;
16126             }
16127             Boolean auditLoggingEnabled = mDevicePolicyEngine.getResolvedPolicy(
16128                     PolicyDefinition.AUDIT_LOGGING, UserHandle.USER_ALL);
16129             enforceLoggingPolicy(enabled, Boolean.TRUE.equals(auditLoggingEnabled));
16130         }
16131 
16132         @Override
enforceAuditLoggingPolicy(boolean enabled)16133         public void enforceAuditLoggingPolicy(boolean enabled) {
16134             if (!Flags.securityLogV2Enabled()) {
16135                 return;
16136             }
16137             Boolean securityLoggingEnabled = mDevicePolicyEngine.getResolvedPolicy(
16138                     PolicyDefinition.SECURITY_LOGGING, UserHandle.USER_ALL);
16139             enforceLoggingPolicy(Boolean.TRUE.equals(securityLoggingEnabled), enabled);
16140         }
16141 
getEnforcingUsers(Set<EnforcingAdmin> admins)16142         private List<EnforcingUser> getEnforcingUsers(Set<EnforcingAdmin> admins) {
16143             List<EnforcingUser> enforcingUsers = new ArrayList();
16144             ComponentName deviceOwner = mOwners.getDeviceOwnerComponent();
16145             for (EnforcingAdmin admin : admins) {
16146                 if (deviceOwner != null
16147                         && deviceOwner.getPackageName().equals(admin.getPackageName())) {
16148                     enforcingUsers.add(new EnforcingUser(admin.getUserId(),
16149                             UserManager.RESTRICTION_SOURCE_DEVICE_OWNER));
16150                 } else {
16151                     enforcingUsers.add(new EnforcingUser(admin.getUserId(),
16152                             UserManager.RESTRICTION_SOURCE_PROFILE_OWNER));
16153                 }
16154             }
16155             return enforcingUsers;
16156         }
16157     }
16158 
enforceLoggingPolicy( boolean securityLogEnabled, boolean auditLogEnabled)16159     private void enforceLoggingPolicy(
16160             boolean securityLogEnabled, boolean auditLogEnabled) {
16161         Slogf.i(LOG_TAG, "Enforcing logging policy, security: %b audit: %b",
16162                 securityLogEnabled, auditLogEnabled);
16163         mInjector.securityLogSetLoggingEnabledProperty(securityLogEnabled || auditLogEnabled);
16164         setLoggingConfiguration(securityLogEnabled, auditLogEnabled);
16165     }
16166 
setLoggingConfiguration( boolean securityLoggingEnabled, boolean auditLoggingEnabled)16167     private void setLoggingConfiguration(
16168             boolean securityLoggingEnabled, boolean auditLoggingEnabled) {
16169         final int loggingEnabledUser = getSecurityLoggingEnabledUser();
16170         mSecurityLogMonitor.setLoggingParams(
16171                 loggingEnabledUser, securityLoggingEnabled, auditLoggingEnabled);
16172         if (securityLoggingEnabled || auditLoggingEnabled) {
16173             synchronized (getLockObject()) {
16174                 maybePauseDeviceWideLoggingLocked();
16175             }
16176         }
16177     }
16178 
createShowAdminSupportIntent(int userId)16179     private Intent createShowAdminSupportIntent(int userId) {
16180         // This method is called with AMS lock held, so don't take DPMS lock
16181         final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
16182         intent.putExtra(Intent.EXTRA_USER_ID, userId);
16183         intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
16184         return intent;
16185     }
16186 
16187     /**
16188      * @param restriction The restriction enforced by admin. It could be any user restriction or
16189      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA},
16190      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE} and  {@link
16191      *                    DevicePolicyManager#POLICY_SUSPEND_PACKAGES}.
16192      */
getEnforcingAdminAndUserDetailsInternal(int userId, String restriction)16193     private Bundle getEnforcingAdminAndUserDetailsInternal(int userId, String restriction) {
16194         Bundle result = null;
16195 
16196         // For POLICY_SUSPEND_PACKAGES return PO or DO to keep the behavior same as
16197         // before the bug fix for b/192245204.
16198         if (restriction == null || DevicePolicyManager.POLICY_SUSPEND_PACKAGES.equals(
16199                 restriction)) {
16200             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
16201             if (profileOwner != null) {
16202                 result = new Bundle();
16203                 result.putInt(Intent.EXTRA_USER_ID, userId);
16204                 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16205                         profileOwner);
16206                 return result;
16207             }
16208             final Pair<Integer, ComponentName> deviceOwner =
16209                     mOwners.getDeviceOwnerUserIdAndComponent();
16210             if (deviceOwner != null && deviceOwner.first == userId) {
16211                 result = new Bundle();
16212                 result.putInt(Intent.EXTRA_USER_ID, userId);
16213                 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16214                         deviceOwner.second);
16215                 return result;
16216             }
16217         } else if (DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
16218             Boolean value = mDevicePolicyEngine.getResolvedPolicy(
16219                     PolicyDefinition.SCREEN_CAPTURE_DISABLED, userId);
16220             if (value != null && value) {
16221                 result = new Bundle();
16222                 result.putInt(Intent.EXTRA_USER_ID, userId);
16223                 return result;
16224             }
16225         } else if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
16226             PolicyDefinition<Boolean> policyDefinition =
16227                     PolicyDefinition.getPolicyDefinitionForUserRestriction(
16228                             UserManager.DISALLOW_CAMERA);
16229             Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
16230             if (value != null && value) {
16231                 result = new Bundle();
16232                 result.putInt(Intent.EXTRA_USER_ID, userId);
16233                 return result;
16234             }
16235         } else {
16236             long ident = mInjector.binderClearCallingIdentity();
16237             try {
16238                 if (getEnforcingAdminsForRestrictionInternal(userId, restriction).size() == 0) {
16239                     return null;
16240                 }
16241 
16242                 ActiveAdmin admin = getMostProbableDPCAdminForLocalPolicy(userId);
16243                 if (admin != null) {
16244                     result = new Bundle();
16245                     result.putInt(Intent.EXTRA_USER_ID, admin.getUserHandle().getIdentifier());
16246                     result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
16247                             admin.info.getComponent());
16248                     return result;
16249                 }
16250                 return null;
16251             } finally {
16252                 mInjector.binderRestoreCallingIdentity(ident);
16253             }
16254         }
16255         return null;
16256     }
16257 
16258     /**
16259      * @param restriction The restriction enforced by admin. It could be any user restriction or
16260      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA},
16261      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE} and  {@link
16262      *                    DevicePolicyManager#POLICY_SUSPEND_PACKAGES}.
16263      */
getEnforcingAdminsForRestrictionInternal( int userId, @NonNull String restriction)16264     private Set<android.app.admin.EnforcingAdmin> getEnforcingAdminsForRestrictionInternal(
16265             int userId, @NonNull String restriction) {
16266         Objects.requireNonNull(restriction);
16267         Set<android.app.admin.EnforcingAdmin> admins = new HashSet<>();
16268         // For POLICY_SUSPEND_PACKAGES return PO or DO to keep the behavior same as
16269         // before the bug fix for b/192245204.
16270         if (DevicePolicyManager.POLICY_SUSPEND_PACKAGES.equals(
16271                 restriction)) {
16272             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
16273             if (profileOwner != null) {
16274                 EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
16275                         profileOwner, userId);
16276                 admins.add(admin.getParcelableAdmin());
16277                 return admins;
16278             }
16279             final Pair<Integer, ComponentName> deviceOwner =
16280                     mOwners.getDeviceOwnerUserIdAndComponent();
16281             if (deviceOwner != null && deviceOwner.first == userId) {
16282                 EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
16283                         deviceOwner.second, deviceOwner.first);
16284                 admins.add(admin.getParcelableAdmin());
16285                 return admins;
16286             }
16287         } else {
16288             long ident = mInjector.binderClearCallingIdentity();
16289             try {
16290                 PolicyDefinition<Boolean> policyDefinition = getPolicyDefinitionForRestriction(
16291                         restriction);
16292                 Boolean value = mDevicePolicyEngine.getResolvedPolicy(policyDefinition, userId);
16293                 if (value != null && value) {
16294                     Map<EnforcingAdmin, PolicyValue<Boolean>> globalPolicies =
16295                             mDevicePolicyEngine.getGlobalPoliciesSetByAdmins(policyDefinition);
16296                     for (EnforcingAdmin admin : globalPolicies.keySet()) {
16297                         if (globalPolicies.get(admin) != null
16298                                 && Boolean.TRUE.equals(globalPolicies.get(admin).getValue())) {
16299                             admins.add(admin.getParcelableAdmin());
16300                         }
16301                     }
16302 
16303                     Map<EnforcingAdmin, PolicyValue<Boolean>> localPolicies =
16304                             mDevicePolicyEngine.getLocalPoliciesSetByAdmins(
16305                                     policyDefinition, userId);
16306                     for (EnforcingAdmin admin : localPolicies.keySet()) {
16307                         if (localPolicies.get(admin) != null
16308                                 && Boolean.TRUE.equals(localPolicies.get(admin).getValue())) {
16309                             admins.add(admin.getParcelableAdmin());
16310                         }
16311                     }
16312                     return admins;
16313                 }
16314             } finally {
16315                 mInjector.binderRestoreCallingIdentity(ident);
16316             }
16317         }
16318         return admins;
16319     }
16320 
getPolicyDefinitionForRestriction( @onNull String restriction)16321     private static PolicyDefinition<Boolean> getPolicyDefinitionForRestriction(
16322             @NonNull String restriction) {
16323         Objects.requireNonNull(restriction);
16324         if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
16325             return PolicyDefinition.getPolicyDefinitionForUserRestriction(
16326                     UserManager.DISALLOW_CAMERA);
16327         } else if (DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
16328             return PolicyDefinition.SCREEN_CAPTURE_DISABLED;
16329         } else {
16330             return PolicyDefinition.getPolicyDefinitionForUserRestriction(restriction);
16331         }
16332     }
16333 
userRestrictionSourceToString(@serRestrictionSource int source)16334     private static String userRestrictionSourceToString(@UserRestrictionSource int source) {
16335         return DebugUtils.flagsToString(UserManager.class, "RESTRICTION_", source);
16336     }
16337 
16338     /**
16339      * @param restriction The restriction enforced by admin. It could be any user restriction or
16340      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
16341      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
16342      * @return Details of admin and user which enforced the restriction for the userId.
16343      */
16344     @Override
getEnforcingAdminAndUserDetails(int userId, String restriction)16345     public Bundle getEnforcingAdminAndUserDetails(int userId, String restriction) {
16346         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()));
16347         return getEnforcingAdminAndUserDetailsInternal(userId, restriction);
16348     }
16349 
16350     @Override
getEnforcingAdminsForRestriction( int userId, String restriction)16351     public List<android.app.admin.EnforcingAdmin> getEnforcingAdminsForRestriction(
16352             int userId, String restriction) {
16353         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()));
16354         return new ArrayList<>(getEnforcingAdminsForRestrictionInternal(userId, restriction));
16355     }
16356 
16357     /**
16358      * @param restriction The restriction enforced by admin. It could be any user restriction or
16359      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
16360      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
16361      */
16362     @Override
createAdminSupportIntent(String restriction)16363     public Intent createAdminSupportIntent(String restriction) {
16364         Objects.requireNonNull(restriction);
16365         final CallerIdentity caller = getCallerIdentity();
16366         final int userId = caller.getUserId();
16367         Intent intent = null;
16368         if (getEnforcingAdminAndUserDetailsInternal(userId, restriction) != null) {
16369             intent = createShowAdminSupportIntent(userId);
16370             intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
16371         }
16372         return intent;
16373     }
16374 
16375     /**
16376      * Returns true if specified admin is allowed to limit passwords and has a
16377      * {@code mPasswordPolicy.quality} of at least {@code minPasswordQuality}
16378      */
isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality)16379     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
16380         if (admin.mPasswordPolicy.quality < minPasswordQuality) {
16381             return false;
16382         }
16383         return admin.isPermissionBased || admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
16384     }
16385 
16386     @Override
setCredentialManagerPolicy(PackagePolicy policy)16387     public void setCredentialManagerPolicy(PackagePolicy policy) {
16388         if (!mHasFeature) {
16389             return;
16390         }
16391         final CallerIdentity caller = getCallerIdentity();
16392         Preconditions.checkCallAuthorization(canWriteCredentialManagerPolicy(caller));
16393 
16394         synchronized (getLockObject()) {
16395             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
16396             if (Objects.equals(admin.mCredentialManagerPolicy, policy)) {
16397                 return;
16398             }
16399 
16400             admin.mCredentialManagerPolicy = policy;
16401             saveSettingsLocked(caller.getUserId());
16402         }
16403     }
16404 
canWriteCredentialManagerPolicy(CallerIdentity caller)16405     private boolean canWriteCredentialManagerPolicy(CallerIdentity caller) {
16406         return (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))
16407                         || isDefaultDeviceOwner(caller)
16408                         || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS);
16409     }
16410 
16411     @Override
getCredentialManagerPolicy(int userId)16412     public PackagePolicy getCredentialManagerPolicy(int userId) {
16413         if (!mHasFeature) {
16414             return null;
16415         }
16416         final CallerIdentity caller = getCallerIdentity();
16417         Preconditions.checkCallAuthorization(
16418                 canWriteCredentialManagerPolicy(caller) || canQueryAdminPolicy(caller));
16419         if (userId != caller.getUserId()) {
16420             Preconditions.checkCallAuthorization(
16421                     hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS));
16422         }
16423 
16424         synchronized (getLockObject()) {
16425             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userId);
16426             return (admin != null) ? admin.mCredentialManagerPolicy : null;
16427         }
16428     }
16429 
16430     @Override
setSystemUpdatePolicy( ComponentName who, String callerPackageName, SystemUpdatePolicy policy)16431     public void setSystemUpdatePolicy(
16432             ComponentName who, String callerPackageName, SystemUpdatePolicy policy) {
16433         if (policy != null) {
16434             // throws exception if policy type is invalid
16435             policy.validateType();
16436             // throws exception if freeze period is invalid
16437             policy.validateFreezePeriods();
16438             Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
16439             // throws exception if freeze period is incompatible with previous freeze period record
16440             policy.validateAgainstPreviousFreezePeriod(record.first, record.second,
16441                     LocalDate.now());
16442         }
16443         CallerIdentity caller;
16444 
16445         synchronized (getLockObject()) {
16446             if (isPermissionCheckFlagEnabled()) {
16447                 caller = getCallerIdentity(who, callerPackageName);
16448                 enforcePermission(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, caller.getPackageName(),
16449                         UserHandle.USER_ALL);
16450             } else {
16451                 caller = getCallerIdentity(who);
16452                 Preconditions.checkCallAuthorization(
16453                         isProfileOwnerOfOrganizationOwnedDevice(caller)
16454                         || isDefaultDeviceOwner(caller));
16455             }
16456 
16457             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_UPDATE_POLICY);
16458 
16459             if (policy == null) {
16460                 mOwners.clearSystemUpdatePolicy();
16461             } else {
16462                 mOwners.setSystemUpdatePolicy(policy);
16463                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false);
16464             }
16465             mOwners.writeDeviceOwner();
16466         }
16467         mInjector.binderWithCleanCallingIdentity(() -> mContext.sendBroadcastAsUser(
16468                 new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM));
16469         DevicePolicyEventLogger
16470                 .createEvent(DevicePolicyEnums.SET_SYSTEM_UPDATE_POLICY)
16471                 .setAdmin(caller.getPackageName())
16472                 .setInt(policy != null ? policy.getPolicyType() : 0)
16473                 .write();
16474     }
16475 
16476     @Override
getSystemUpdatePolicy()16477     public SystemUpdatePolicy getSystemUpdatePolicy() {
16478         synchronized (getLockObject()) {
16479             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
16480             if (policy != null && !policy.isValid()) {
16481                 Slogf.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
16482                 return null;
16483             }
16484             return policy;
16485         }
16486     }
16487 
withinRange(Pair<LocalDate, LocalDate> range, LocalDate date)16488     private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) {
16489         return (!date.isBefore(range.first) && !date.isAfter(range.second));
16490     }
16491 
16492     /**
16493      * keeps track of the last continuous period when the system is under OTA freeze.
16494      *
16495      * DPMS keeps track of the previous dates during which OTA was freezed as a result of an
16496      * system update policy with freeze periods in effect. This is needed to make robust
16497      * validation on new system update polices, for example to prevent the OTA from being
16498      * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period
16499      * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting
16500      * a new freeze period after a few days.
16501      *
16502      * @param saveIfChanged whether to persist the result on disk if freeze period record is
16503      *            updated. This should only be set to {@code false} if there is a guaranteed
16504      *            mOwners.writeDeviceOwner() later in the control flow to reduce the number of
16505      *            disk writes. Otherwise you risk inconsistent on-disk state.
16506      *
16507      * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod
16508      */
updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged)16509     private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) {
16510         Slogf.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord");
16511         synchronized (getLockObject()) {
16512             final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
16513             if (policy == null) {
16514                 return;
16515             }
16516             final LocalDate now = LocalDate.now();
16517             final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now);
16518             if (currentPeriod == null) {
16519                 return;
16520             }
16521             final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
16522             final LocalDate start = record.first;
16523             final LocalDate end = record.second;
16524             final boolean changed;
16525             if (end == null || start == null) {
16526                 // Start a new period if there is none at the moment
16527                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
16528             } else if (now.equals(end.plusDays(1))) {
16529                 // Extend the existing period
16530                 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
16531             } else if (now.isAfter(end.plusDays(1))) {
16532                 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) {
16533                     // The device might be off for some period. If the past freeze record
16534                     // is within range of the current freeze period, assume the device was off
16535                     // during the period [end, now] and extend the freeze record to [start, now].
16536                     changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
16537                 } else {
16538                     changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
16539                 }
16540             } else if (now.isBefore(start)) {
16541                 // Systm clock was adjusted backwards, restart record
16542                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
16543             } else /* start <= now <= end */ {
16544                 changed = false;
16545             }
16546             if (changed && saveIfChanged) {
16547                 mOwners.writeDeviceOwner();
16548             }
16549         }
16550     }
16551 
16552     @Override
clearSystemUpdatePolicyFreezePeriodRecord()16553     public void clearSystemUpdatePolicyFreezePeriodRecord() {
16554         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
16555                         || hasCallingOrSelfPermission(permission.CLEAR_FREEZE_PERIOD),
16556                 "Caller must be shell, or hold CLEAR_FREEZE_PERIOD permission to call "
16557                         + "clearSystemUpdatePolicyFreezePeriodRecord");
16558         synchronized (getLockObject()) {
16559             // Print out current record to help diagnosed CTS failures
16560             Slogf.i(LOG_TAG, "Clear freeze period record: "
16561                     + mOwners.getSystemUpdateFreezePeriodRecordAsString());
16562             if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) {
16563                 mOwners.writeDeviceOwner();
16564             }
16565         }
16566     }
16567 
16568     /**
16569      * Checks if any of the packages associated with the UID of the app provided is that
16570      * of the device owner.
16571      * @param appUid UID of the app to check.
16572      * @return {@code true} if any of the packages are the device owner, {@code false} otherwise.
16573      */
isUidDeviceOwnerLocked(int appUid)16574     private boolean isUidDeviceOwnerLocked(int appUid) {
16575         ensureLocked();
16576         final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
16577                 .getPackageName();
16578         try {
16579             String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(appUid);
16580             if (pkgs == null) {
16581                 return false;
16582             }
16583 
16584             for (String pkg : pkgs) {
16585                 if (deviceOwnerPackageName.equals(pkg)) {
16586                     return true;
16587                 }
16588             }
16589         } catch (RemoteException e) {
16590             return false;
16591         }
16592         return false;
16593     }
16594 
16595     @Override
notifyPendingSystemUpdate(@ullable SystemUpdateInfo info)16596     public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
16597         Preconditions.checkCallAuthorization(
16598                 hasCallingOrSelfPermission(NOTIFY_PENDING_SYSTEM_UPDATE),
16599                 "Only the system update service can broadcast update information");
16600 
16601         mInjector.binderWithCleanCallingIdentity(() -> {
16602             if (!mUserManager.getUserInfo(UserHandle.getCallingUserId()).isMain()) {
16603                 Slogf.w(LOG_TAG, "Only the system update service in the main user can broadcast "
16604                         + "update information.");
16605                 return;
16606             }
16607         });
16608 
16609         if (!mOwners.saveSystemUpdateInfo(info)) {
16610             // Pending system update hasn't changed, don't send duplicate notification.
16611             return;
16612         }
16613 
16614         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
16615                 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
16616                         info == null ? -1 : info.getReceivedTime());
16617 
16618         mInjector.binderWithCleanCallingIdentity(() -> {
16619             synchronized (getLockObject()) {
16620                 // Broadcast to device owner first if there is one.
16621                 if (mOwners.hasDeviceOwner()) {
16622                     final UserHandle deviceOwnerUser =
16623                             UserHandle.of(mOwners.getDeviceOwnerUserId());
16624                     intent.setComponent(mOwners.getDeviceOwnerComponent());
16625                     mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
16626                 }
16627             }
16628             // Get running users.
16629             final int runningUserIds[];
16630             try {
16631                 runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
16632             } catch (RemoteException e) {
16633                 // Shouldn't happen.
16634                 Slogf.e(LOG_TAG, "Could not retrieve the list of running users", e);
16635                 return;
16636             }
16637             // Send broadcasts to corresponding profile owners if any.
16638             for (final int userId : runningUserIds) {
16639                 final ComponentName profileOwnerPackage;
16640                 synchronized (getLockObject()) {
16641                     profileOwnerPackage = mOwners.getProfileOwnerComponent(userId);
16642                 }
16643                 if (profileOwnerPackage != null) {
16644                     intent.setComponent(profileOwnerPackage);
16645                     mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
16646                 }
16647 
16648                 if (Flags.permissionMigrationForZeroTrustImplEnabled()) {
16649                     final UserHandle user = UserHandle.of(userId);
16650                     final String roleHolderPackage = getRoleHolderPackageNameOnUser(
16651                             RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, userId);
16652                     if (roleHolderPackage != null) {
16653                         broadcastExplicitIntentToPackage(intent, roleHolderPackage, user);
16654                     }
16655                 }
16656             }
16657         });
16658     }
16659 
16660     @Override
getPendingSystemUpdate(ComponentName admin, String callerPackage)16661     public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin, String callerPackage) {
16662         if (Flags.permissionMigrationForZeroTrustImplEnabled()) {
16663             CallerIdentity caller = getCallerIdentity(admin, callerPackage);
16664             enforcePermissions(new String[] {NOTIFY_PENDING_SYSTEM_UPDATE,
16665                     MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES}, caller.getPackageName(),
16666                     caller.getUserId());
16667         } else {
16668             Objects.requireNonNull(admin, "ComponentName is null");
16669 
16670             final CallerIdentity caller = getCallerIdentity(admin);
16671             Preconditions.checkCallAuthorization(
16672                     isDefaultDeviceOwner(caller) || isProfileOwner(caller));
16673         }
16674         return mOwners.getSystemUpdateInfo();
16675     }
16676 
16677     @Override
setPermissionPolicy(ComponentName admin, String callerPackage, int policy)16678     public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) {
16679         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
16680         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
16681                 && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)))
16682                 || (caller.hasPackage() && isCallerDelegate(caller,
16683                 DELEGATION_PERMISSION_GRANT)));
16684         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_POLICY);
16685 
16686         final int forUser = caller.getUserId();
16687         synchronized (getLockObject()) {
16688             DevicePolicyData userPolicy = getUserData(forUser);
16689             if (userPolicy.mPermissionPolicy != policy) {
16690                 userPolicy.mPermissionPolicy = policy;
16691                 mPolicyCache.setPermissionPolicy(forUser, policy);
16692                 saveSettingsLocked(forUser);
16693             }
16694         }
16695         DevicePolicyEventLogger
16696                 .createEvent(DevicePolicyEnums.SET_PERMISSION_POLICY)
16697                 .setAdmin(caller.getPackageName())
16698                 .setInt(policy)
16699                 .setBoolean(/* isDelegate */ admin == null)
16700                 .write();
16701     }
16702 
updatePermissionPolicyCache(int userId)16703     private void updatePermissionPolicyCache(int userId) {
16704         synchronized (getLockObject()) {
16705             DevicePolicyData userPolicy = getUserData(userId);
16706             mPolicyCache.setPermissionPolicy(userId, userPolicy.mPermissionPolicy);
16707         }
16708     }
16709 
16710     @Override
getPermissionPolicy(ComponentName admin)16711     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
16712         int userId = UserHandle.getCallingUserId();
16713         return mPolicyCache.getPermissionPolicy(userId);
16714     }
16715 
16716     @Override
setPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission, int grantState, RemoteCallback callback)16717     public void setPermissionGrantState(ComponentName admin, String callerPackage,
16718             String packageName, String permission, int grantState, RemoteCallback callback)
16719             throws RemoteException {
16720         Objects.requireNonNull(callback);
16721 
16722         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
16723         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_GRANT_STATE);
16724 
16725         synchronized (getLockObject()) {
16726             if (isFinancedDeviceOwner(caller)) {
16727                 enforcePermissionGrantStateOnFinancedDevice(packageName, permission);
16728             }
16729         }
16730         EnforcingAdmin enforcingAdmin;
16731         if (isUnicornFlagEnabled()) {
16732             enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
16733                     admin,
16734                     MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
16735                     callerPackage,
16736                     caller.getUserId());
16737             if (SENSOR_PERMISSIONS.contains(permission)
16738                     && grantState == PERMISSION_GRANT_STATE_GRANTED
16739                     && !canAdminGrantSensorsPermissions()) {
16740                 if (mInjector.isChangeEnabled(THROW_SECURITY_EXCEPTION_FOR_SENSOR_PERMISSIONS,
16741                         caller.getPackageName(), caller.getUserId())) {
16742                     throw new SecurityException(
16743                             "Caller not permitted to grant sensor permissions.");
16744                 } else {
16745                     // This is to match the legacy behaviour.
16746                     callback.sendResult(Bundle.EMPTY);
16747                     return;
16748                 }
16749             }
16750             // Check all the states where Exceptions aren't thrown but the permission
16751             // isn't granted either.
16752             if (!canGrantPermission(caller, permission, packageName)) {
16753                 callback.sendResult(null);
16754                 return;
16755             }
16756         } else {
16757             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
16758                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)
16759                     || isFinancedDeviceOwner(caller)))
16760                     || (caller.hasPackage() && isCallerDelegate(caller,
16761                     DELEGATION_PERMISSION_GRANT)));
16762             if (SENSOR_PERMISSIONS.contains(permission)
16763                     && grantState == PERMISSION_GRANT_STATE_GRANTED
16764                     && !canAdminGrantSensorsPermissions()) {
16765                 if (mInjector.isChangeEnabled(THROW_SECURITY_EXCEPTION_FOR_SENSOR_PERMISSIONS,
16766                         caller.getPackageName(), caller.getUserId())) {
16767                     throw new SecurityException(
16768                             "Caller not permitted to grant sensor permissions.");
16769                 } else {
16770                     Slogf.e(LOG_TAG, "Caller attempted to grant sensor permissions but denied");
16771                     // This is to match the legacy behaviour.
16772                     callback.sendResult(Bundle.EMPTY);
16773                     return;
16774                 }
16775             }
16776             synchronized (getLockObject()) {
16777                 long ident = mInjector.binderClearCallingIdentity();
16778                 try {
16779                     boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
16780                             >= android.os.Build.VERSION_CODES.Q;
16781                     if (!isPostQAdmin) {
16782                         // Legacy admins assume that they cannot control pre-M apps
16783                         if (getTargetSdk(packageName, caller.getUserId())
16784                                 < android.os.Build.VERSION_CODES.M) {
16785                             callback.sendResult(null);
16786                             return;
16787                         }
16788                     }
16789                     if (!isRuntimePermission(permission)) {
16790                         callback.sendResult(null);
16791                         return;
16792                     }
16793                 } catch (SecurityException e) {
16794                     Slogf.e(LOG_TAG, "Could not set permission grant state", e);
16795                     callback.sendResult(null);
16796                 } finally {
16797                     mInjector.binderRestoreCallingIdentity(ident);
16798                 }
16799             }
16800         }
16801         // TODO(b/278710449): enable when we stop policy enforecer callback from blocking the main
16802         //  thread
16803         if (false) {
16804             // TODO(b/266924257): decide how to handle the internal state if the package doesn't
16805             //  exist, or the permission isn't requested by the app, because we could end up with
16806             //  inconsistent state between the policy engine and package manager. Also a package
16807             //  might get removed or has it's permission updated after we've set the policy.
16808             if (grantState == PERMISSION_GRANT_STATE_DEFAULT) {
16809                 mDevicePolicyEngine.removeLocalPolicy(
16810                         PolicyDefinition.PERMISSION_GRANT(packageName, permission),
16811                         enforcingAdmin,
16812                         caller.getUserId());
16813             } else {
16814                 mDevicePolicyEngine.setLocalPolicy(
16815                         PolicyDefinition.PERMISSION_GRANT(packageName, permission),
16816                         enforcingAdmin,
16817                         new IntegerPolicyValue(grantState),
16818                         caller.getUserId());
16819             }
16820             int newState = mInjector.binderWithCleanCallingIdentity(() ->
16821                     getPermissionGrantStateForUser(
16822                             packageName, permission, caller, caller.getUserId()));
16823             if (newState == grantState) {
16824                 callback.sendResult(Bundle.EMPTY);
16825             } else {
16826                 callback.sendResult(null);
16827             }
16828         } else {
16829             synchronized (getLockObject()) {
16830                 long ident = mInjector.binderClearCallingIdentity();
16831                 try {
16832                     boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
16833                             >= android.os.Build.VERSION_CODES.Q;
16834                     if (grantState == PERMISSION_GRANT_STATE_GRANTED
16835                             || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED
16836                             || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
16837                         AdminPermissionControlParams permissionParams =
16838                                 new AdminPermissionControlParams(packageName, permission,
16839                                         grantState,
16840                                         canAdminGrantSensorsPermissions());
16841                         mInjector.getPermissionControllerManager(caller.getUserHandle())
16842                                 .setRuntimePermissionGrantStateByDeviceAdmin(
16843                                         caller.getPackageName(),
16844                                         permissionParams, mContext.getMainExecutor(),
16845                                         (permissionWasSet) -> {
16846                                             if (isPostQAdmin && !permissionWasSet) {
16847                                                 callback.sendResult(null);
16848                                                 return;
16849                                             }
16850                                             callback.sendResult(Bundle.EMPTY);
16851                                         });
16852                     }
16853                 } catch (SecurityException e) {
16854                     Slogf.e(LOG_TAG, "Could not set permission grant state", e);
16855 
16856                     callback.sendResult(null);
16857                 } finally {
16858                     mInjector.binderRestoreCallingIdentity(ident);
16859                 }
16860             }
16861         }
16862         DevicePolicyEventLogger.createEvent(DevicePolicyEnums.SET_PERMISSION_GRANT_STATE)
16863                 .setAdmin(caller.getPackageName())
16864                 .setStrings(permission)
16865                 .setInt(grantState)
16866                 .setBoolean(/* isDelegate */ isCallerDelegate(caller))
16867                 .write();
16868     }
16869 
16870     private static final List<String> SENSOR_PERMISSIONS = new ArrayList<>();
16871     {
16872         SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
16873         SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
16874         SENSOR_PERMISSIONS.add(Manifest.permission.ACCESS_COARSE_LOCATION);
16875         SENSOR_PERMISSIONS.add(Manifest.permission.CAMERA);
16876         SENSOR_PERMISSIONS.add(Manifest.permission.RECORD_AUDIO);
16877         SENSOR_PERMISSIONS.add(Manifest.permission.ACTIVITY_RECOGNITION);
16878         SENSOR_PERMISSIONS.add(Manifest.permission.BODY_SENSORS);
16879         SENSOR_PERMISSIONS.add(Manifest.permission.BACKGROUND_CAMERA);
16880         SENSOR_PERMISSIONS.add(Manifest.permission.RECORD_BACKGROUND_AUDIO);
16881         SENSOR_PERMISSIONS.add(Manifest.permission.BODY_SENSORS_BACKGROUND);
16882     }
16883 
canGrantPermission(CallerIdentity caller, String permission, String targetPackageName)16884     private boolean canGrantPermission(CallerIdentity caller, String permission,
16885             String targetPackageName) {
16886         boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
16887                 >= android.os.Build.VERSION_CODES.Q;
16888         if (!isPostQAdmin) {
16889             // Legacy admins assume that they cannot control pre-M apps
16890             if (getTargetSdk(targetPackageName, caller.getUserId())
16891                     < android.os.Build.VERSION_CODES.M) {
16892                 return false;
16893             }
16894         }
16895         if (!isRuntimePermission(permission)) {
16896             return false;
16897         }
16898         return true;
16899     }
16900 
enforcePermissionGrantStateOnFinancedDevice( String packageName, String permission)16901     private void enforcePermissionGrantStateOnFinancedDevice(
16902             String packageName, String permission) {
16903         if (!Manifest.permission.READ_PHONE_STATE.equals(permission)) {
16904             throw new SecurityException(permission + " cannot be used when managing a financed"
16905                     + " device for permission grant state");
16906         } else if (!mOwners.getDeviceOwnerPackageName().equals(packageName)) {
16907             throw new SecurityException("Device owner package is the only package that can be used"
16908                     + " for permission grant state when managing a financed device");
16909         }
16910     }
16911 
16912     @Override
getPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission)16913     public int getPermissionGrantState(ComponentName admin, String callerPackage,
16914             String packageName, String permission) throws RemoteException {
16915         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
16916         if (isUnicornFlagEnabled()) {
16917             enforceCanQuery(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, caller.getPackageName(),
16918                     caller.getUserId());
16919         } else {
16920             Preconditions.checkCallAuthorization(isSystemUid(caller) || (caller.hasAdminComponent()
16921                     && (isProfileOwner(caller) || isDefaultDeviceOwner(caller)
16922                     || isFinancedDeviceOwner(caller)))
16923                     || (caller.hasPackage() && isCallerDelegate(caller,
16924                     DELEGATION_PERMISSION_GRANT)));
16925         }
16926 
16927         synchronized (getLockObject()) {
16928             if (isFinancedDeviceOwner(caller)) {
16929                 enforcePermissionGrantStateOnFinancedDevice(packageName, permission);
16930             }
16931             return mInjector.binderWithCleanCallingIdentity(() -> getPermissionGrantStateForUser(
16932                     packageName, permission, caller, caller.getUserId()));
16933         }
16934     }
16935 
getPermissionGrantStateForUser( String packageName, String permission, CallerIdentity caller, int userId)16936     private int getPermissionGrantStateForUser(
16937             String packageName, String permission, CallerIdentity caller, int userId)
16938             throws RemoteException {
16939         int granted;
16940         if (getTargetSdk(caller.getPackageName(), caller.getUserId())
16941                 < android.os.Build.VERSION_CODES.Q) {
16942             // The per-Q behavior was to not check the app-ops state.
16943             granted = mIPackageManager.checkPermission(permission, packageName, userId);
16944         } else {
16945             try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
16946                 var packageState = snapshot.getPackageStates().get(packageName);
16947                 if (packageState == null) {
16948                     Slog.w(LOG_TAG, "Can't get permission state for missing package "
16949                             + packageName);
16950                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
16951                 } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
16952                     Slog.w(LOG_TAG, "Can't get permission state for uninstalled package "
16953                             + packageName);
16954                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
16955                 } else {
16956                     if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
16957                             PermissionChecker.PID_UNKNOWN,
16958                             UserHandle.getUid(userId, packageState.getAppId()), packageName)
16959                             != PermissionChecker.PERMISSION_GRANTED) {
16960                         granted = PackageManager.PERMISSION_DENIED;
16961                     } else {
16962                         granted = PackageManager.PERMISSION_GRANTED;
16963                     }
16964 
16965                 }
16966             }
16967         }
16968         int permFlags = mInjector.getPackageManager().getPermissionFlags(
16969                 permission, packageName, UserHandle.of(userId));
16970         if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
16971                 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
16972             // Not controlled by policy
16973             return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
16974         } else {
16975             // Policy controlled so return result based on permission grant state
16976             return granted == PackageManager.PERMISSION_GRANTED
16977                     ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
16978                     : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
16979         }
16980     }
16981 
isPackageInstalledForUser(String packageName, int userHandle)16982     boolean isPackageInstalledForUser(String packageName, int userHandle) {
16983         return mInjector.binderWithCleanCallingIdentity(() -> {
16984             try {
16985                 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
16986                         userHandle);
16987                 return (pi != null) && (pi.applicationInfo.flags != 0);
16988             } catch (RemoteException re) {
16989                 throw new RuntimeException("Package manager has died", re);
16990             }
16991         });
16992     }
16993 
16994     private boolean isRuntimePermission(String permissionName) {
16995         try {
16996             final PackageManager packageManager = mInjector.getPackageManager();
16997             PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
16998             return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16999                     == PermissionInfo.PROTECTION_DANGEROUS;
17000         } catch (NameNotFoundException e) {
17001             return false;
17002         }
17003     }
17004 
17005     @Override
17006     public boolean isProvisioningAllowed(String action, String packageName) {
17007         Objects.requireNonNull(packageName);
17008         final CallerIdentity caller = getCallerIdentity();
17009         final long ident = mInjector.binderClearCallingIdentity();
17010         try {
17011             final List<String> callerUidPackageNames = Arrays.asList(
17012                     mInjector.getPackageManager().getPackagesForUid(caller.getUid()));
17013             Preconditions.checkArgument(callerUidPackageNames.contains(packageName),
17014                     "Caller uid doesn't match the one for the provided package.");
17015 
17016             return checkProvisioningPreconditionSkipPermission(action, packageName, caller.getUserId())
17017                     == STATUS_OK;
17018         } finally {
17019             mInjector.binderRestoreCallingIdentity(ident);
17020         }
17021     }
17022 
17023     @Override
17024     public int checkProvisioningPrecondition(String action, String packageName) {
17025         Objects.requireNonNull(packageName, "packageName is null");
17026         final CallerIdentity caller = getCallerIdentity();
17027         Preconditions.checkCallAuthorization(
17028                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
17029 
17030         long originalId = mInjector.binderClearCallingIdentity();
17031         try {
17032             return checkProvisioningPreconditionSkipPermission(
17033                     action, packageName, caller.getUserId());
17034         } finally {
17035             mInjector.binderRestoreCallingIdentity(originalId);
17036         }
17037 
17038     }
17039 
17040     private int checkProvisioningPreconditionSkipPermission(
17041             String action, String packageName, int userId) {
17042         return checkProvisioningPreconditionSkipPermission(
17043                 action, packageName, /* componentName = */ null, userId);
17044     }
17045 
17046     private int checkProvisioningPreconditionSkipPermission(
17047             String action, ComponentName componentName, int userId) {
17048         return checkProvisioningPreconditionSkipPermission(
17049                 action, componentName.getPackageName(), componentName, userId);
17050     }
17051 
17052     private int checkProvisioningPreconditionSkipPermission(
17053             String action, String packageName, @Nullable ComponentName componentName, int userId) {
17054         if (!mHasFeature) {
17055             logMissingFeatureAction("Cannot check provisioning for action " + action);
17056             return STATUS_DEVICE_ADMIN_NOT_SUPPORTED;
17057         }
17058         if (!isProvisioningAllowed()) {
17059             return STATUS_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
17060         }
17061         final int code = checkProvisioningPreConditionSkipPermissionNoLog(
17062                 action, packageName, componentName, userId);
17063         if (code != STATUS_OK) {
17064             Slogf.d(LOG_TAG, "checkProvisioningPreCondition(" + action + ", " + packageName
17065                     + ") failed: " + computeProvisioningErrorString(
17066                             code, mInjector.userHandleGetCallingUserId()));
17067         }
17068         return code;
17069     }
17070 
17071     /**
17072      *  Checks if provisioning is allowed during regular usage (non-developer/CTS). This could
17073      *  return {@code false} if the device has an overlaid config value set to false. If not set,
17074      *  the default is true.
17075      */
17076     private boolean isProvisioningAllowed() {
17077         boolean isDeveloperMode = isDeveloperMode(mContext);
17078         boolean isProvisioningAllowedForNormalUsers = SystemProperties.getBoolean(
17079                 ALLOW_USER_PROVISIONING_KEY, /* defValue= */ true);
17080 
17081         return isDeveloperMode || isProvisioningAllowedForNormalUsers;
17082     }
17083 
17084     private static boolean isDeveloperMode(Context context) {
17085         return Global.getInt(context.getContentResolver(), Global.ADB_ENABLED, 0) > 0;
17086     }
17087 
17088     private int checkProvisioningPreConditionSkipPermissionNoLog(String action,
17089             String packageName, @Nullable ComponentName componentName, int userId) {
17090         if (packageName != null && componentName != null
17091                 && !packageName.equals(componentName.getPackageName())) {
17092             throw new IllegalArgumentException("PackageName: " + packageName + " is not the same as"
17093                     + " the package provided in componentName: " + componentName);
17094         }
17095         if (action != null) {
17096             switch (action) {
17097                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
17098                     return checkManagedProfileProvisioningPreCondition(packageName, userId);
17099                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
17100                 case DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE:
17101                     return checkDeviceOwnerProvisioningPreCondition(componentName, userId);
17102             }
17103         }
17104         throw new IllegalArgumentException("Unknown provisioning action " + action);
17105     }
17106 
17107     /**
17108      * The device owner can only be set before the setup phase of the primary user has completed,
17109      * except for adb command if no accounts or additional users are present on the device.
17110      */
17111     private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
17112             @UserIdInt int deviceOwnerUserId, @UserIdInt int callingUserId, boolean isAdb,
17113             boolean hasIncompatibleAccountsOrNonAdb) {
17114         if (mOwners.hasDeviceOwner()) {
17115             return STATUS_HAS_DEVICE_OWNER;
17116         }
17117         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
17118             return STATUS_USER_HAS_PROFILE_OWNER;
17119         }
17120 
17121         if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
17122             return STATUS_USER_NOT_RUNNING;
17123         }
17124 
17125         DeviceAdminInfo adminInfo = null;
17126 
17127         boolean isHeadlessModeAffiliated = false;
17128 
17129         boolean isHeadlessModeSingleUser = false;
17130 
17131         boolean isHeadlessSystemUserMode = mInjector.userManagerIsHeadlessSystemUserMode();
17132 
17133         int ensureSetUpUser = UserHandle.USER_SYSTEM;
17134         if (isHeadlessSystemUserMode) {
17135             if (owner != null) {
17136                 int headlessDeviceOwnerMode = getHeadlessDeviceOwnerModeForDeviceAdmin(
17137                         owner, deviceOwnerUserId);
17138 
17139                 isHeadlessModeAffiliated =
17140                         headlessDeviceOwnerMode == HEADLESS_DEVICE_OWNER_MODE_AFFILIATED;
17141 
17142                 isHeadlessModeSingleUser =
17143                         headlessDeviceOwnerMode == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER;
17144 
17145                 if (!isHeadlessModeAffiliated && !isHeadlessModeSingleUser) {
17146                     return STATUS_HEADLESS_SYSTEM_USER_MODE_NOT_SUPPORTED;
17147                 }
17148 
17149                 if (Flags.headlessDeviceOwnerSingleUserEnabled() && isHeadlessModeSingleUser) {
17150                     ensureSetUpUser = mUserManagerInternal.getMainUserId();
17151                     if (ensureSetUpUser == UserHandle.USER_NULL) {
17152                         return STATUS_HEADLESS_ONLY_SYSTEM_USER;
17153                     }
17154                 }
17155             }
17156 
17157             if (isHeadlessModeAffiliated && deviceOwnerUserId != UserHandle.USER_SYSTEM) {
17158                 Slogf.e(LOG_TAG, "In headless system user mode, "
17159                         + "device owner can only be set on headless system user.");
17160                 return STATUS_NOT_SYSTEM_USER;
17161             }
17162 
17163         }
17164 
17165         if (isAdb) {
17166             // If shell command runs after user setup completed check device status. Otherwise, OK.
17167             if (hasUserSetupCompleted(ensureSetUpUser)) {
17168                 // DO can be setup only if there are no users which are neither created by default
17169                 // nor marked as FOR_TESTING
17170 
17171                 if (nonTestNonPrecreatedUsersExist()) {
17172                     return STATUS_NONSYSTEM_USER_EXISTS;
17173                 }
17174 
17175                 int currentForegroundUser = getCurrentForegroundUserId();
17176                 if (callingUserId != currentForegroundUser
17177                         && mInjector.userManagerIsHeadlessSystemUserMode()
17178                         && currentForegroundUser == UserHandle.USER_SYSTEM) {
17179                     Slogf.wtf(LOG_TAG, "In headless system user mode, "
17180                             + "current user cannot be system user when setting device owner");
17181                     return STATUS_SYSTEM_USER;
17182                 }
17183                 if (hasIncompatibleAccountsOrNonAdb) {
17184                     return STATUS_ACCOUNTS_NOT_EMPTY;
17185                 }
17186             }
17187             return STATUS_OK;
17188         } else {
17189             // DO has to be user 0 if setting affiliated DO
17190             if ((!isHeadlessSystemUserMode || isHeadlessModeAffiliated)
17191                     && deviceOwnerUserId != UserHandle.USER_SYSTEM) {
17192                 return STATUS_NOT_SYSTEM_USER;
17193             }
17194             // Only provision DO before setup wizard completes
17195             if (hasUserSetupCompleted(ensureSetUpUser)) {
17196                 return STATUS_USER_SETUP_COMPLETED;
17197             }
17198             return STATUS_OK;
17199         }
17200     }
17201 
17202     /**
17203      * True if there are any users on the device which were not setup by default (1 usually, 2 for
17204      * devices with a headless system user) and also are not marked as FOR_TESTING.
17205      */
17206     private boolean nonTestNonPrecreatedUsersExist() {
17207         int allowedUsers = UserManager.isHeadlessSystemUserMode() ? 2 : 1;
17208         return mUserManagerInternal.getUsers(/* excludeDying= */ true).stream()
17209                 .filter(u -> !u.isForTesting())
17210                 .count() > allowedUsers;
17211     }
17212 
17213     private int checkDeviceOwnerProvisioningPreCondition(
17214             @Nullable ComponentName componentName, @UserIdInt int callingUserId) {
17215         synchronized (getLockObject()) {
17216             int deviceOwnerUserId = -1;
17217             if (Flags.headlessDeviceOwnerProvisioningFixEnabled()) {
17218                 deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode()
17219                         && getHeadlessDeviceOwnerModeForDeviceAdmin(componentName, callingUserId)
17220                         == HEADLESS_DEVICE_OWNER_MODE_AFFILIATED
17221                         ? UserHandle.USER_SYSTEM : callingUserId;
17222             } else {
17223                 deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode()
17224                         && getHeadlessDeviceOwnerModeForDeviceOwner()
17225                         == HEADLESS_DEVICE_OWNER_MODE_AFFILIATED
17226                         ? UserHandle.USER_SYSTEM : callingUserId;
17227             }
17228             Slogf.i(LOG_TAG, "Calling user %d, device owner will be set on user %d",
17229                     callingUserId, deviceOwnerUserId);
17230             // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
17231             return checkDeviceOwnerProvisioningPreConditionLocked(componentName,
17232                     deviceOwnerUserId, callingUserId, /* isAdb= */ false,
17233                     /* hasIncompatibleAccountsOrNonAdb=*/ true);
17234         }
17235     }
17236 
17237     private int checkManagedProfileProvisioningPreCondition(String packageName,
17238             @UserIdInt int callingUserId) {
17239         if (!hasFeatureManagedUsers()) {
17240             return STATUS_MANAGED_USERS_NOT_SUPPORTED;
17241         }
17242         if (getProfileOwnerAsUser(callingUserId) != null) {
17243             // Managed user cannot have a managed profile.
17244             return STATUS_USER_HAS_PROFILE_OWNER;
17245         }
17246 
17247         final long ident = mInjector.binderClearCallingIdentity();
17248         try {
17249             final UserHandle callingUserHandle = UserHandle.of(callingUserId);
17250             final boolean hasDeviceOwner;
17251             synchronized (getLockObject()) {
17252                 hasDeviceOwner = getDeviceOwnerAdminLocked() != null;
17253             }
17254 
17255             final boolean addingProfileRestricted = mUserManager.hasUserRestriction(
17256                     UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserHandle);
17257 
17258             if (mUserManager.getUserInfo(callingUserId).isProfile()) {
17259                 Slogf.i(LOG_TAG, "Calling user %d is a profile, cannot add another.",
17260                         callingUserId);
17261                 // The check is called from inside a managed profile. A managed profile cannot
17262                 // be provisioned from within another managed profile.
17263                 return STATUS_CANNOT_ADD_MANAGED_PROFILE;
17264             }
17265 
17266             // If there's a device owner, the restriction on adding a managed profile must be set.
17267             if (hasDeviceOwner && !addingProfileRestricted) {
17268                 Slogf.wtf(LOG_TAG, "Has a device owner but no restriction on adding a profile.");
17269             }
17270 
17271             // Do not allow adding a managed profile if there's a restriction.
17272             if (addingProfileRestricted) {
17273                 Slogf.i(LOG_TAG, "Adding a profile is restricted: User %s Has device owner? %b",
17274                         callingUserHandle, hasDeviceOwner);
17275                 return STATUS_CANNOT_ADD_MANAGED_PROFILE;
17276             }
17277 
17278             // Bail out if we are trying to provision a work profile but one already exists.
17279             if (!mUserManager.canAddMoreManagedProfiles(
17280                     callingUserId, /* allowedToRemoveOne= */ false)) {
17281                 Slogf.i(LOG_TAG, "Cannot add more managed profiles.");
17282                 return STATUS_CANNOT_ADD_MANAGED_PROFILE;
17283             }
17284         } finally {
17285             mInjector.binderRestoreCallingIdentity(ident);
17286         }
17287         return STATUS_OK;
17288     }
17289 
17290     private void checkIsDeviceOwner(CallerIdentity caller) {
17291         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller), caller.getUid()
17292                 + " is not device owner");
17293     }
17294 
17295     /**
17296      * Return device owner or profile owner set on a given user.
17297      */
17298     private @Nullable ComponentName getOwnerComponent(int userId) {
17299         synchronized (getLockObject()) {
17300             if (mOwners.getDeviceOwnerUserId() == userId) {
17301                 return mOwners.getDeviceOwnerComponent();
17302             }
17303             if (mOwners.hasProfileOwner(userId)) {
17304                 return mOwners.getProfileOwnerComponent(userId);
17305             }
17306         }
17307         return null;
17308     }
17309 
17310     private boolean hasFeatureManagedUsers() {
17311         try {
17312             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
17313         } catch (RemoteException e) {
17314             return false;
17315         }
17316     }
17317 
17318     @Override
17319     public String getWifiMacAddress(ComponentName admin, String callerPackageName) {
17320 //        if (!isPermissionCheckFlagEnabled()) {
17321             Objects.requireNonNull(admin, "ComponentName is null");
17322 //        }
17323 
17324         final CallerIdentity caller = getCallerIdentity(admin, callerPackageName);
17325 //        if (isPermissionCheckFlagEnabled()) {
17326 //            enforcePermission(MANAGE_DEVICE_POLICY_WIFI, UserHandle.USER_ALL);
17327 //        } else {
17328             Preconditions.checkCallAuthorization(
17329                     isDefaultDeviceOwner(caller)
17330                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
17331 //        }
17332 
17333         return mInjector.binderWithCleanCallingIdentity(() -> {
17334             String[] macAddresses = mInjector.getWifiManager().getFactoryMacAddresses();
17335             if (macAddresses == null) {
17336                 return null;
17337             }
17338             DevicePolicyEventLogger
17339                     .createEvent(DevicePolicyEnums.GET_WIFI_MAC_ADDRESS)
17340                     .setAdmin(caller.getPackageName())
17341                     .write();
17342             return macAddresses.length > 0 ? macAddresses[0] : null;
17343         });
17344     }
17345 
17346     /**
17347      * Returns the target sdk version number that the given packageName was built for
17348      * in the given user.
17349      */
17350     private int getTargetSdk(String packageName, int userId) {
17351         final ApplicationInfo ai;
17352         try {
17353             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
17354             return ai == null ? 0 : ai.targetSdkVersion;
17355         } catch (RemoteException e) {
17356             // Shouldn't happen
17357             Slogf.wtf(LOG_TAG, "Error getting application info", e);
17358             return 0;
17359         }
17360     }
17361 
17362     @Override
17363     public boolean isManagedProfile(ComponentName admin) {
17364         Objects.requireNonNull(admin, "ComponentName is null");
17365 
17366         final CallerIdentity caller = getCallerIdentity(admin);
17367         Preconditions.checkCallAuthorization(
17368                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
17369 
17370         return isManagedProfile(caller.getUserId());
17371     }
17372 
17373     @Override
17374     public void reboot(ComponentName admin) {
17375         Objects.requireNonNull(admin, "ComponentName is null");
17376         final CallerIdentity caller = getCallerIdentity(admin);
17377         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
17378         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REBOOT);
17379         mInjector.binderWithCleanCallingIdentity(() -> {
17380             // Make sure there are no ongoing calls on the device.
17381             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
17382                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
17383             }
17384             DevicePolicyEventLogger
17385                     .createEvent(DevicePolicyEnums.REBOOT)
17386                     .setAdmin(admin)
17387                     .write();
17388             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
17389         });
17390     }
17391 
17392     @Override
17393     public void setShortSupportMessage(@Nullable ComponentName who, String callerPackageName,
17394             CharSequence message) {
17395         if (!mHasFeature) {
17396             return;
17397         }
17398         CallerIdentity caller;
17399         ActiveAdmin admin;
17400 
17401         message = PolicySizeVerifier.truncateIfLonger(message, MAX_SHORT_SUPPORT_MESSAGE_LENGTH);
17402 
17403         if (isPermissionCheckFlagEnabled()) {
17404             caller = getCallerIdentity(who, callerPackageName);
17405             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
17406                     who,
17407                     MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
17408                     caller.getPackageName(),
17409                     caller.getUserId());
17410             admin = enforcingAdmin.getActiveAdmin();
17411         } else {
17412             caller = getCallerIdentity(who);
17413             Objects.requireNonNull(who, "ComponentName is null");
17414             synchronized (getLockObject()) {
17415                 admin = getActiveAdminForUidLocked(who, caller.getUid());
17416             }
17417         }
17418 
17419         synchronized (getLockObject()) {
17420             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
17421                 admin.shortSupportMessage = message;
17422                 saveSettingsLocked(caller.getUserId());
17423             }
17424         }
17425         DevicePolicyEventLogger
17426                 .createEvent(DevicePolicyEnums.SET_SHORT_SUPPORT_MESSAGE)
17427                 .setAdmin(caller.getPackageName())
17428                 .write();
17429     }
17430 
17431     @Override
17432     public CharSequence getShortSupportMessage(@Nullable ComponentName who,
17433             String callerPackageName) {
17434         if (!mHasFeature) {
17435             return null;
17436         }
17437         CallerIdentity caller;
17438         ActiveAdmin admin;
17439 
17440         if (isPermissionCheckFlagEnabled()) {
17441             caller = getCallerIdentity(who, callerPackageName);
17442             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
17443                     who,
17444                     MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
17445                     caller.getPackageName(),
17446                     caller.getUserId());
17447             admin = enforcingAdmin.getActiveAdmin();
17448         } else {
17449             caller = getCallerIdentity(who);
17450             Objects.requireNonNull(who, "ComponentName is null");
17451             synchronized (getLockObject()) {
17452                 admin = getActiveAdminForUidLocked(who, caller.getUid());
17453             }
17454         }
17455         return admin.shortSupportMessage;
17456     }
17457 
17458     @Override
17459     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
17460         if (!mHasFeature) {
17461             return;
17462         }
17463 
17464         message = PolicySizeVerifier.truncateIfLonger(message, MAX_LONG_SUPPORT_MESSAGE_LENGTH);
17465 
17466         Objects.requireNonNull(who, "ComponentName is null");
17467         final CallerIdentity caller = getCallerIdentity(who);
17468         synchronized (getLockObject()) {
17469             ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
17470             if (!TextUtils.equals(admin.longSupportMessage, message)) {
17471                 admin.longSupportMessage = message;
17472                 saveSettingsLocked(caller.getUserId());
17473             }
17474         }
17475         DevicePolicyEventLogger
17476                 .createEvent(DevicePolicyEnums.SET_LONG_SUPPORT_MESSAGE)
17477                 .setAdmin(who)
17478                 .write();
17479     }
17480 
17481     @Override
17482     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
17483         if (!mHasFeature) {
17484             return null;
17485         }
17486         Objects.requireNonNull(who, "ComponentName is null");
17487         final CallerIdentity caller = getCallerIdentity(who);
17488         synchronized (getLockObject()) {
17489             ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
17490             return admin.longSupportMessage;
17491         }
17492     }
17493 
17494     @Override
17495     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
17496         if (!mHasFeature) {
17497             return null;
17498         }
17499         Objects.requireNonNull(who, "ComponentName is null");
17500         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
17501                 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user"));
17502 
17503         synchronized (getLockObject()) {
17504             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
17505             if (admin != null) {
17506                 return admin.shortSupportMessage;
17507             }
17508         }
17509         return null;
17510     }
17511 
17512     @Override
17513     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
17514         if (!mHasFeature) {
17515             return null;
17516         }
17517         Objects.requireNonNull(who, "ComponentName is null");
17518         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
17519                 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user"));
17520 
17521         synchronized (getLockObject()) {
17522             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
17523             if (admin != null) {
17524                 return admin.longSupportMessage;
17525             }
17526         }
17527         return null;
17528     }
17529 
17530     @Override
17531     public void setOrganizationColor(@NonNull ComponentName who, int color) {
17532         if (!mHasFeature) {
17533             return;
17534         }
17535         Objects.requireNonNull(who, "ComponentName is null");
17536 
17537         final CallerIdentity caller = getCallerIdentity(who);
17538         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
17539         Preconditions.checkCallAuthorization(isProfileOwner(caller));
17540 
17541         synchronized (getLockObject()) {
17542             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
17543             admin.organizationColor = color;
17544             saveSettingsLocked(caller.getUserId());
17545         }
17546         DevicePolicyEventLogger
17547                 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_COLOR)
17548                 .setAdmin(caller.getComponentName())
17549                 .write();
17550     }
17551 
17552     @Override
17553     public void setOrganizationColorForUser(int color, int userId) {
17554         if (!mHasFeature) {
17555             return;
17556         }
17557         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
17558 
17559         final CallerIdentity caller = getCallerIdentity();
17560         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
17561         Preconditions.checkCallAuthorization(canManageUsers(caller));
17562         Preconditions.checkCallAuthorization(isManagedProfile(userId), "You can not "
17563                 + "set organization color outside a managed profile, userId = %d", userId);
17564 
17565         synchronized (getLockObject()) {
17566             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
17567             admin.organizationColor = color;
17568             saveSettingsLocked(userId);
17569         }
17570     }
17571 
17572     @Override
17573     public int getOrganizationColor(@NonNull ComponentName who) {
17574         if (!mHasFeature) {
17575             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
17576         }
17577         Objects.requireNonNull(who, "ComponentName is null");
17578 
17579         final CallerIdentity caller = getCallerIdentity(who);
17580         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
17581         Preconditions.checkCallAuthorization(isProfileOwner(caller));
17582 
17583         synchronized (getLockObject()) {
17584             ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
17585             return admin.organizationColor;
17586         }
17587     }
17588 
17589     @Override
17590     public int getOrganizationColorForUser(int userHandle) {
17591         if (!mHasFeature) {
17592             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
17593         }
17594         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
17595 
17596         final CallerIdentity caller = getCallerIdentity();
17597         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
17598         Preconditions.checkCallAuthorization(isManagedProfile(userHandle), "You can "
17599                 + "not get organization color outside a managed profile, userId = %d", userHandle);
17600 
17601         synchronized (getLockObject()) {
17602             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
17603             return (profileOwner != null)
17604                     ? profileOwner.organizationColor
17605                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
17606         }
17607     }
17608 
17609     @Override
17610     public void setOrganizationName(@Nullable ComponentName who, String callerPackageName,
17611             CharSequence text) {
17612         if (!mHasFeature) {
17613             return;
17614         }
17615         CallerIdentity caller = getCallerIdentity(who);
17616         ActiveAdmin admin = null;
17617 
17618         if (isPermissionCheckFlagEnabled()) {
17619             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
17620                     who,
17621                     MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
17622                     caller.getPackageName(),
17623                     caller.getUserId());
17624             admin = enforcingAdmin.getActiveAdmin();
17625         } else {
17626             Objects.requireNonNull(who, "ComponentName is null");
17627             Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
17628         }
17629 
17630         text = PolicySizeVerifier.truncateIfLonger(text, MAX_ORG_NAME_LENGTH);
17631 
17632         synchronized (getLockObject()) {
17633             if (!isPermissionCheckFlagEnabled()) {
17634                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
17635             }
17636             if (!TextUtils.equals(admin.organizationName, text)) {
17637                 admin.organizationName = (text == null || text.length() == 0)
17638                         ? null : text.toString();
17639                 saveSettingsLocked(caller.getUserId());
17640             }
17641         }
17642     }
17643 
17644     @Override
17645     public CharSequence getOrganizationName(@Nullable ComponentName who, String callerPackageName) {
17646         if (!mHasFeature) {
17647             return null;
17648         }
17649         CallerIdentity caller = getCallerIdentity(who);
17650         ActiveAdmin admin;
17651 
17652         if (isPermissionCheckFlagEnabled()) {
17653             EnforcingAdmin enforcingAdmin = enforceCanQueryAndGetEnforcingAdmin(
17654                     who,
17655                     MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
17656                     caller.getPackageName(),
17657                     caller.getUserId());
17658             admin = enforcingAdmin.getActiveAdmin();
17659         } else {
17660             Objects.requireNonNull(who, "ComponentName is null");
17661             Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
17662             Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
17663 
17664             synchronized (getLockObject()) {
17665                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
17666             }
17667         }
17668 
17669         return admin.organizationName;
17670     }
17671 
17672     /**
17673      * This API is cached: invalidate with invalidateBinderCaches().
17674      */
17675     @Override
17676     public CharSequence getDeviceOwnerOrganizationName() {
17677         if (!mHasFeature) {
17678             return null;
17679         }
17680         final CallerIdentity caller = getCallerIdentity();
17681         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
17682                 || canManageUsers(caller) || isFinancedDeviceOwner(caller));
17683         synchronized (getLockObject()) {
17684             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
17685             return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
17686         }
17687     }
17688 
17689     /**
17690      * This API is cached: invalidate with invalidateBinderCaches().
17691      */
17692     @Override
17693     public CharSequence getOrganizationNameForUser(int userHandle) {
17694         if (!mHasFeature) {
17695             return null;
17696         }
17697         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
17698 
17699         final CallerIdentity caller = getCallerIdentity();
17700         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
17701         Preconditions.checkCallAuthorization(canManageUsers(caller));
17702         Preconditions.checkCallAuthorization(isManagedProfile(userHandle),
17703                 "You can not get organization name outside a managed profile, userId = %d",
17704                 userHandle);
17705 
17706         synchronized (getLockObject()) {
17707             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
17708             return (profileOwner != null)
17709                     ? profileOwner.organizationName
17710                     : null;
17711         }
17712     }
17713 
17714     @Override
17715     public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) {
17716         Objects.requireNonNull(who);
17717         Objects.requireNonNull(packageNames);
17718         final CallerIdentity caller = getCallerIdentity(who);
17719         Preconditions.checkCallAuthorization(
17720                 isDefaultDeviceOwner(caller) || isProfileOwner(caller),
17721                 "Admin %s does not own the profile", caller.getComponentName());
17722 
17723         if (!mHasFeature) {
17724             return packageNames;
17725         }
17726         return mInjector.binderWithCleanCallingIdentity(() -> {
17727             final List<String> excludedPkgs = removeInvalidPkgsForMeteredDataRestriction(
17728                     caller.getUserId(), packageNames);
17729 
17730             synchronized (getLockObject()) {
17731                 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
17732                 admin.meteredDisabledPackages = packageNames;
17733                 saveSettingsLocked(caller.getUserId());
17734             }
17735             pushMeteredDisabledPackages(caller.getUserId());
17736             return excludedPkgs;
17737         });
17738     }
17739 
17740     private List<String> removeInvalidPkgsForMeteredDataRestriction(
17741             int userId, List<String> pkgNames) {
17742         synchronized (getLockObject()) {
17743             final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId);
17744             final List<String> excludedPkgs = new ArrayList<>();
17745             for (int i = pkgNames.size() - 1; i >= 0; --i) {
17746                 final String pkgName = pkgNames.get(i);
17747                 // If the package is an active admin, don't restrict it.
17748                 if (activeAdmins.contains(pkgName)) {
17749                     excludedPkgs.add(pkgName);
17750                     continue;
17751                 }
17752                 // If the package doesn't exist, don't restrict it.
17753                 try {
17754                     if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) {
17755                         excludedPkgs.add(pkgName);
17756                     }
17757                 } catch (RemoteException e) {
17758                     // Should not happen
17759                 }
17760             }
17761             pkgNames.removeAll(excludedPkgs);
17762             return excludedPkgs;
17763         }
17764     }
17765 
17766     @Override
17767     public List<String> getMeteredDataDisabledPackages(ComponentName who) {
17768         Objects.requireNonNull(who);
17769 
17770         if (!mHasFeature) {
17771             return new ArrayList<>();
17772         }
17773         final CallerIdentity caller = getCallerIdentity(who);
17774         Preconditions.checkCallAuthorization(
17775                 isDefaultDeviceOwner(caller) || isProfileOwner(caller),
17776                 "Admin %s does not own the profile", caller.getComponentName());
17777 
17778         synchronized (getLockObject()) {
17779             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
17780             return admin.meteredDisabledPackages == null
17781                     ? new ArrayList<>() : admin.meteredDisabledPackages;
17782         }
17783     }
17784 
17785     @Override
17786     public boolean isMeteredDataDisabledPackageForUser(ComponentName who,
17787             String packageName, int userId) {
17788         Objects.requireNonNull(who);
17789 
17790         if (!mHasFeature) {
17791             return false;
17792         }
17793         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
17794                 String.format(NOT_SYSTEM_CALLER_MSG, "query restricted pkgs for a specific user"));
17795 
17796         synchronized (getLockObject()) {
17797             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
17798             if (admin != null && admin.meteredDisabledPackages != null) {
17799                 return admin.meteredDisabledPackages.contains(packageName);
17800             }
17801         }
17802         return false;
17803     }
17804 
17805     @Override
17806     public void setProfileOwnerOnOrganizationOwnedDevice(ComponentName who, int userId,
17807             boolean isProfileOwnerOnOrganizationOwnedDevice) {
17808         if (!mHasFeature) {
17809             return;
17810         }
17811         // As the caller is the system, it must specify the component name of the profile owner
17812         // as a safety check.
17813         Objects.requireNonNull(who);
17814 
17815         final CallerIdentity caller = getCallerIdentity();
17816         // Only adb or system apps with the right permission can mark a profile owner on
17817         // organization-owned device.
17818         if (!(isAdb(caller) || hasCallingPermission(permission.MARK_DEVICE_ORGANIZATION_OWNED)
17819                 || hasCallingPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS))) {
17820             throw new SecurityException(
17821                     "Only the system can mark a profile owner of organization-owned device.");
17822         }
17823         // Only a test admin can be unmarked as a profile owner on an organization-owned device.
17824         synchronized (getLockObject()) {
17825             if (!isProfileOwnerOnOrganizationOwnedDevice && !isAdminTestOnlyLocked(who, userId)) {
17826                 throw new SecurityException("Only a test admin can be unmarked as a "
17827                         + "profile owner of organization-owned device.");
17828             }
17829         }
17830 
17831         if (isAdb(caller)) {
17832             if (hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, who)) {
17833                 throw new SecurityException(
17834                         "Can only be called from ADB if the device has no accounts.");
17835             }
17836         } else {
17837             if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
17838                 throw new IllegalStateException(
17839                         "Cannot mark profile owner as managing an organization-owned device after"
17840                                 + " set-up");
17841             }
17842         }
17843 
17844         // Grant access under lock.
17845         synchronized (getLockObject()) {
17846             setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(who, userId,
17847                     isProfileOwnerOnOrganizationOwnedDevice);
17848         }
17849     }
17850 
17851     @GuardedBy("getLockObject()")
17852     private void setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(
17853             ComponentName who, int userId, boolean isProfileOwnerOnOrganizationOwnedDevice) {
17854         // Make sure that the user has a profile owner and that the specified
17855         // component is the profile owner of that user.
17856         if (!isProfileOwner(who, userId)) {
17857             throw new IllegalArgumentException(String.format(
17858                     "Component %s is not a Profile Owner of user %d",
17859                     who.flattenToString(), userId));
17860         }
17861 
17862         Slogf.i(LOG_TAG, "%s %s as profile owner on organization-owned device for user %d",
17863                 isProfileOwnerOnOrganizationOwnedDevice ? "Marking" : "Unmarking",
17864                 who.flattenToString(), userId);
17865 
17866         // First, set restriction on removing the profile.
17867         mInjector.binderWithCleanCallingIdentity(() -> {
17868             // Clear restriction as user.
17869             final UserHandle parentUser = mUserManager.getProfileParent(UserHandle.of(userId));
17870             if (parentUser == null) {
17871                 throw new IllegalStateException(String.format("User %d is not a profile", userId));
17872             }
17873 
17874             mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
17875                     isProfileOwnerOnOrganizationOwnedDevice,
17876                     parentUser);
17877             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER,
17878                     isProfileOwnerOnOrganizationOwnedDevice,
17879                     parentUser);
17880         });
17881 
17882         // setProfileOwnerOfOrganizationOwnedDevice will trigger writing of the profile owner
17883         // data, no need to do it manually.
17884         mOwners.setProfileOwnerOfOrganizationOwnedDevice(userId,
17885                 isProfileOwnerOnOrganizationOwnedDevice);
17886     }
17887 
17888     private void pushMeteredDisabledPackages(int userId) {
17889         wtfIfInLock();
17890         mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages(
17891                 getMeteredDisabledPackages(userId), userId);
17892     }
17893 
17894     private Set<String> getMeteredDisabledPackages(int userId) {
17895         synchronized (getLockObject()) {
17896             final Set<String> restrictedPkgs = new ArraySet<>();
17897             final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
17898             if (admin != null && admin.meteredDisabledPackages != null) {
17899                 restrictedPkgs.addAll(admin.meteredDisabledPackages);
17900             }
17901 
17902             return restrictedPkgs;
17903         }
17904     }
17905 
17906     @Override
17907     public void setAffiliationIds(ComponentName admin, List<String> ids) {
17908         if (!mHasFeature) {
17909             return;
17910         }
17911         if (ids == null) {
17912             throw new IllegalArgumentException("ids must not be null");
17913         }
17914         for (String id : ids) {
17915             Preconditions.checkArgument(!TextUtils.isEmpty(id), "ids must not have empty string");
17916             PolicySizeVerifier.enforceMaxStringLength(id, "affiliation id");
17917         }
17918 
17919         final Set<String> affiliationIds = new ArraySet<>(ids);
17920         final CallerIdentity caller = getCallerIdentity(admin);
17921         Preconditions.checkCallAuthorization(
17922                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
17923         final int callingUserId = caller.getUserId();
17924 
17925         synchronized (getLockObject()) {
17926             getUserData(callingUserId).mAffiliationIds = affiliationIds;
17927             saveSettingsLocked(callingUserId);
17928             mStateCache.setHasAffiliationWithDevice(callingUserId,
17929                     isUserAffiliatedWithDeviceLocked(callingUserId));
17930             if (callingUserId == UserHandle.USER_SYSTEM) {
17931                 resetAffiliationCacheLocked();
17932             } else if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin,
17933                     callingUserId)) {
17934                 // Affiliation ids specified by the device owner are additionally stored in
17935                 // UserHandle.USER_SYSTEM's DevicePolicyData.
17936                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
17937                 mStateCache.setHasAffiliationWithDevice(UserHandle.USER_SYSTEM, true);
17938                 saveSettingsLocked(UserHandle.USER_SYSTEM);
17939             }
17940 
17941             // Affiliation status for any user, not just the calling user, might have changed.
17942             // The device owner user will still be affiliated after changing its affiliation ids,
17943             // but as a result of that other users might become affiliated or un-affiliated.
17944             maybePauseDeviceWideLoggingLocked();
17945             maybeResumeDeviceWideLoggingLocked();
17946             maybeClearLockTaskPolicyLocked();
17947             updateAdminCanGrantSensorsPermissionCache(callingUserId);
17948         }
17949     }
17950 
17951     private void resetAffiliationCacheLocked() {
17952         mInjector.binderWithCleanCallingIdentity(() -> {
17953             for (UserInfo user : mUserManager.getUsers()) {
17954                 mStateCache.setHasAffiliationWithDevice(user.id,
17955                         isUserAffiliatedWithDeviceLocked(user.id));
17956             }
17957         });
17958     }
17959 
17960     @Override
17961     public List<String> getAffiliationIds(ComponentName admin) {
17962         if (!mHasFeature) {
17963             return Collections.emptyList();
17964         }
17965 
17966         Objects.requireNonNull(admin);
17967         final CallerIdentity caller = getCallerIdentity(admin);
17968         Preconditions.checkCallAuthorization(
17969                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
17970 
17971         synchronized (getLockObject()) {
17972             return new ArrayList<String>(getUserData(caller.getUserId()).mAffiliationIds);
17973         }
17974     }
17975 
17976     @Override
17977     public boolean isCallingUserAffiliated() {
17978         if (!mHasFeature) {
17979             return false;
17980         }
17981 
17982         synchronized (getLockObject()) {
17983             return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
17984         }
17985     }
17986 
17987     @Override
17988     public boolean isAffiliatedUser(@UserIdInt int userId) {
17989         if (!mHasFeature) {
17990             return false;
17991         }
17992         final CallerIdentity caller = getCallerIdentity();
17993         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
17994 
17995         return isUserAffiliatedWithDevice(userId);
17996     }
17997 
17998     private boolean isUserAffiliatedWithDevice(@UserIdInt int userId) {
17999         synchronized (getLockObject()) {
18000             return isUserAffiliatedWithDeviceLocked(userId);
18001         }
18002     }
18003 
18004     private boolean isUserAffiliatedWithDeviceLocked(@UserIdInt int userId) {
18005         if (!mOwners.hasDeviceOwner()) {
18006             return false;
18007         }
18008         if (userId == UserHandle.USER_SYSTEM) {
18009             // The system user is always affiliated in a DO device,
18010             // even if in headless system user mode.
18011             return true;
18012         }
18013         if (userId == mOwners.getDeviceOwnerUserId()) {
18014             // The user that the DO is installed on is always affiliated with the device.
18015             return true;
18016         }
18017 
18018         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
18019         if (profileOwner == null) {
18020             return false;
18021         }
18022 
18023         final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
18024         final Set<String> deviceAffiliationIds =
18025                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
18026         for (String id : userAffiliationIds) {
18027             if (deviceAffiliationIds.contains(id)) {
18028                 return true;
18029             }
18030         }
18031         return false;
18032     }
18033 
18034     private boolean areAllUsersAffiliatedWithDeviceLocked() {
18035         return mInjector.binderWithCleanCallingIdentity(() -> {
18036             final List<UserInfo> userInfos = mUserManager.getAliveUsers();
18037             for (int i = 0; i < userInfos.size(); i++) {
18038                 int userId = userInfos.get(i).id;
18039                 if (!isUserAffiliatedWithDeviceLocked(userId)) {
18040                     Slogf.d(LOG_TAG, "User id " + userId + " not affiliated.");
18041                     return false;
18042                 }
18043             }
18044             return true;
18045         });
18046     }
18047 
18048     private @UserIdInt int getSecurityLoggingEnabledUser() {
18049         synchronized (getLockObject()) {
18050             if (mOwners.hasDeviceOwner()) {
18051                 return UserHandle.USER_ALL;
18052             }
18053         }
18054         // TODO: Add check for permission-based
18055         return getOrganizationOwnedProfileUserId();
18056     }
18057 
18058     @Override
18059     public void setSecurityLoggingEnabled(ComponentName who, String packageName,
18060             boolean enabled) {
18061         if (!mHasFeature) {
18062             return;
18063         }
18064         final CallerIdentity caller = getCallerIdentity(who, packageName);
18065 
18066         if (Flags.securityLogV2Enabled()) {
18067             EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
18068                     who,
18069                     MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
18070                     caller.getPackageName(),
18071                     caller.getUserId());
18072             if (enabled) {
18073                 mDevicePolicyEngine.setGlobalPolicy(
18074                         PolicyDefinition.SECURITY_LOGGING,
18075                         admin,
18076                         new BooleanPolicyValue(true));
18077             } else {
18078                 mDevicePolicyEngine.removeGlobalPolicy(
18079                         PolicyDefinition.SECURITY_LOGGING,
18080                         admin);
18081             }
18082         } else {
18083             synchronized (getLockObject()) {
18084                 if (who != null) {
18085                     Preconditions.checkCallAuthorization(
18086                             isProfileOwnerOfOrganizationOwnedDevice(caller)
18087                                     || isDefaultDeviceOwner(caller));
18088                 } else {
18089                     // A delegate app passes a null admin component, which is expected
18090                     Preconditions.checkCallAuthorization(
18091                             isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
18092                 }
18093 
18094                 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
18095                     return;
18096                 }
18097                 mInjector.securityLogSetLoggingEnabledProperty(enabled);
18098                 if (enabled) {
18099                     mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
18100                     maybePauseDeviceWideLoggingLocked();
18101                 } else {
18102                     mSecurityLogMonitor.stop();
18103                 }
18104             }
18105         }
18106         DevicePolicyEventLogger
18107                 .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED)
18108                 .setAdmin(caller.getPackageName())
18109                 .setBoolean(enabled)
18110                 .write();
18111     }
18112 
18113     @Override
18114     public boolean isSecurityLoggingEnabled(ComponentName admin, String packageName) {
18115         if (!mHasFeature) {
18116             return false;
18117         }
18118 
18119         final CallerIdentity caller = getCallerIdentity(admin, packageName);
18120         if (isSystemUid(caller)) {
18121             // Settings uses this for privacy transparency.
18122             // TODO: create a separate @hidden API for settings.
18123             return mInjector.securityLogGetLoggingEnabledProperty();
18124         }
18125 
18126         if (Flags.securityLogV2Enabled()) {
18127             final EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
18128                     admin,
18129                     MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
18130                     caller.getPackageName(),
18131                     caller.getUserId());
18132             final Boolean policy = mDevicePolicyEngine.getGlobalPolicySetByAdmin(
18133                     PolicyDefinition.SECURITY_LOGGING, enforcingAdmin);
18134             return Boolean.TRUE.equals(policy);
18135         } else {
18136             synchronized (getLockObject()) {
18137                 if (admin != null) {
18138                     Preconditions.checkCallAuthorization(
18139                             isProfileOwnerOfOrganizationOwnedDevice(caller)
18140                                     || isDefaultDeviceOwner(caller));
18141                 } else {
18142                     // A delegate app passes a null admin component, which is expected
18143                     Preconditions.checkCallAuthorization(
18144                             isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
18145                 }
18146                 return mInjector.securityLogGetLoggingEnabledProperty();
18147             }
18148         }
18149     }
18150 
18151     private void recordSecurityLogRetrievalTime() {
18152         synchronized (getLockObject()) {
18153             final long currentTime = System.currentTimeMillis();
18154             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
18155             if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
18156                 policyData.mLastSecurityLogRetrievalTime = currentTime;
18157                 saveSettingsLocked(UserHandle.USER_SYSTEM);
18158             }
18159         }
18160     }
18161 
18162     @Override
18163     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin,
18164             String packageName) {
18165         if (!mHasFeature) {
18166             return null;
18167         }
18168 
18169         final CallerIdentity caller = getCallerIdentity(admin, packageName);
18170         if (isPermissionCheckFlagEnabled()) {
18171             Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
18172                     || areAllUsersAffiliatedWithDeviceLocked());
18173             enforcePermission(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, caller.getPackageName(),
18174                     UserHandle.USER_ALL);
18175         } else {
18176             if (admin != null) {
18177                 Preconditions.checkCallAuthorization(
18178                         isProfileOwnerOfOrganizationOwnedDevice(caller)
18179                                 || isDefaultDeviceOwner(caller));
18180             } else {
18181                 // A delegate app passes a null admin component, which is expected
18182                 Preconditions.checkCallAuthorization(
18183                         isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
18184             }
18185 
18186             Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
18187                     || areAllUsersAffiliatedWithDeviceLocked());
18188         }
18189 
18190         DevicePolicyEventLogger
18191                 .createEvent(DevicePolicyEnums.RETRIEVE_PRE_REBOOT_SECURITY_LOGS)
18192                 .setAdmin(caller.getPackageName())
18193                 .write();
18194 
18195         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
18196                 || !mInjector.securityLogGetLoggingEnabledProperty()) {
18197             return null;
18198         }
18199 
18200         recordSecurityLogRetrievalTime();
18201         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
18202         try {
18203             SecurityLog.readPreviousEvents(output);
18204             int enabledUser = getSecurityLoggingEnabledUser();
18205             if (enabledUser != UserHandle.USER_ALL) {
18206                 SecurityLog.redactEvents(output, enabledUser);
18207             }
18208             return new ParceledListSlice<SecurityEvent>(output);
18209         } catch (IOException e) {
18210             Slogf.w(LOG_TAG, "Fail to read previous events" , e);
18211             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
18212         }
18213     }
18214 
18215     @Override
18216     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin,
18217             String packageName) {
18218         if (!mHasFeature) {
18219             return null;
18220         }
18221 
18222         final CallerIdentity caller = getCallerIdentity(admin, packageName);
18223 
18224         if (Flags.securityLogV2Enabled()) {
18225             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
18226                     admin,
18227                     MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
18228                     caller.getPackageName(),
18229                     caller.getUserId());
18230 
18231             synchronized (getLockObject()) {
18232                 Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
18233                         || areAllUsersAffiliatedWithDeviceLocked());
18234             }
18235 
18236             Boolean policy = mDevicePolicyEngine.getGlobalPolicySetByAdmin(
18237                     PolicyDefinition.SECURITY_LOGGING, enforcingAdmin);
18238 
18239             if (!Boolean.TRUE.equals(policy)) {
18240                 Slogf.e(LOG_TAG, "%s hasn't enabled security logging but tries to retrieve logs",
18241                         caller.getPackageName());
18242                 return null;
18243             }
18244         } else {
18245             if (admin != null) {
18246                 Preconditions.checkCallAuthorization(
18247                         isProfileOwnerOfOrganizationOwnedDevice(caller)
18248                                 || isDefaultDeviceOwner(caller));
18249             } else {
18250                 // A delegate app passes a null admin component, which is expected
18251                 Preconditions.checkCallAuthorization(
18252                         isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
18253             }
18254             Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
18255                     || areAllUsersAffiliatedWithDeviceLocked());
18256 
18257             if (!mInjector.securityLogGetLoggingEnabledProperty()) {
18258                 return null;
18259             }
18260         }
18261 
18262         recordSecurityLogRetrievalTime();
18263 
18264         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
18265         DevicePolicyEventLogger
18266                 .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS)
18267                 .setAdmin(caller.getPackageName())
18268                 .write();
18269         return logs != null ? new ParceledListSlice<>(logs) : null;
18270     }
18271 
18272     @Override
18273     public void setAuditLogEnabled(String callingPackage, boolean enabled) {
18274         if (!mHasFeature) {
18275             return;
18276         }
18277         final CallerIdentity caller = getCallerIdentity(callingPackage);
18278 
18279         if (!Flags.securityLogV2Enabled()) {
18280             throw new UnsupportedOperationException("Audit log not enabled");
18281         }
18282 
18283         EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
18284                 null /* admin */,
18285                 MANAGE_DEVICE_POLICY_AUDIT_LOGGING,
18286                 caller.getPackageName(),
18287                 caller.getUserId());
18288         if (enabled) {
18289             mDevicePolicyEngine.setGlobalPolicy(
18290                     PolicyDefinition.AUDIT_LOGGING,
18291                     admin,
18292                     new BooleanPolicyValue(true));
18293         } else {
18294             mDevicePolicyEngine.removeGlobalPolicy(
18295                     PolicyDefinition.AUDIT_LOGGING,
18296                     admin);
18297             mSecurityLogMonitor.setAuditLogEventsCallback(caller.getUid(), null /* callback */);
18298         }
18299     }
18300 
18301     @Override
18302     public boolean isAuditLogEnabled(String callingPackage) {
18303         if (!mHasFeature) {
18304             return false;
18305         }
18306 
18307         if (!Flags.securityLogV2Enabled()) {
18308             throw new UnsupportedOperationException("Audit log not enabled");
18309         }
18310 
18311         final CallerIdentity caller = getCallerIdentity(callingPackage);
18312         EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
18313                 null /* admin */,
18314                 MANAGE_DEVICE_POLICY_AUDIT_LOGGING,
18315                 caller.getPackageName(),
18316                 caller.getUserId());
18317 
18318         Boolean policy = mDevicePolicyEngine.getGlobalPolicySetByAdmin(
18319                 PolicyDefinition.AUDIT_LOGGING, admin);
18320 
18321         return Boolean.TRUE.equals(policy);
18322     }
18323 
18324     @Override
18325     public void setAuditLogEventsCallback(String callingPackage, IAuditLogEventsCallback callback) {
18326         if (!mHasFeature) {
18327             return;
18328         }
18329 
18330         final CallerIdentity caller = getCallerIdentity(callingPackage);
18331         EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(
18332                 null /* admin */,
18333                 MANAGE_DEVICE_POLICY_AUDIT_LOGGING,
18334                 caller.getPackageName(),
18335                 caller.getUserId());
18336 
18337         Boolean policy = mDevicePolicyEngine.getGlobalPolicySetByAdmin(
18338                 PolicyDefinition.AUDIT_LOGGING, admin);
18339 
18340         if (!Boolean.TRUE.equals(policy)) {
18341             throw new IllegalStateException(
18342                     "Managing app has to enable audit log before setting events callback");
18343         }
18344 
18345         mSecurityLogMonitor.setAuditLogEventsCallback(caller.getUid(), callback);
18346     }
18347 
18348     @Override
18349     public long forceSecurityLogs() {
18350         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
18351                         || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS),
18352                 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call "
18353                         + "forceSecurityLogs");
18354         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
18355             throw new IllegalStateException("logging is not available");
18356         }
18357         return mSecurityLogMonitor.forceLogs();
18358     }
18359 
18360     @Override
18361     public boolean isUninstallInQueue(final String packageName) {
18362         final CallerIdentity caller = getCallerIdentity();
18363         Preconditions.checkCallAuthorization(
18364                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
18365 
18366         UserPackage packageUserPair = UserPackage.of(caller.getUserId(), packageName);
18367         synchronized (getLockObject()) {
18368             return mPackagesToRemove.contains(packageUserPair);
18369         }
18370     }
18371 
18372     @Override
18373     public void uninstallPackageWithActiveAdmins(final String packageName) {
18374         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
18375 
18376         final CallerIdentity caller = getCallerIdentity();
18377         Preconditions.checkCallAuthorization(
18378                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
18379 
18380         final int userId = caller.getUserId();
18381         enforceUserUnlocked(userId);
18382 
18383         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
18384         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
18385             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
18386         }
18387 
18388         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
18389         if (getDeviceOwnerUserId() == userId && deviceOwner != null
18390                 && packageName.equals(deviceOwner.getPackageName())) {
18391             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
18392         }
18393 
18394         final UserPackage packageUserPair = UserPackage.of(userId, packageName);
18395         synchronized (getLockObject()) {
18396             mPackagesToRemove.add(packageUserPair);
18397         }
18398 
18399         // All active admins on the user.
18400         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
18401 
18402         // Active admins in the target package.
18403         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
18404         if (allActiveAdmins != null) {
18405             for (ComponentName activeAdmin : allActiveAdmins) {
18406                 if (packageName.equals(activeAdmin.getPackageName())) {
18407                     packageActiveAdmins.add(activeAdmin);
18408                     removeActiveAdmin(activeAdmin, userId);
18409                 }
18410             }
18411         }
18412         if (packageActiveAdmins.size() == 0) {
18413             startUninstallIntent(packageName, userId);
18414         } else {
18415             mHandler.postDelayed(new Runnable() {
18416                 @Override
18417                 public void run() {
18418                     for (ComponentName activeAdmin : packageActiveAdmins) {
18419                         removeAdminArtifacts(activeAdmin, userId);
18420                     }
18421                     startUninstallIntent(packageName, userId);
18422                 }
18423             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
18424         }
18425     }
18426 
18427     @Override
18428     public boolean isDeviceProvisioned() {
18429         final CallerIdentity caller = getCallerIdentity();
18430         Preconditions.checkCallAuthorization(canManageUsers(caller));
18431 
18432         synchronized (getLockObject()) {
18433             return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
18434         }
18435     }
18436 
18437     private boolean isCurrentUserDemo() {
18438         if (UserManager.isDeviceInDemoMode(mContext)) {
18439             final int userId = mInjector.userHandleGetCallingUserId();
18440             return mInjector.binderWithCleanCallingIdentity(
18441                     () -> mUserManager.getUserInfo(userId).isDemo());
18442         }
18443         return false;
18444     }
18445 
18446     private void removePackageIfRequired(final String packageName, final int userId) {
18447         if (!packageHasActiveAdmins(packageName, userId)) {
18448             // Will not do anything if uninstall was not requested or was already started.
18449             startUninstallIntent(packageName, userId);
18450         }
18451     }
18452 
18453     private void startUninstallIntent(final String packageName, final int userId) {
18454         final UserPackage packageUserPair = UserPackage.of(userId, packageName);
18455         synchronized (getLockObject()) {
18456             if (!mPackagesToRemove.contains(packageUserPair)) {
18457                 // Do nothing if uninstall was not requested or was already started.
18458                 return;
18459             }
18460             mPackagesToRemove.remove(packageUserPair);
18461         }
18462         if (!isPackageInstalledForUser(packageName, userId)) {
18463             // Package does not exist. Nothing to do.
18464             return;
18465         }
18466 
18467         try { // force stop the package before uninstalling
18468             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
18469         } catch (RemoteException re) {
18470             Slogf.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
18471         }
18472         final Uri packageURI = Uri.parse("package:" + packageName);
18473         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
18474         uninstallIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
18475         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
18476     }
18477 
18478     /**
18479      * Removes the admin from the policy. Ideally called after the admin's
18480      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
18481      *
18482      * @param adminReceiver The admin to remove
18483      * @param userHandle The user for which this admin has to be removed.
18484      */
18485     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
18486         synchronized (getLockObject()) {
18487             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
18488             if (admin == null) {
18489                 return;
18490             }
18491             final DevicePolicyData policy = getUserData(userHandle);
18492             final boolean doProxyCleanup = admin.info.usesPolicy(
18493                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
18494             policy.mAdminList.remove(admin);
18495             policy.mAdminMap.remove(adminReceiver);
18496             policy.validatePasswordOwner();
18497             if (doProxyCleanup) {
18498                 resetGlobalProxyLocked(policy);
18499             }
18500             pushActiveAdminPackagesLocked(userHandle);
18501             saveSettingsLocked(userHandle);
18502             updateMaximumTimeToLockLocked(userHandle);
18503 
18504             Slogf.d(LOG_TAG,
18505                     "Removing device admin " + adminReceiver + " from user " + userHandle);
18506             logStackTrace("removeAdminArtifacts");
18507 
18508             policy.mRemovingAdmins.remove(adminReceiver);
18509             Slogf.d(LOG_TAG, "Current state of DevicePolicyData#mRemovingAdmins for user "
18510                     + userHandle + ": " + policy.mRemovingAdmins);
18511 
18512             Slogf.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
18513         }
18514         pushMeteredDisabledPackages(userHandle);
18515     }
18516 
18517     @Override
18518     public void setDeviceProvisioningConfigApplied() {
18519         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
18520 
18521         synchronized (getLockObject()) {
18522             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
18523             policy.mDeviceProvisioningConfigApplied = true;
18524             saveSettingsLocked(UserHandle.USER_SYSTEM);
18525         }
18526     }
18527 
18528     @Override
18529     public boolean isDeviceProvisioningConfigApplied() {
18530         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
18531 
18532         synchronized (getLockObject()) {
18533             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
18534             return policy.mDeviceProvisioningConfigApplied;
18535         }
18536     }
18537 
18538     /**
18539      * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
18540      *
18541      * It's added for testing only. Please use this API carefully if it's used by other system app
18542      * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
18543      * apps.
18544      */
18545     @Override
18546     public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
18547         Preconditions.checkCallAuthorization(
18548                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
18549 
18550         boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
18551                 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
18552         DevicePolicyData policy = getUserData(userId);
18553         policy.mUserSetupComplete = isUserCompleted;
18554         mStateCache.setDeviceProvisioned(isUserCompleted);
18555         synchronized (getLockObject()) {
18556             saveSettingsLocked(userId);
18557         }
18558     }
18559 
18560     @Override
18561     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
18562         if (!mHasFeature) {
18563             return;
18564         }
18565         Objects.requireNonNull(admin, "ComponentName is null");
18566 
18567         final CallerIdentity caller = getCallerIdentity(admin);
18568         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
18569                 || isProfileOwner(caller) || isFinancedDeviceOwner(caller));
18570 
18571         // Backup service has to be enabled on the main user in order for it to be enabled on
18572         // secondary users.
18573         if (Flags.headlessSingleUserFixes() && isDeviceOwner(caller)
18574                 && getHeadlessDeviceOwnerModeForDeviceOwner()
18575                 == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER) {
18576             toggleBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
18577         }
18578 
18579         toggleBackupServiceActive(caller.getUserId(), enabled);
18580 
18581         if (Flags.backupServiceSecurityLogEventEnabled()) {
18582             if (SecurityLog.isLoggingEnabled()) {
18583                 SecurityLog.writeEvent(SecurityLog.TAG_BACKUP_SERVICE_TOGGLED,
18584                         caller.getPackageName(), caller.getUserId(), enabled ? 1 : 0);
18585             }
18586         }
18587     }
18588 
18589     @Override
18590     public boolean isBackupServiceEnabled(ComponentName admin) {
18591         if (!mHasFeature) {
18592             return true;
18593         }
18594         Objects.requireNonNull(admin, "ComponentName is null");
18595 
18596         final CallerIdentity caller = getCallerIdentity(admin);
18597         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
18598                 || isProfileOwner(caller) || isFinancedDeviceOwner(caller));
18599 
18600         return mInjector.binderWithCleanCallingIdentity(() -> {
18601             synchronized (getLockObject()) {
18602                 try {
18603                     IBackupManager ibm = mInjector.getIBackupManager();
18604                     return ibm != null && ibm.isBackupServiceActive(caller.getUserId());
18605                 } catch (RemoteException e) {
18606                     throw new IllegalStateException("Failed requesting backup service state.", e);
18607                 }
18608             }
18609         });
18610     }
18611 
18612     @Override
18613     public boolean bindDeviceAdminServiceAsUser(
18614             @NonNull ComponentName admin, @NonNull IApplicationThread caller,
18615             @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
18616             @NonNull IServiceConnection connection, long flags, @UserIdInt int targetUserId) {
18617         if (!mHasFeature) {
18618             return false;
18619         }
18620         Objects.requireNonNull(admin);
18621         Objects.requireNonNull(caller);
18622         Objects.requireNonNull(serviceIntent);
18623         Preconditions.checkArgument(
18624                 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
18625                 "Service intent must be explicit (with a package name or component): "
18626                         + serviceIntent);
18627         Objects.requireNonNull(connection);
18628         Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
18629                 "target user id must be different from the calling user id");
18630 
18631         if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
18632             throw new SecurityException("Not allowed to bind to target user id");
18633         }
18634 
18635         final String targetPackage;
18636         synchronized (getLockObject()) {
18637             targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
18638         }
18639 
18640         final long callingIdentity = mInjector.binderClearCallingIdentity();
18641         try {
18642             // Validate and sanitize the incoming service intent.
18643             final Intent sanitizedIntent =
18644                     createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
18645             if (sanitizedIntent == null) {
18646                 // Fail, cannot lookup the target service.
18647                 return false;
18648             }
18649             // Ask ActivityManager to bind it. Notice that we are binding the service with the
18650             // caller app instead of DevicePolicyManagerService.
18651             return mInjector.getIActivityManager().bindService(
18652                     caller, activtiyToken, serviceIntent,
18653                     serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
18654                     connection, flags, mContext.getOpPackageName(),
18655                     targetUserId) != 0;
18656         } catch (RemoteException ex) {
18657             // Same process, should not happen.
18658         } finally {
18659             mInjector.binderRestoreCallingIdentity(callingIdentity);
18660         }
18661 
18662         // Failed to bind.
18663         return false;
18664     }
18665 
18666     @Override
18667     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
18668         if (!mHasFeature) {
18669             return Collections.emptyList();
18670         }
18671         Objects.requireNonNull(admin);
18672         final CallerIdentity caller = getCallerIdentity(admin);
18673         Preconditions.checkCallAuthorization(
18674                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
18675 
18676         synchronized (getLockObject()) {
18677             final int callingUserId = caller.getUserId();
18678             return mInjector.binderWithCleanCallingIdentity(() -> {
18679                 ArrayList<UserHandle> targetUsers = new ArrayList<>();
18680                 if (!isDeviceOwner(admin, callingUserId)) {
18681                     // Profile owners can only bind to the device owner.
18682                     if (canUserBindToDeviceOwnerLocked(callingUserId)) {
18683                         targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
18684                     }
18685                 } else {
18686                     // Caller is the device owner: Look for profile owners that it can bind to.
18687                     final List<UserInfo> userInfos = mUserManager.getAliveUsers();
18688                     for (int i = 0; i < userInfos.size(); i++) {
18689                         final int userId = userInfos.get(i).id;
18690                         if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
18691                             targetUsers.add(UserHandle.of(userId));
18692                         }
18693                     }
18694                 }
18695 
18696                 return targetUsers;
18697             });
18698         }
18699     }
18700 
18701     private boolean canUserBindToDeviceOwnerLocked(int userId) {
18702         // There has to be a device owner, under another user id.
18703         if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
18704             return false;
18705         }
18706 
18707         // The user must have a profile owner that belongs to the same package as the device owner.
18708         if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
18709                 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
18710             return false;
18711         }
18712 
18713         // The user must be affiliated.
18714         return isUserAffiliatedWithDeviceLocked(userId);
18715     }
18716 
18717     private boolean hasIncompatibleAccountsOnAnyUser() {
18718         if (mHasIncompatibleAccounts == null) {
18719             // Hasn't loaded for the first time yet - assume the worst
18720             return true;
18721         }
18722 
18723         for (boolean hasIncompatible : mHasIncompatibleAccounts.values()) {
18724             if (hasIncompatible) {
18725                 return true;
18726             }
18727         }
18728 
18729         return false;
18730     }
18731 
18732     private boolean hasIncompatibleAccounts(int userId) {
18733         return mHasIncompatibleAccounts == null ? true
18734                 : mHasIncompatibleAccounts.getOrDefault(userId, /* default= */ false);
18735     }
18736 
18737     /**
18738      * Return true if a given user has any accounts that'll prevent installing a device or profile
18739      * owner {@code owner}.
18740      * - If the user has no accounts, then return false.
18741      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
18742      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
18743      *   ..._DISALLOWED, return true.
18744      * - Otherwise return false.
18745      *
18746      * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
18747      * when the caller is not ADB.
18748      *
18749      * DO NOT CALL IT WITH THE DPMS LOCK HELD.
18750      */
18751     private boolean hasIncompatibleAccountsOrNonAdbNoLock(CallerIdentity caller,
18752             int userId, @Nullable ComponentName owner) {
18753         if (!isAdb(caller)) {
18754             return true;
18755         }
18756         wtfIfInLock();
18757 
18758         return mInjector.binderWithCleanCallingIdentity(() -> {
18759             AccountManager am =
18760                     mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0)
18761                             .getSystemService(AccountManager.class);
18762             Account[] accounts = am.getAccounts();
18763             if (accounts.length == 0) {
18764                 return false;
18765             }
18766             synchronized (getLockObject()) {
18767                 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
18768                     Slogf.w(LOG_TAG,
18769                             "Non test-only owner can't be installed with existing accounts.");
18770                     return true;
18771                 }
18772             }
18773 
18774             boolean compatible = !hasIncompatibleAccounts(userId);
18775             if (compatible) {
18776                 Slogf.w(LOG_TAG, "All accounts are compatible");
18777             } else {
18778                 Slogf.e(LOG_TAG, "Found incompatible accounts");
18779             }
18780             return !compatible;
18781         });
18782     }
18783 
18784     ThreadPoolExecutor calculateHasIncompatibleAccountsExecutor = new ThreadPoolExecutor(
18785             1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
18786 
18787     @Override
18788     public void calculateHasIncompatibleAccounts() {
18789         if (calculateHasIncompatibleAccountsExecutor.getQueue().size() > 1) {
18790             return;
18791         }
18792         new CalculateHasIncompatibleAccountsTask().executeOnExecutor(
18793                 calculateHasIncompatibleAccountsExecutor);
18794     }
18795 
18796     @Nullable
18797     private volatile Map<Integer, Boolean> mHasIncompatibleAccounts;
18798 
18799     class CalculateHasIncompatibleAccountsTask extends AsyncTask<
18800             Void, Void, Map<Integer, Boolean>> {
18801         private static final String[] FEATURE_ALLOW =
18802                 {DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED};
18803         private static final String[] FEATURE_DISALLOW =
18804                 {DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED};
18805 
18806         @Override
18807         protected Map<Integer, Boolean> doInBackground(Void... args) {
18808             List<UserInfo> users = mUserManagerInternal.getUsers(/* excludeDying= */ true);
18809             Map<Integer, Boolean> results = new HashMap<>();
18810             for (UserInfo userInfo : users) {
18811                 results.put(userInfo.id, userHasIncompatibleAccounts(userInfo.id));
18812             }
18813 
18814             return results;
18815         }
18816 
18817         private boolean userHasIncompatibleAccounts(int id) {
18818             AccountManager am = mContext.createContextAsUser(UserHandle.of(id), /* flags= */ 0)
18819                     .getSystemService(AccountManager.class);
18820             Account[] accounts = am.getAccounts();
18821 
18822             for (Account account : accounts) {
18823                 if (hasAccountFeatures(am, account, FEATURE_DISALLOW)) {
18824                     return true;
18825                 }
18826                 if (!hasAccountFeatures(am, account, FEATURE_ALLOW)) {
18827                     return true;
18828                 }
18829             }
18830 
18831             return false;
18832         }
18833 
18834         @Override
18835         protected void onPostExecute(Map<Integer, Boolean> results) {
18836             mHasIncompatibleAccounts = Collections.unmodifiableMap(results);
18837 
18838             Slogf.i(LOG_TAG, "Finished calculating hasIncompatibleAccountsTask");
18839         }
18840 
18841         private static boolean hasAccountFeatures(AccountManager am, Account account,
18842                 String[] features) {
18843             try {
18844                 return am.hasFeatures(account, features, null, null)
18845                         .getResult(30, TimeUnit.SECONDS);
18846             } catch (Exception e) {
18847                 Slogf.w(LOG_TAG, "Failed to get account feature", e);
18848                 return false;
18849             }
18850         }
18851     };
18852 
18853     private boolean isAdb(CallerIdentity caller) {
18854         return isShellUid(caller) || isRootUid(caller);
18855     }
18856 
18857     @Override
18858     public void setNetworkLoggingEnabled(@Nullable ComponentName admin,
18859             @NonNull String packageName, boolean enabled) {
18860         if (!mHasFeature) {
18861             return;
18862         }
18863         final CallerIdentity caller = getCallerIdentity(admin, packageName);
18864         final boolean isManagedProfileOwner = isProfileOwner(caller)
18865                 && isManagedProfile(caller.getUserId());
18866         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
18867                 && (isDefaultDeviceOwner(caller) || isManagedProfileOwner))
18868                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)));
18869 
18870         synchronized (getLockObject()) {
18871             if (enabled == isNetworkLoggingEnabledInternalLocked()) {
18872                 // already in the requested state
18873                 return;
18874             }
18875             final ActiveAdmin activeAdmin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
18876             activeAdmin.isNetworkLoggingEnabled = enabled;
18877             if (!enabled) {
18878                 activeAdmin.numNetworkLoggingNotifications = 0;
18879                 activeAdmin.lastNetworkLoggingNotificationTimeMs = 0;
18880             }
18881             saveSettingsLocked(caller.getUserId());
18882             setNetworkLoggingActiveInternal(enabled);
18883 
18884             DevicePolicyEventLogger
18885                     .createEvent(DevicePolicyEnums.SET_NETWORK_LOGGING_ENABLED)
18886                     .setAdmin(caller.getPackageName())
18887                     .setBoolean(/* isDelegate */ admin == null)
18888                     .setInt(enabled ? 1 : 0)
18889                     .setStrings(isManagedProfileOwner
18890                             ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER)
18891                     .write();
18892         }
18893     }
18894 
18895     private void setNetworkLoggingActiveInternal(boolean active) {
18896         mInjector.binderWithCleanCallingIdentity(() -> {
18897             boolean shouldSendNotification = false;
18898             synchronized (getLockObject()) {
18899                 if (active) {
18900                     if (mNetworkLogger == null) {
18901                         final int affectedUserId = getNetworkLoggingAffectedUser();
18902                         mNetworkLogger = new NetworkLogger(this,
18903                                 mInjector.getPackageManagerInternal(),
18904                                 affectedUserId == UserHandle.USER_SYSTEM
18905                                         ? UserHandle.USER_ALL : affectedUserId);
18906                     }
18907                     if (!mNetworkLogger.startNetworkLogging()) {
18908                         mNetworkLogger = null;
18909                         Slogf.wtf(LOG_TAG, "Network logging could not be started due to the logging"
18910                                 + " service not being available yet.");
18911                     }
18912                     maybePauseDeviceWideLoggingLocked();
18913                     shouldSendNotification = shouldSendNetworkLoggingNotificationLocked();
18914                 } else {
18915                     if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
18916                         Slogf.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
18917                                 + " service not being available yet.");
18918                     }
18919                     mNetworkLogger = null;
18920                 }
18921             }
18922             if (active) {
18923                 if (shouldSendNotification) {
18924                     mHandler.post(() -> handleSendNetworkLoggingNotification());
18925                 }
18926             } else {
18927                 mHandler.post(() -> handleCancelNetworkLoggingNotification());
18928             }
18929         });
18930     }
18931 
18932     private @UserIdInt int getNetworkLoggingAffectedUser() {
18933         synchronized (getLockObject()) {
18934             if (mOwners.hasDeviceOwner()) {
18935                 return mOwners.getDeviceOwnerUserId();
18936             } else {
18937                 return mInjector.binderWithCleanCallingIdentity(
18938                         () -> getManagedUserId());
18939             }
18940         }
18941     }
18942 
18943     private ActiveAdmin getNetworkLoggingControllingAdminLocked() {
18944         int affectedUserId = getNetworkLoggingAffectedUser();
18945         if (affectedUserId < 0) {
18946             return null;
18947         }
18948         return getDeviceOrProfileOwnerAdminLocked(affectedUserId);
18949     }
18950 
18951     @Override
18952     public long forceNetworkLogs() {
18953         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
18954                 || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS),
18955                 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call "
18956                         + "forceNetworkLogs");
18957         synchronized (getLockObject()) {
18958             if (!isNetworkLoggingEnabledInternalLocked()) {
18959                 throw new IllegalStateException("logging is not available");
18960             }
18961             if (mNetworkLogger != null) {
18962                 return mInjector.binderWithCleanCallingIdentity(
18963                         () -> mNetworkLogger.forceBatchFinalization());
18964             }
18965             return 0;
18966         }
18967     }
18968 
18969     /** Pauses security and network logging if there are unaffiliated users on the device */
18970     @GuardedBy("getLockObject()")
18971     private void maybePauseDeviceWideLoggingLocked() {
18972         if (!areAllUsersAffiliatedWithDeviceLocked()) {
18973             if (mOwners.hasDeviceOwner()) {
18974                 Slogf.i(LOG_TAG, "There are unaffiliated users, network logging will be "
18975                         + "paused if enabled.");
18976                 if (mNetworkLogger != null) {
18977                     mNetworkLogger.pause();
18978                 }
18979             }
18980             // TODO: We need to also enable this when someone is managing using permission
18981             if (!isOrganizationOwnedDeviceWithManagedProfile()) {
18982                 Slogf.i(LOG_TAG,
18983                         "Not org-owned managed profile device, security logging will be "
18984                                 + "paused if enabled.");
18985                 mSecurityLogMonitor.pause();
18986             }
18987         }
18988     }
18989 
18990     /** Resumes security and network logging (if they are enabled) if all users are affiliated */
18991     @GuardedBy("getLockObject()")
18992     private void maybeResumeDeviceWideLoggingLocked() {
18993         boolean allUsersAffiliated = areAllUsersAffiliatedWithDeviceLocked();
18994         boolean orgOwnedProfileDevice = isOrganizationOwnedDeviceWithManagedProfile();
18995         mInjector.binderWithCleanCallingIdentity(() -> {
18996             if (allUsersAffiliated || orgOwnedProfileDevice) {
18997                 mSecurityLogMonitor.resume();
18998             }
18999             // If there is no device owner, then per-user network logging may be enabled for the
19000             // managed profile. In which case, all users do not need to be affiliated.
19001             if (allUsersAffiliated || !mOwners.hasDeviceOwner()) {
19002                 if (mNetworkLogger != null) {
19003                     mNetworkLogger.resume();
19004                 }
19005             }
19006         });
19007     }
19008 
19009     /** Deletes any security and network logs that might have been collected so far */
19010     @GuardedBy("getLockObject()")
19011     private void discardDeviceWideLogsLocked() {
19012         mSecurityLogMonitor.discardLogs();
19013         if (mNetworkLogger != null) {
19014             mNetworkLogger.discardLogs();
19015         }
19016         // TODO: We should discard pre-boot security logs here too, as otherwise those
19017         // logs (which might contain data from the user just removed) will be
19018         // available after next boot.
19019     }
19020 
19021     /**
19022      * This API is cached: invalidate with invalidateBinderCaches().
19023      */
19024     @Override
19025     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin,
19026             @NonNull String packageName) {
19027         if (!mHasFeature) {
19028             return false;
19029         }
19030         final CallerIdentity caller = getCallerIdentity(admin, packageName);
19031         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
19032                 &&  (isDefaultDeviceOwner(caller)
19033                 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))))
19034                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING))
19035                 || hasCallingOrSelfPermission(permission.MANAGE_USERS));
19036 
19037         synchronized (getLockObject()) {
19038             return isNetworkLoggingEnabledInternalLocked();
19039         }
19040     }
19041 
19042     private boolean isNetworkLoggingEnabledInternalLocked() {
19043         ActiveAdmin activeAdmin = getNetworkLoggingControllingAdminLocked();
19044         return (activeAdmin != null) && activeAdmin.isNetworkLoggingEnabled;
19045     }
19046 
19047     /*
19048      * A maximum of 1200 events are returned, and the total marshalled size is in the order of
19049      * 100kB, so returning a List instead of ParceledListSlice is acceptable.
19050      * Ideally this would be done with ParceledList, however it only supports homogeneous types.
19051      *
19052      * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
19053      */
19054     @Override
19055     public List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
19056             @NonNull String packageName, long batchToken) {
19057         if (!mHasFeature) {
19058             return null;
19059         }
19060         final CallerIdentity caller = getCallerIdentity(admin, packageName);
19061         final boolean isManagedProfileOwner = isProfileOwner(caller)
19062                 && isManagedProfile(caller.getUserId());
19063         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
19064                 &&  (isDefaultDeviceOwner(caller) || isManagedProfileOwner))
19065                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)));
19066         if (mOwners.hasDeviceOwner()) {
19067             checkAllUsersAreAffiliatedWithDevice();
19068         }
19069 
19070         synchronized (getLockObject()) {
19071             if (mNetworkLogger == null || !isNetworkLoggingEnabledInternalLocked()) {
19072                 return null;
19073             }
19074             DevicePolicyEventLogger
19075                     .createEvent(DevicePolicyEnums.RETRIEVE_NETWORK_LOGS)
19076                     .setAdmin(caller.getPackageName())
19077                     .setBoolean(/* isDelegate */ admin == null)
19078                     .setStrings(isManagedProfileOwner
19079                             ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER)
19080                     .write();
19081 
19082             final long currentTime = System.currentTimeMillis();
19083             DevicePolicyData policyData = getUserData(caller.getUserId());
19084             if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
19085                 policyData.mLastNetworkLogsRetrievalTime = currentTime;
19086                 saveSettingsLocked(caller.getUserId());
19087             }
19088             return mNetworkLogger.retrieveLogs(batchToken);
19089         }
19090     }
19091 
19092     /**
19093      * Returns whether it's time to post another network logging notification. When returning true,
19094      * this method has the side-effect of updating the recorded last network logging notification
19095      * time to now.
19096      */
19097     private boolean shouldSendNetworkLoggingNotificationLocked() {
19098         ensureLocked();
19099         // Send a network logging notification if the admin is a device owner, not profile owner.
19100         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19101         if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
19102             return false;
19103         }
19104         if (deviceOwner.numNetworkLoggingNotifications
19105                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
19106             return false;
19107         }
19108         final long now = System.currentTimeMillis();
19109         if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
19110             return false;
19111         }
19112         deviceOwner.numNetworkLoggingNotifications++;
19113         if (deviceOwner.numNetworkLoggingNotifications
19114                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
19115             deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
19116         } else {
19117             deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
19118         }
19119         saveSettingsLocked(deviceOwner.getUserHandle().getIdentifier());
19120         return true;
19121     }
19122 
19123     private void handleSendNetworkLoggingNotification() {
19124         final PackageManagerInternal pm = mInjector.getPackageManagerInternal();
19125         final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
19126         intent.setPackage(pm.getSystemUiServiceComponent().getPackageName());
19127         mNetworkLoggingNotificationUserId = getCurrentForegroundUserId();
19128         // Simple notification clicks are immutable
19129         final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent,
19130                 PendingIntent.FLAG_IMMUTABLE, UserHandle.CURRENT);
19131 
19132         final String title = getNetworkLoggingTitle();
19133         final String text = getNetworkLoggingText();
19134         Notification notification =
19135                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
19136                 .setSmallIcon(R.drawable.ic_info_outline)
19137                 .setContentTitle(title)
19138                 .setContentText(text)
19139                 .setTicker(title)
19140                 .setShowWhen(true)
19141                 .setContentIntent(pendingIntent)
19142                 .setStyle(new Notification.BigTextStyle().bigText(text))
19143                 .build();
19144         Slogf.i(LOG_TAG, "Sending network logging notification to user %d",
19145                 mNetworkLoggingNotificationUserId);
19146         mInjector.getNotificationManager().notifyAsUser(/* tag= */ null,
19147                 SystemMessage.NOTE_NETWORK_LOGGING, notification,
19148                 UserHandle.of(mNetworkLoggingNotificationUserId));
19149     }
19150 
19151     private String getNetworkLoggingTitle() {
19152         return getUpdatableString(
19153                 NETWORK_LOGGING_TITLE, R.string.network_logging_notification_title);
19154     }
19155 
19156     private String getNetworkLoggingText() {
19157         return getUpdatableString(
19158                 NETWORK_LOGGING_MESSAGE, R.string.network_logging_notification_text);
19159     }
19160 
19161     private void handleCancelNetworkLoggingNotification() {
19162         if (mNetworkLoggingNotificationUserId == UserHandle.USER_NULL) {
19163             // Happens when setNetworkLoggingActive(false) is called before called with true
19164             Slogf.d(LOG_TAG, "Not cancelling network logging notification for USER_NULL");
19165             return;
19166         }
19167 
19168         Slogf.i(LOG_TAG, "Cancelling network logging notification for user %d",
19169                 mNetworkLoggingNotificationUserId);
19170         mInjector.getNotificationManager().cancelAsUser(/* tag= */ null,
19171                 SystemMessage.NOTE_NETWORK_LOGGING,
19172                 UserHandle.of(mNetworkLoggingNotificationUserId));
19173         mNetworkLoggingNotificationUserId = UserHandle.USER_NULL;
19174     }
19175 
19176     /**
19177      * Return the package name of owner in a given user.
19178      */
19179     private String getOwnerPackageNameForUserLocked(int userId) {
19180         return mOwners.getDeviceOwnerUserId() == userId
19181                 ? mOwners.getDeviceOwnerPackageName()
19182                 : mOwners.getProfileOwnerPackage(userId);
19183     }
19184 
19185     /**
19186      * @param rawIntent Original service intent specified by caller. It must be explicit.
19187      * @param expectedPackageName The expected package name of the resolved service.
19188      * @return Intent that have component explicitly set. {@code null} if no service is resolved
19189      *     with the given intent.
19190      * @throws SecurityException if the intent is resolved to an invalid service.
19191      */
19192     private Intent createCrossUserServiceIntent(
19193             @NonNull Intent rawIntent, @NonNull String expectedPackageName,
19194             @UserIdInt int targetUserId) throws RemoteException, SecurityException {
19195         ResolveInfo info = mIPackageManager.resolveService(
19196                 rawIntent,
19197                 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
19198                 0,  // flags
19199                 targetUserId);
19200         if (info == null || info.serviceInfo == null) {
19201             Slogf.e(LOG_TAG, "Fail to look up the service: %s or user %d is not running", rawIntent,
19202                     targetUserId);
19203             return null;
19204         }
19205         if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
19206             throw new SecurityException("Only allow to bind service in " + expectedPackageName);
19207         }
19208         // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
19209         if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
19210             throw new SecurityException(
19211                     "Service must be protected by BIND_DEVICE_ADMIN permission");
19212         }
19213         // It is the system server to bind the service, it would be extremely dangerous if it
19214         // can be exploited to bind any service. Set the component explicitly to make sure we
19215         // do not bind anything accidentally.
19216         rawIntent.setComponent(info.serviceInfo.getComponentName());
19217         return rawIntent;
19218     }
19219 
19220     @Override
19221     public long getLastSecurityLogRetrievalTime() {
19222         final CallerIdentity caller = getCallerIdentity();
19223         Preconditions.checkCallAuthorization(
19224                 isDefaultDeviceOwner(caller) || canManageUsers(caller));
19225         return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
19226      }
19227 
19228     @Override
19229     public long getLastBugReportRequestTime() {
19230         final CallerIdentity caller = getCallerIdentity();
19231         Preconditions.checkCallAuthorization(
19232                 isDefaultDeviceOwner(caller) || canManageUsers(caller));
19233         return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
19234      }
19235 
19236     @Override
19237     public long getLastNetworkLogRetrievalTime() {
19238         final CallerIdentity caller = getCallerIdentity();
19239 
19240         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19241                 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))
19242                 || canManageUsers(caller));
19243         final int affectedUserId = getNetworkLoggingAffectedUser();
19244         return affectedUserId >= 0 ? getUserData(affectedUserId).mLastNetworkLogsRetrievalTime : -1;
19245     }
19246 
19247     @Override
19248     public boolean setResetPasswordToken(ComponentName admin, String callerPackageName,
19249             byte[] token) {
19250         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
19251             return false;
19252         }
19253         if (token == null || token.length < 32) {
19254             throw new IllegalArgumentException("token must be at least 32-byte long");
19255         }
19256         CallerIdentity caller;
19257         if (isUnicornFlagEnabled()) {
19258             caller = getCallerIdentity(admin, callerPackageName);
19259         } else {
19260             caller = getCallerIdentity(admin);
19261         }
19262         final int userId = caller.getUserId();
19263 
19264         if (isUnicornFlagEnabled()) {
19265             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
19266                     admin,
19267                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
19268                     caller.getPackageName(),
19269                     userId);
19270             Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
19271                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19272                     enforcingAdmin,
19273                     userId);
19274             long tokenHandle = addEscrowToken(
19275                     token, currentTokenHandle == null ? 0 : currentTokenHandle, userId);
19276             if (tokenHandle == 0) {
19277                 return false;
19278             }
19279             mDevicePolicyEngine.setLocalPolicy(
19280                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19281                     enforcingAdmin,
19282                     new LongPolicyValue(tokenHandle),
19283                     userId);
19284             return true;
19285         } else {
19286             Objects.requireNonNull(admin, "ComponentName is null");
19287             Preconditions.checkCallAuthorization(
19288                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19289             synchronized (getLockObject()) {
19290                 DevicePolicyData policy = getUserData(userId);
19291                 policy.mPasswordTokenHandle = addEscrowToken(
19292                         token, policy.mPasswordTokenHandle, userId);
19293                 saveSettingsLocked(userId);
19294                 return policy.mPasswordTokenHandle != 0;
19295             }
19296         }
19297     }
19298 
19299     private long addEscrowToken(byte[] token, long currentPasswordTokenHandle, int userId) {
19300         resetEscrowToken(currentPasswordTokenHandle, userId);
19301         return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.addEscrowToken(
19302                 token, userId, /* EscrowTokenStateChangeCallback= */ null));
19303     }
19304 
19305     private boolean resetEscrowToken(long tokenHandle, int userId) {
19306         return mInjector.binderWithCleanCallingIdentity(() -> {
19307             if (tokenHandle != 0) {
19308                 return mLockPatternUtils.removeEscrowToken(tokenHandle, userId);
19309             }
19310             return false;
19311         });
19312     }
19313 
19314     @Override
19315     public boolean clearResetPasswordToken(ComponentName admin, String callerPackageName) {
19316         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
19317             return false;
19318         }
19319         CallerIdentity caller;
19320         if (isUnicornFlagEnabled()) {
19321             caller = getCallerIdentity(admin, callerPackageName);
19322         } else {
19323             caller = getCallerIdentity(admin);
19324         }
19325         final int userId = caller.getUserId();
19326         boolean result = false;
19327 
19328         if (isUnicornFlagEnabled()) {
19329             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
19330                     admin,
19331                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
19332                     caller.getPackageName(),
19333                     userId);
19334             Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
19335                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19336                     enforcingAdmin,
19337                     userId);
19338             if (currentTokenHandle != null) {
19339                 result = resetEscrowToken(currentTokenHandle, userId);
19340                 mDevicePolicyEngine.removeLocalPolicy(
19341                         PolicyDefinition.RESET_PASSWORD_TOKEN,
19342                         enforcingAdmin,
19343                         userId);
19344             }
19345         } else {
19346             Objects.requireNonNull(admin, "ComponentName is null");
19347             Preconditions.checkCallAuthorization(
19348                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19349             synchronized (getLockObject()) {
19350                 DevicePolicyData policy = getUserData(userId);
19351                 if (policy.mPasswordTokenHandle != 0) {
19352                     result = resetEscrowToken(policy.mPasswordTokenHandle, userId);
19353                     policy.mPasswordTokenHandle = 0;
19354                     saveSettingsLocked(userId);
19355                 }
19356             }
19357         }
19358         return result;
19359     }
19360 
19361     @Override
19362     public boolean isResetPasswordTokenActive(ComponentName admin, String callerPackageName) {
19363         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
19364             return false;
19365         }
19366         CallerIdentity caller;
19367         if (isUnicornFlagEnabled()) {
19368             caller = getCallerIdentity(admin, callerPackageName);
19369         } else {
19370             caller = getCallerIdentity(admin);
19371         }
19372         int userId = caller.getUserId();
19373 
19374         if (isUnicornFlagEnabled()) {
19375             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
19376                     admin,
19377                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
19378                     caller.getPackageName(),
19379                     userId);
19380             Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
19381                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19382                     enforcingAdmin,
19383                     userId);
19384             return isResetPasswordTokenActiveForUserLocked(
19385                     currentTokenHandle == null ? 0 : currentTokenHandle, userId);
19386         } else {
19387             Objects.requireNonNull(admin, "ComponentName is null");
19388             Preconditions.checkCallAuthorization(
19389                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19390             synchronized (getLockObject()) {
19391                 DevicePolicyData policy = getUserData(userId);
19392                 return isResetPasswordTokenActiveForUserLocked(policy.mPasswordTokenHandle, userId);
19393             }
19394         }
19395     }
19396 
19397     private boolean isResetPasswordTokenActiveForUserLocked(
19398             long passwordTokenHandle, int userHandle) {
19399         if (passwordTokenHandle != 0) {
19400             return mInjector.binderWithCleanCallingIdentity(() ->
19401                     mLockPatternUtils.isEscrowTokenActive(passwordTokenHandle, userHandle));
19402         }
19403         return false;
19404     }
19405 
19406     @Override
19407     public boolean resetPasswordWithToken(ComponentName admin, String callerPackageName,
19408             String passwordOrNull, byte[] token,
19409             int flags) {
19410         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
19411             return false;
19412         }
19413         Objects.requireNonNull(token);
19414 
19415         CallerIdentity caller;
19416         if (isUnicornFlagEnabled()) {
19417             caller = getCallerIdentity(admin, callerPackageName);
19418         } else {
19419             caller = getCallerIdentity(admin);
19420         }
19421 
19422         int userId = caller.getUserId();
19423         boolean result = false;
19424         final String password = passwordOrNull != null ? passwordOrNull : "";
19425 
19426         if (isUnicornFlagEnabled()) {
19427             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
19428                     admin,
19429                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
19430                     caller.getPackageName(),
19431                     userId);
19432             Long currentTokenHandle = mDevicePolicyEngine.getLocalPolicySetByAdmin(
19433                     PolicyDefinition.RESET_PASSWORD_TOKEN,
19434                     enforcingAdmin,
19435                     userId);
19436             if (currentTokenHandle != null && currentTokenHandle != 0) {
19437                 result = resetPasswordInternal(password, currentTokenHandle, token, flags, caller);
19438             } else {
19439                 Slogf.w(LOG_TAG, "No saved token handle");
19440             }
19441         } else {
19442             Objects.requireNonNull(admin, "ComponentName is null");
19443             Preconditions.checkCallAuthorization(
19444                     isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19445             synchronized (getLockObject()) {
19446                 DevicePolicyData policy = getUserData(userId);
19447                 if (policy.mPasswordTokenHandle != 0) {
19448                     result = resetPasswordInternal(
19449                             password, policy.mPasswordTokenHandle, token, flags, caller);
19450                 } else {
19451                     Slogf.w(LOG_TAG, "No saved token handle");
19452                 }
19453             }
19454         }
19455 
19456         if (result) {
19457             if (isUnicornFlagEnabled()) {
19458                 DevicePolicyEventLogger
19459                         .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN)
19460                         .setAdmin(callerPackageName)
19461                         .write();
19462             } else {
19463                 DevicePolicyEventLogger
19464                         .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN)
19465                         .setAdmin(caller.getComponentName())
19466                         .write();
19467             }
19468         }
19469         return result;
19470     }
19471 
19472     @Override
19473     public boolean isCurrentInputMethodSetByOwner() {
19474         final CallerIdentity caller = getCallerIdentity();
19475         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19476                 || isProfileOwner(caller) || canQueryAdminPolicy(caller) || isSystemUid(caller),
19477                 "Only profile owner, device owner, a caller with QUERY_ADMIN_POLICY "
19478                         + "permission or system may call this method.");
19479         return getUserData(caller.getUserId()).mCurrentInputMethodSet;
19480     }
19481 
19482     @Override
19483     public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
19484         final int userId = user.getIdentifier();
19485         final CallerIdentity caller = getCallerIdentity();
19486         Preconditions.checkCallAuthorization(
19487                 (isProfileOwner(caller) || isDefaultDeviceOwner(caller) || canQueryAdminPolicy(
19488                         caller)) && hasFullCrossUsersPermission(caller, userId));
19489 
19490         synchronized (getLockObject()) {
19491             return new StringParceledListSlice(
19492                     new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
19493         }
19494     }
19495 
19496     @Override
19497     public void clearApplicationUserData(ComponentName admin, String packageName,
19498             IPackageDataObserver callback) {
19499         Objects.requireNonNull(admin, "ComponentName is null");
19500         Objects.requireNonNull(packageName, "packageName is null");
19501         Objects.requireNonNull(callback, "callback is null");
19502 
19503         final CallerIdentity caller = getCallerIdentity(admin);
19504         Preconditions.checkCallAuthorization(
19505                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
19506         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CLEAR_APPLICATION_USER_DATA);
19507 
19508         long ident = mInjector.binderClearCallingIdentity();
19509         try {
19510             ActivityManager.getService().clearApplicationUserData(packageName, false, callback,
19511                     caller.getUserId());
19512         } catch(RemoteException re) {
19513             // Same process, should not happen.
19514         } catch (SecurityException se) {
19515             // This can happen e.g. for device admin packages, do not throw out the exception,
19516             // because callers have no means to know beforehand for which packages this might
19517             // happen. If so, we send back that removal failed.
19518             Slogf.w(LOG_TAG, "Not allowed to clear application user data for package "
19519                     + packageName, se);
19520             try {
19521                 callback.onRemoveCompleted(packageName, false);
19522             } catch (RemoteException re) {
19523                 // Caller is no longer available, ignore
19524             }
19525         } finally {
19526             mInjector.binderRestoreCallingIdentity(ident);
19527         }
19528     }
19529 
19530     @Override
19531     public void setLogoutEnabled(ComponentName admin, boolean enabled) {
19532         if (!mHasFeature) {
19533             return;
19534         }
19535         Objects.requireNonNull(admin, "ComponentName is null");
19536         final CallerIdentity caller = getCallerIdentity(admin);
19537         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19538         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOGOUT_ENABLED);
19539 
19540         synchronized (getLockObject()) {
19541             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19542             if (deviceOwner.isLogoutEnabled == enabled) {
19543                 // already in the requested state
19544                 return;
19545             }
19546             deviceOwner.isLogoutEnabled = enabled;
19547             saveSettingsLocked(caller.getUserId());
19548         }
19549     }
19550 
19551     @Override
19552     public boolean isLogoutEnabled() {
19553         if (!mHasFeature) {
19554             return false;
19555         }
19556         synchronized (getLockObject()) {
19557             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19558             return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
19559         }
19560     }
19561 
19562     @Override
19563     public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
19564             String provisioningAction) throws RemoteException {
19565         Preconditions.checkCallAuthorization(
19566                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
19567 
19568         return new ArrayList<>(
19569                 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
19570     }
19571 
19572     @Override
19573     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
19574             @Nullable PersistableBundle bundle) {
19575         if (!mHasFeature) {
19576             return;
19577         }
19578         Objects.requireNonNull(admin, "ComponentName is null");
19579         Objects.requireNonNull(target, "Target cannot be null.");
19580         Preconditions.checkArgument(!admin.equals(target),
19581                 "Provided administrator and target are the same object.");
19582         Preconditions.checkArgument(!admin.getPackageName().equals(target.getPackageName()),
19583                 "Provided administrator and target have the same package name.");
19584         if (bundle != null) {
19585             PolicySizeVerifier.enforceMaxStringLength(bundle, "bundle");
19586         }
19587 
19588         final CallerIdentity caller = getCallerIdentity(admin);
19589         Preconditions.checkCallAuthorization(
19590                 isDefaultDeviceOwner(caller) || isProfileOwner(caller));
19591 
19592         final int callingUserId = caller.getUserId();
19593         final DevicePolicyData policy = getUserData(callingUserId);
19594         final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId,
19595                 /* throwForMissingPermission= */ true);
19596         checkActiveAdminPrecondition(target, incomingDeviceInfo, policy);
19597         Preconditions.checkArgument(incomingDeviceInfo.supportsTransferOwnership(),
19598                 "Provided target does not support ownership transfer.");
19599 
19600         final long id = mInjector.binderClearCallingIdentity();
19601         String ownerType = null;
19602         try {
19603             synchronized (getLockObject()) {
19604                 /*
19605                 * We must ensure the whole process is atomic to prevent the device from ending up
19606                 * in an invalid state (e.g. no active admin). This could happen if the device
19607                 * is rebooted or work mode is turned off mid-transfer.
19608                 * In order to guarantee atomicity, we:
19609                 *
19610                 * 1. Save an atomic journal file describing the transfer process
19611                 * 2. Perform the transfer itself
19612                 * 3. Delete the journal file
19613                 *
19614                 * That way if the journal file exists on device boot, we know that the transfer
19615                 * must be reverted back to the original administrator. This logic is implemented in
19616                 * revertTransferOwnershipIfNecessaryLocked.
19617                 * */
19618                 if (bundle == null) {
19619                     bundle = new PersistableBundle();
19620                 }
19621                 if (isProfileOwner(caller)) {
19622                     ownerType = ADMIN_TYPE_PROFILE_OWNER;
19623                     prepareTransfer(admin, target, bundle, callingUserId,
19624                             ADMIN_TYPE_PROFILE_OWNER);
19625                     transferProfileOwnershipLocked(admin, target, callingUserId);
19626                     sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
19627                             getTransferOwnershipAdminExtras(bundle), callingUserId);
19628                     postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId);
19629                     if (isUserAffiliatedWithDeviceLocked(callingUserId)) {
19630                         notifyAffiliatedProfileTransferOwnershipComplete(callingUserId);
19631                     }
19632                 } else if (isDefaultDeviceOwner(caller)) {
19633                     ownerType = ADMIN_TYPE_DEVICE_OWNER;
19634                     prepareTransfer(admin, target, bundle, callingUserId,
19635                             ADMIN_TYPE_DEVICE_OWNER);
19636                     transferDeviceOwnershipLocked(admin, target, callingUserId);
19637                     sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
19638                             getTransferOwnershipAdminExtras(bundle));
19639                     postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId);
19640                 }
19641             }
19642         } finally {
19643             mInjector.binderRestoreCallingIdentity(id);
19644         }
19645         DevicePolicyEventLogger
19646                 .createEvent(DevicePolicyEnums.TRANSFER_OWNERSHIP)
19647                 .setAdmin(admin)
19648                 .setStrings(target.getPackageName(), ownerType)
19649                 .write();
19650     }
19651 
19652     private void transferSubscriptionOwnership(ComponentName admin, ComponentName target) {
19653         if (Flags.esimManagementEnabled()) {
19654             SubscriptionManager subscriptionManager = mContext.getSystemService(
19655                     SubscriptionManager.class);
19656             for (int subId : getSubscriptionIdsInternal(admin.getPackageName()).toArray()) {
19657                 try {
19658                     subscriptionManager.setGroupOwner(subId, target.getPackageName());
19659                 } catch (Exception e) {
19660                     // Shouldn't happen.
19661                     Slogf.e(LOG_TAG, e, "Error setting group owner for subId: " + subId);
19662                 }
19663             }
19664         }
19665     }
19666 
19667     private void prepareTransfer(ComponentName admin, ComponentName target,
19668             PersistableBundle bundle, int callingUserId, String adminType) {
19669         saveTransferOwnershipBundleLocked(bundle, callingUserId);
19670         mTransferOwnershipMetadataManager.saveMetadataFile(
19671                 new TransferOwnershipMetadataManager.Metadata(admin, target,
19672                         callingUserId, adminType));
19673     }
19674 
19675     private void postTransfer(String broadcast, int callingUserId) {
19676         deleteTransferOwnershipMetadataFileLocked();
19677         sendOwnerChangedBroadcast(broadcast, callingUserId);
19678     }
19679 
19680     private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) {
19681         final Bundle extras = new Bundle();
19682         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId));
19683         sendDeviceOwnerCommand(
19684                 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras);
19685     }
19686 
19687     /**
19688      * Transfers the profile owner for user with id profileOwnerUserId from admin to target.
19689      */
19690     private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target,
19691             int profileOwnerUserId) {
19692         transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId);
19693         mOwners.transferProfileOwner(target, profileOwnerUserId);
19694         Slogf.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId);
19695         mOwners.writeProfileOwner(profileOwnerUserId);
19696         mDeviceAdminServiceController.startServiceForAdmin(
19697                 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner");
19698     }
19699 
19700     /**
19701      * Transfers the device owner for user with id userId from admin to target.
19702      */
19703     private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) {
19704         transferActiveAdminUncheckedLocked(target, admin, userId);
19705         mOwners.transferDeviceOwnership(target);
19706         Slogf.i(LOG_TAG, "Device owner set: " + target + " on user " + userId);
19707         mOwners.writeDeviceOwner();
19708         mDeviceAdminServiceController.startServiceForAdmin(
19709                 target.getPackageName(), userId, "transfer-device-owner");
19710     }
19711 
19712     private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) {
19713         Bundle extras = new Bundle();
19714         if (bundle != null) {
19715             extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle);
19716         }
19717         return extras;
19718     }
19719 
19720     @Override
19721     public void setStartUserSessionMessage(
19722             ComponentName admin, CharSequence startUserSessionMessage) {
19723         if (!mHasFeature) {
19724             return;
19725         }
19726         Objects.requireNonNull(admin, "ComponentName is null");
19727         final CallerIdentity caller = getCallerIdentity(admin);
19728         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19729 
19730         final String startUserSessionMessageString =
19731                 startUserSessionMessage != null ? startUserSessionMessage.toString() : null;
19732 
19733         synchronized (getLockObject()) {
19734             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19735             if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) {
19736                 return;
19737             }
19738             deviceOwner.startUserSessionMessage = startUserSessionMessageString;
19739             saveSettingsLocked(caller.getUserId());
19740         }
19741 
19742         mInjector.getActivityManagerInternal()
19743                 .setSwitchingFromSystemUserMessage(startUserSessionMessageString);
19744     }
19745 
19746     @Override
19747     public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) {
19748         if (!mHasFeature) {
19749             return;
19750         }
19751         Objects.requireNonNull(admin, "ComponentName is null");
19752         final CallerIdentity caller = getCallerIdentity(admin);
19753         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19754 
19755         final String endUserSessionMessageString =
19756                 endUserSessionMessage != null ? endUserSessionMessage.toString() : null;
19757 
19758         synchronized (getLockObject()) {
19759             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19760             if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) {
19761                 return;
19762             }
19763             deviceOwner.endUserSessionMessage = endUserSessionMessageString;
19764             saveSettingsLocked(caller.getUserId());
19765         }
19766 
19767         mInjector.getActivityManagerInternal()
19768                 .setSwitchingToSystemUserMessage(endUserSessionMessageString);
19769     }
19770 
19771     @Override
19772     public String getStartUserSessionMessage(ComponentName admin) {
19773         if (!mHasFeature) {
19774             return null;
19775         }
19776         Objects.requireNonNull(admin, "ComponentName is null");
19777         final CallerIdentity caller = getCallerIdentity(admin);
19778         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19779 
19780         synchronized (getLockObject()) {
19781             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19782             return deviceOwner.startUserSessionMessage;
19783         }
19784     }
19785 
19786     @Override
19787     public String getEndUserSessionMessage(ComponentName admin) {
19788         if (!mHasFeature) {
19789             return null;
19790         }
19791         Objects.requireNonNull(admin, "ComponentName is null");
19792         final CallerIdentity caller = getCallerIdentity(admin);
19793         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19794 
19795         synchronized (getLockObject()) {
19796             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
19797             return deviceOwner.endUserSessionMessage;
19798         }
19799     }
19800 
19801     private void deleteTransferOwnershipMetadataFileLocked() {
19802         mTransferOwnershipMetadataManager.deleteMetadataFile();
19803     }
19804 
19805     @Override
19806     @Nullable
19807     public PersistableBundle getTransferOwnershipBundle() {
19808         final CallerIdentity caller = getCallerIdentity();
19809         Preconditions.checkCallAuthorization(
19810                 isProfileOwner(caller) || isDefaultDeviceOwner(caller));
19811 
19812         synchronized (getLockObject()) {
19813             final int callingUserId = caller.getUserId();
19814             final File bundleFile = new File(
19815                     mPathProvider.getUserSystemDirectory(callingUserId),
19816                     TRANSFER_OWNERSHIP_PARAMETERS_XML);
19817             if (!bundleFile.exists()) {
19818                 return null;
19819             }
19820             try (FileInputStream stream = new FileInputStream(bundleFile)) {
19821                 TypedXmlPullParser parser = Xml.resolvePullParser(stream);
19822                 parser.next();
19823                 return PersistableBundle.restoreFromXml(parser);
19824             } catch (IOException | XmlPullParserException | IllegalArgumentException e) {
19825                 Slogf.e(LOG_TAG, "Caught exception while trying to load the "
19826                         + "owner transfer parameters from file " + bundleFile, e);
19827                 return null;
19828             }
19829         }
19830     }
19831 
19832     @Override
19833     public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) {
19834         if (!mHasFeature || !mHasTelephonyFeature) {
19835             return -1;
19836         }
19837         Objects.requireNonNull(who, "ComponentName is null");
19838         Objects.requireNonNull(apnSetting, "ApnSetting is null in addOverrideApn");
19839         final CallerIdentity caller = getCallerIdentity(who);
19840         if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
19841             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19842                     || isManagedProfileOwner(caller));
19843         } else {
19844             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19845         }
19846 
19847         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
19848         if (tm != null) {
19849             return mInjector.binderWithCleanCallingIdentity(
19850                     () -> tm.addDevicePolicyOverrideApn(mContext, apnSetting));
19851         } else {
19852             Slogf.w(LOG_TAG, "TelephonyManager is null when trying to add override apn");
19853             return INVALID_APN_ID;
19854         }
19855     }
19856 
19857     @Override
19858     public boolean updateOverrideApn(@NonNull ComponentName who, int apnId,
19859             @NonNull ApnSetting apnSetting) {
19860         if (!mHasFeature || !mHasTelephonyFeature) {
19861             return false;
19862         }
19863         Objects.requireNonNull(who, "ComponentName is null");
19864         Objects.requireNonNull(apnSetting, "ApnSetting is null in updateOverrideApn");
19865         final CallerIdentity caller = getCallerIdentity(who);
19866         ApnSetting apn = getApnSetting(apnId);
19867         if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE
19868                 && apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
19869             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19870                     || isManagedProfileOwner(caller));
19871         } else {
19872             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19873         }
19874 
19875         if (apnId < 0) {
19876             return false;
19877         }
19878         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
19879         if (tm != null) {
19880             return mInjector.binderWithCleanCallingIdentity(
19881                     () -> tm.modifyDevicePolicyOverrideApn(mContext, apnId, apnSetting));
19882         } else {
19883             Slogf.w(LOG_TAG, "TelephonyManager is null when trying to modify override apn");
19884             return false;
19885         }
19886     }
19887 
19888     @Override
19889     public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) {
19890         if (!mHasFeature || !mHasTelephonyFeature) {
19891             return false;
19892         }
19893         Objects.requireNonNull(who, "ComponentName is null");
19894         final CallerIdentity caller = getCallerIdentity(who);
19895         ApnSetting apn = getApnSetting(apnId);
19896         if (apn != null && apn.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
19897             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19898                     || isManagedProfileOwner(caller));
19899         } else {
19900             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19901         }
19902         return removeOverrideApnUnchecked(apnId);
19903     }
19904 
19905     private boolean removeOverrideApnUnchecked(int apnId) {
19906         if(apnId < 0) {
19907             return false;
19908         }
19909         int numDeleted = mInjector.binderWithCleanCallingIdentity(
19910                 () -> mContext.getContentResolver().delete(
19911                         Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null));
19912         return numDeleted > 0;
19913     }
19914 
19915     private ApnSetting getApnSetting(int apnId) {
19916         if (apnId < 0) {
19917             return null;
19918         }
19919         ApnSetting apnSetting = null;
19920         Cursor cursor = mInjector.binderWithCleanCallingIdentity(
19921                 () -> mContext.getContentResolver().query(
19922                         Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null, null,
19923                         Telephony.Carriers.DEFAULT_SORT_ORDER));
19924         if (cursor != null) {
19925             while (cursor.moveToNext()) {
19926                 apnSetting = ApnSetting.makeApnSetting(cursor);
19927                 if (apnSetting != null) {
19928                     break;
19929                 }
19930             }
19931             cursor.close();
19932         }
19933         return apnSetting;
19934     }
19935 
19936     @Override
19937     public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) {
19938         if (!mHasFeature || !mHasTelephonyFeature) {
19939             return Collections.emptyList();
19940         }
19941         Objects.requireNonNull(who, "ComponentName is null");
19942         final CallerIdentity caller = getCallerIdentity(who);
19943         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller)
19944                 || isManagedProfileOwner(caller));
19945         List<ApnSetting> apnSettings = getOverrideApnsUnchecked();
19946         if (isProfileOwner(caller)) {
19947             List<ApnSetting> apnSettingList = new ArrayList<>();
19948             for (ApnSetting apnSetting : apnSettings) {
19949                 if (apnSetting.getApnTypeBitmask() == ApnSetting.TYPE_ENTERPRISE) {
19950                     apnSettingList.add(apnSetting);
19951                 }
19952             }
19953             return apnSettingList;
19954         } else {
19955             return apnSettings;
19956         }
19957     }
19958 
19959     private List<ApnSetting> getOverrideApnsUnchecked() {
19960         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
19961         if (tm != null) {
19962             return mInjector.binderWithCleanCallingIdentity(
19963                     () -> tm.getDevicePolicyOverrideApns(mContext));
19964         }
19965         Slogf.w(LOG_TAG, "TelephonyManager is null when trying to get override apns");
19966         return Collections.emptyList();
19967     }
19968 
19969     @Override
19970     public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) {
19971         if (!mHasFeature || !mHasTelephonyFeature) {
19972             return;
19973         }
19974         Objects.requireNonNull(who, "ComponentName is null");
19975         final CallerIdentity caller = getCallerIdentity(who);
19976         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19977         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_OVERRIDE_APNS_ENABLED);
19978 
19979         setOverrideApnsEnabledUnchecked(enabled);
19980     }
19981 
19982     private void setOverrideApnsEnabledUnchecked(boolean enabled) {
19983         ContentValues value = new ContentValues();
19984         value.put(ENFORCE_KEY, enabled);
19985         mInjector.binderWithCleanCallingIdentity(() -> mContext.getContentResolver().update(
19986                     ENFORCE_MANAGED_URI, value, null, null));
19987     }
19988 
19989     @Override
19990     public boolean isOverrideApnEnabled(@NonNull ComponentName who) {
19991         if (!mHasFeature || !mHasTelephonyFeature) {
19992             return false;
19993         }
19994         Objects.requireNonNull(who, "ComponentName is null");
19995         final CallerIdentity caller = getCallerIdentity(who);
19996         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
19997 
19998         Cursor enforceCursor = mInjector.binderWithCleanCallingIdentity(
19999                 () -> mContext.getContentResolver().query(
20000                         ENFORCE_MANAGED_URI, null, null, null, null));
20001 
20002         if (enforceCursor == null) {
20003             return false;
20004         }
20005         try {
20006             if (enforceCursor.moveToFirst()) {
20007                 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1;
20008             }
20009         } catch (IllegalArgumentException e) {
20010             Slogf.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain "
20011                     + "correct info.", e);
20012         } finally {
20013             enforceCursor.close();
20014         }
20015         return false;
20016     }
20017 
20018     @VisibleForTesting
20019     void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) {
20020         final File parametersFile = new File(
20021                 mPathProvider.getUserSystemDirectory(userId),
20022                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
20023         final AtomicFile atomicFile = new AtomicFile(parametersFile);
20024         FileOutputStream stream = null;
20025         try {
20026             stream = atomicFile.startWrite();
20027             final TypedXmlSerializer serializer = Xml.resolveSerializer(stream);
20028             serializer.startDocument(null, true);
20029             serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
20030             bundle.saveToXml(serializer);
20031             serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
20032             serializer.endDocument();
20033             atomicFile.finishWrite(stream);
20034         } catch (IOException | XmlPullParserException e) {
20035             Slogf.e(LOG_TAG, "Caught exception while trying to save the "
20036                     + "owner transfer parameters to file " + parametersFile, e);
20037             parametersFile.delete();
20038             atomicFile.failWrite(stream);
20039         }
20040     }
20041 
20042     void deleteTransferOwnershipBundleLocked(int userId) {
20043         final File parametersFile = new File(mPathProvider.getUserSystemDirectory(userId),
20044                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
20045         parametersFile.delete();
20046     }
20047 
20048     private void logPasswordQualitySetIfSecurityLogEnabled(ComponentName who, int userId,
20049             boolean parent, PasswordPolicy passwordPolicy) {
20050         if (SecurityLog.isLoggingEnabled()) {
20051             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
20052             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(),
20053                     userId, affectedUserId, passwordPolicy.length, passwordPolicy.quality,
20054                     passwordPolicy.letters, passwordPolicy.nonLetter, passwordPolicy.numeric,
20055                     passwordPolicy.upperCase, passwordPolicy.lowerCase, passwordPolicy.symbols);
20056         }
20057     }
20058 
20059     private static String getManagedProvisioningPackage(Context context) {
20060         return context.getResources().getString(R.string.config_managed_provisioning_package);
20061     }
20062 
20063     private void putPrivateDnsSettings(int mode, @Nullable String host) {
20064         // Set Private DNS settings using system permissions, as apps cannot write
20065         // to global settings.
20066         mInjector.binderWithCleanCallingIdentity(() -> {
20067             ConnectivitySettingsManager.setPrivateDnsMode(mContext, mode);
20068             ConnectivitySettingsManager.setPrivateDnsHostname(mContext, host);
20069         });
20070     }
20071 
20072     @Override
20073     public int setGlobalPrivateDns(@NonNull ComponentName who, int mode, String privateDnsHost) {
20074         if (!mHasFeature) {
20075             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
20076         }
20077         Objects.requireNonNull(who, "ComponentName is null");
20078         final CallerIdentity caller = getCallerIdentity(who);
20079         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20080         checkAllUsersAreAffiliatedWithDevice();
20081         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_GLOBAL_PRIVATE_DNS);
20082 
20083         switch (mode) {
20084             case PRIVATE_DNS_MODE_OPPORTUNISTIC:
20085                 if (!TextUtils.isEmpty(privateDnsHost)) {
20086                     throw new IllegalArgumentException(
20087                             "Host provided for opportunistic mode, but is not needed.");
20088                 }
20089                 putPrivateDnsSettings(ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC,
20090                         null);
20091                 return PRIVATE_DNS_SET_NO_ERROR;
20092             case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
20093                 if (TextUtils.isEmpty(privateDnsHost)
20094                         || !NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
20095                     throw new IllegalArgumentException(
20096                             String.format("Provided hostname %s is not valid", privateDnsHost));
20097                 }
20098 
20099                 // Connectivity check will have been performed in the DevicePolicyManager before
20100                 // the call here.
20101                 putPrivateDnsSettings(
20102                         ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
20103                         privateDnsHost);
20104                 return PRIVATE_DNS_SET_NO_ERROR;
20105             default:
20106                 throw new IllegalArgumentException(
20107                         String.format("Provided mode, %d, is not a valid mode.", mode));
20108         }
20109     }
20110 
20111     @Override
20112     public int getGlobalPrivateDnsMode(@NonNull ComponentName who) {
20113         if (!mHasFeature) {
20114             return PRIVATE_DNS_MODE_UNKNOWN;
20115         }
20116         Objects.requireNonNull(who, "ComponentName is null");
20117         final CallerIdentity caller = getCallerIdentity(who);
20118         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20119 
20120         final int currentMode = ConnectivitySettingsManager.getPrivateDnsMode(mContext);
20121         switch (currentMode) {
20122             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OFF:
20123                 return PRIVATE_DNS_MODE_OFF;
20124             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC:
20125                 return PRIVATE_DNS_MODE_OPPORTUNISTIC;
20126             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
20127                 return PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
20128         }
20129 
20130         return PRIVATE_DNS_MODE_UNKNOWN;
20131     }
20132 
20133     @Override
20134     public String getGlobalPrivateDnsHost(@NonNull ComponentName who) {
20135         if (!mHasFeature) {
20136             return null;
20137         }
20138         Objects.requireNonNull(who, "ComponentName is null");
20139         final CallerIdentity caller = getCallerIdentity(who);
20140         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
20141         return mInjector.settingsGlobalGetString(PRIVATE_DNS_SPECIFIER);
20142     }
20143 
20144     @Override
20145     public void installUpdateFromFile(ComponentName admin, String callerPackageName,
20146             ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback) {
20147         if (!isPermissionCheckFlagEnabled()) {
20148             Objects.requireNonNull(admin, "ComponentName is null");
20149         }
20150 
20151         CallerIdentity caller;
20152         if (isPermissionCheckFlagEnabled()) {
20153             caller = getCallerIdentity(admin, callerPackageName);
20154             enforcePermission(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, caller.getPackageName(),
20155                     UserHandle.USER_ALL);
20156         } else {
20157             caller = getCallerIdentity(admin);
20158             Preconditions.checkCallAuthorization(
20159                     isDefaultDeviceOwner(caller)
20160                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
20161         }
20162         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_SYSTEM_UPDATE);
20163 
20164         DevicePolicyEventLogger
20165                 .createEvent(DevicePolicyEnums.INSTALL_SYSTEM_UPDATE)
20166                 .setAdmin(caller.getPackageName())
20167                 .setBoolean(isDeviceAB())
20168                 .write();
20169 
20170         mInjector.binderWithCleanCallingIdentity(() -> {
20171             UpdateInstaller updateInstaller;
20172             if (isDeviceAB()) {
20173                 updateInstaller = new AbUpdateInstaller(
20174                         mContext, updateFileDescriptor, callback, mInjector, mConstants);
20175             } else {
20176                 updateInstaller = new NonAbUpdateInstaller(
20177                         mContext, updateFileDescriptor, callback, mInjector, mConstants);
20178             }
20179             updateInstaller.startInstallUpdate();
20180         });
20181     }
20182 
20183     private boolean isDeviceAB() {
20184         return "true".equalsIgnoreCase(android.os.SystemProperties
20185                 .get(AB_DEVICE_KEY, ""));
20186     }
20187 
20188     @Override
20189     public void setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames) {
20190         if (!mHasFeature) {
20191             return;
20192         }
20193         Objects.requireNonNull(who, "ComponentName is null");
20194         final CallerIdentity caller = getCallerIdentity(who);
20195         Preconditions.checkCallAuthorization(isProfileOwner(caller));
20196 
20197         synchronized (getLockObject()) {
20198             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20199             admin.mCrossProfileCalendarPackages = packageNames;
20200             saveSettingsLocked(caller.getUserId());
20201         }
20202         DevicePolicyEventLogger
20203                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALENDAR_PACKAGES)
20204                 .setAdmin(who)
20205                 .setStrings(packageNames == null ? null
20206                         : packageNames.toArray(new String[packageNames.size()]))
20207                 .write();
20208     }
20209 
20210     @Override
20211     public List<String> getCrossProfileCalendarPackages(ComponentName who) {
20212         if (!mHasFeature) {
20213             return Collections.emptyList();
20214         }
20215         Objects.requireNonNull(who, "ComponentName is null");
20216         final CallerIdentity caller = getCallerIdentity(who);
20217         Preconditions.checkCallAuthorization(isProfileOwner(caller));
20218 
20219         synchronized (getLockObject()) {
20220             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20221             return admin.mCrossProfileCalendarPackages;
20222         }
20223     }
20224 
20225     @Override
20226     public boolean isPackageAllowedToAccessCalendarForUser(String packageName,
20227             @UserIdInt int userId) {
20228         if (!mHasFeature) {
20229             return false;
20230         }
20231         Preconditions.checkStringNotEmpty(packageName, "Package name is null or empty");
20232         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
20233 
20234         final int packageUid;
20235         try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
20236             var packageState = snapshot.getPackageStates().get(packageName);
20237             if (packageState == null) {
20238                 Slogf.w(LOG_TAG, "Couldn't find package %s in user %d", packageName,
20239                         userId);
20240                 return false;
20241             } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
20242                 Slogf.w(LOG_TAG, "Couldn't find installed package %s in user %d", packageName,
20243                         userId);
20244                 return false;
20245             } else {
20246                 packageUid = UserHandle.getUid(userId, packageState.getAppId());
20247             }
20248         }
20249         final CallerIdentity caller = getCallerIdentity();
20250         if (caller.getUid() != packageUid) {
20251             Preconditions.checkCallAuthorization(
20252                     hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)
20253                             || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL));
20254         }
20255 
20256         synchronized (getLockObject()) {
20257             if (mInjector.settingsSecureGetIntForUser(
20258                     Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userId) == 0) {
20259                 return false;
20260             }
20261             final ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
20262             if (admin != null) {
20263                 if (admin.mCrossProfileCalendarPackages == null) {
20264                     return true;
20265                 }
20266                 return admin.mCrossProfileCalendarPackages.contains(packageName);
20267             }
20268         }
20269         return false;
20270     }
20271 
20272     @Override
20273     public List<String> getCrossProfileCalendarPackagesForUser(int userHandle) {
20274         if (!mHasFeature) {
20275             return Collections.emptyList();
20276         }
20277         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
20278         Preconditions.checkCallAuthorization(
20279                 hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)
20280                         || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL));
20281 
20282         synchronized (getLockObject()) {
20283             final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
20284             if (admin != null) {
20285                 return admin.mCrossProfileCalendarPackages;
20286             }
20287         }
20288         return Collections.emptyList();
20289     }
20290 
20291     @Override
20292     public void setCrossProfilePackages(ComponentName who, List<String> packageNames) {
20293         if (!mHasFeature) {
20294             return;
20295         }
20296 
20297         Objects.requireNonNull(who, "ComponentName is null");
20298         Objects.requireNonNull(packageNames, "Package names is null");
20299         final CallerIdentity caller = getCallerIdentity(who);
20300         Preconditions.checkCallAuthorization(isProfileOwner(caller));
20301 
20302         final List<String> previousCrossProfilePackages;
20303         synchronized (getLockObject()) {
20304             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20305             previousCrossProfilePackages = admin.mCrossProfilePackages;
20306             if (packageNames.equals(previousCrossProfilePackages)) {
20307                 return;
20308             }
20309             admin.mCrossProfilePackages = packageNames;
20310             saveSettingsLocked(caller.getUserId());
20311         }
20312         logSetCrossProfilePackages(who, packageNames);
20313         final CrossProfileApps crossProfileApps =
20314                 mContext.createContextAsUser(
20315                         caller.getUserHandle(), /* flags= */ 0)
20316                         .getSystemService(CrossProfileApps.class);
20317         mInjector.binderWithCleanCallingIdentity(
20318         () -> crossProfileApps.resetInteractAcrossProfilesAppOps(
20319                         previousCrossProfilePackages, new HashSet<>(packageNames)));
20320     }
20321 
20322     private void logSetCrossProfilePackages(ComponentName who, List<String> packageNames) {
20323         DevicePolicyEventLogger
20324                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_PACKAGES)
20325                 .setAdmin(who)
20326                 .setStrings(packageNames.toArray(new String[packageNames.size()]))
20327                 .write();
20328     }
20329 
20330     @Override
20331     public List<String> getCrossProfilePackages(ComponentName who) {
20332         if (!mHasFeature) {
20333             return Collections.emptyList();
20334         }
20335         Objects.requireNonNull(who, "ComponentName is null");
20336         final CallerIdentity caller = getCallerIdentity(who);
20337         Preconditions.checkCallAuthorization(isProfileOwner(caller));
20338 
20339         synchronized (getLockObject()) {
20340             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20341             return admin.mCrossProfilePackages;
20342         }
20343     }
20344 
20345     @Override
20346     public List<String> getAllCrossProfilePackages(int userId) {
20347         if (!mHasFeature) {
20348             return Collections.emptyList();
20349         }
20350         final CallerIdentity caller = getCallerIdentity();
20351         Preconditions.checkCallAuthorization(
20352                 isSystemUid(caller) || isRootUid(caller) || hasCallingPermission(
20353                         permission.INTERACT_ACROSS_USERS) || hasCallingPermission(
20354                         permission.INTERACT_ACROSS_USERS_FULL) || hasPermissionForPreflight(
20355                                                 caller, permission.INTERACT_ACROSS_PROFILES));
20356 
20357         synchronized (getLockObject()) {
20358             final List<ActiveAdmin> admins = getProfileOwnerAdminsForProfileGroup(userId);
20359             final List<String> packages = getCrossProfilePackagesForAdmins(admins);
20360 
20361             packages.addAll(getDefaultCrossProfilePackages());
20362 
20363             return packages;
20364         }
20365     }
20366 
20367     private List<String> getCrossProfilePackagesForAdmins(List<ActiveAdmin> admins) {
20368         final List<String> packages = new ArrayList<>();
20369         for (int i = 0; i < admins.size(); i++) {
20370             packages.addAll(admins.get(i).mCrossProfilePackages);
20371         }
20372         return packages;
20373     }
20374 
20375     @Override
20376     public List<String> getDefaultCrossProfilePackages() {
20377         Set<String> crossProfilePackages = new HashSet<>();
20378 
20379         Collections.addAll(crossProfilePackages, mContext.getResources()
20380                 .getStringArray(R.array.cross_profile_apps));
20381         Collections.addAll(crossProfilePackages, mContext.getResources()
20382                 .getStringArray(R.array.vendor_cross_profile_apps));
20383 
20384         return new ArrayList<>(crossProfilePackages);
20385     }
20386 
20387     private List<ActiveAdmin> getProfileOwnerAdminsForProfileGroup(int userId) {
20388         synchronized (getLockObject()) {
20389             final List<ActiveAdmin> admins = new ArrayList<>();
20390             int[] users = mUserManager.getProfileIdsWithDisabled(userId);
20391             for (int i = 0; i < users.length; i++) {
20392                 final ComponentName componentName = getProfileOwnerAsUser(users[i]);
20393                 if (componentName != null) {
20394                     ActiveAdmin admin = getActiveAdminUncheckedLocked(componentName, users[i]);
20395                     if (admin != null) {
20396                         admins.add(admin);
20397                     }
20398                 }
20399             }
20400             return admins;
20401         }
20402     }
20403 
20404     @Override
20405     public boolean isManagedKiosk() {
20406         if (!mHasFeature) {
20407             return false;
20408         }
20409         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
20410                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
20411 
20412         long id = mInjector.binderClearCallingIdentity();
20413         try {
20414             return isManagedKioskInternal();
20415         } catch (RemoteException e) {
20416             throw new IllegalStateException(e);
20417         } finally {
20418             mInjector.binderRestoreCallingIdentity(id);
20419         }
20420     }
20421 
20422     private boolean isUnattendedManagedKioskUnchecked() {
20423         try {
20424             return isManagedKioskInternal()
20425                     && getPowerManagerInternal().wasDeviceIdleFor(UNATTENDED_MANAGED_KIOSK_MS);
20426         } catch (RemoteException e) {
20427             throw new IllegalStateException(e);
20428         }
20429     }
20430 
20431     @Override
20432     public boolean isUnattendedManagedKiosk() {
20433         if (!mHasFeature) {
20434             return false;
20435         }
20436         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
20437                 || hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
20438 
20439         return mInjector.binderWithCleanCallingIdentity(() -> isUnattendedManagedKioskUnchecked());
20440     }
20441 
20442     /**
20443      * Returns whether the device is currently being used as a publicly-accessible dedicated device.
20444      * Assumes that feature checks and permission checks have already been performed, and that the
20445      * calling identity has been cleared.
20446      */
20447     private boolean isManagedKioskInternal() throws RemoteException {
20448         return mOwners.hasDeviceOwner()
20449                 && mInjector.getIActivityManager().getLockTaskModeState()
20450                         == ActivityManager.LOCK_TASK_MODE_LOCKED
20451                 && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO)
20452                 && !deviceHasKeyguard()
20453                 && !inEphemeralUserSession();
20454     }
20455 
20456     private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException {
20457         LockTaskPolicy policy = mDevicePolicyEngine.getResolvedPolicy(
20458                 PolicyDefinition.LOCK_TASK, getCurrentForegroundUserId());
20459         int lockTaskFeatures = policy == null
20460                 // We default on the power button menu, in order to be consistent with pre-P
20461                 // behaviour.
20462                 ? DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS
20463                 : policy.getFlags();
20464         return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature;
20465     }
20466 
20467     private boolean deviceHasKeyguard() {
20468         for (UserInfo userInfo : mUserManager.getUsers()) {
20469             if (mLockPatternUtils.isSecure(userInfo.id)) {
20470                 return true;
20471             }
20472         }
20473         return false;
20474     }
20475 
20476     private boolean inEphemeralUserSession() {
20477         for (UserInfo userInfo : mUserManager.getUsers()) {
20478             if (mInjector.getUserManager().isUserEphemeral(userInfo.id)) {
20479                 return true;
20480             }
20481         }
20482         return false;
20483     }
20484 
20485     private PowerManagerInternal getPowerManagerInternal() {
20486         return mInjector.getPowerManagerInternal();
20487     }
20488 
20489     @Override
20490     public boolean startViewCalendarEventInManagedProfile(String packageName, long eventId,
20491             long start, long end, boolean allDay, int flags) {
20492         if (!mHasFeature) {
20493             return false;
20494         }
20495         Preconditions.checkStringNotEmpty(packageName, "Package name is empty");
20496 
20497         final CallerIdentity caller = getCallerIdentity();
20498         if (!isCallingFromPackage(packageName, caller.getUid())) {
20499             throw new SecurityException("Input package name doesn't align with actual "
20500                     + "calling package.");
20501         }
20502         return mInjector.binderWithCleanCallingIdentity(() -> {
20503             final int workProfileUserId = getManagedUserId(caller.getUserId());
20504             if (workProfileUserId < 0) {
20505                 return false;
20506             }
20507             if (!isPackageAllowedToAccessCalendarForUser(packageName, workProfileUserId)) {
20508                 Slogf.d(LOG_TAG, "Package %s is not allowed to access cross-profile calendar APIs",
20509                         packageName);
20510                 return false;
20511             }
20512             final Intent intent = new Intent(
20513                     CalendarContract.ACTION_VIEW_MANAGED_PROFILE_CALENDAR_EVENT);
20514             intent.setPackage(packageName);
20515             intent.putExtra(CalendarContract.EXTRA_EVENT_ID, eventId);
20516             intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start);
20517             intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
20518             intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay);
20519             intent.setFlags(flags);
20520             try {
20521                 mContext.startActivityAsUser(intent, UserHandle.of(workProfileUserId));
20522             } catch (ActivityNotFoundException e) {
20523                 Slogf.e(LOG_TAG, "View event activity not found", e);
20524                 return false;
20525             }
20526             return true;
20527         });
20528     }
20529 
20530     @Override
20531     public void setApplicationExemptions(String callerPackage, String packageName,
20532             int[] exemptions) {
20533         if (!mHasFeature) {
20534             return;
20535         }
20536         Preconditions.checkStringNotEmpty(packageName, "Package name cannot be empty.");
20537         Objects.requireNonNull(exemptions, "Application exemptions must not be null.");
20538         Preconditions.checkArgument(areApplicationExemptionsValid(exemptions),
20539                 "Invalid application exemption constant found in application exemptions set.");
20540         Preconditions.checkCallAuthorization(
20541                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS));
20542 
20543         final CallerIdentity caller = getCallerIdentity(callerPackage);
20544         final AppOpsManager appOpsMgr = mInjector.getAppOpsManager();
20545         final ApplicationInfo appInfo = getPackageInfoWithNullCheck(packageName, caller);
20546         final int uid = appInfo.uid;
20547 
20548         mInjector.binderWithCleanCallingIdentity(() -> {
20549             APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.forEach((exemption, appOp) -> {
20550                 int currentMode = appOpsMgr.unsafeCheckOpNoThrow(appOp, uid, packageName);
20551                 int newMode = ArrayUtils.contains(exemptions, exemption)
20552                         ? MODE_ALLOWED : MODE_DEFAULT;
20553                 if (currentMode != newMode) {
20554                     appOpsMgr.setMode(appOp, uid, packageName, newMode);
20555 
20556                     // If the user has already disabled background usage for the package, it won't
20557                     // have OP_RUN_ANY_IN_BACKGROUND app op and won't execute in the background. The
20558                     // code below grants that app op, and once the exemption is in place, the user
20559                     // won't be able to disable background usage anymore.
20560                     if (Flags.powerExemptionBgUsageFix()
20561                             && exemption == EXEMPT_FROM_POWER_RESTRICTIONS
20562                             && newMode == MODE_ALLOWED) {
20563                         setBgUsageAppOp(appOpsMgr, appInfo);
20564                     }
20565                 }
20566             });
20567         });
20568 
20569         String[] appOpExemptions = new String[exemptions.length];
20570         for (int i = 0; i < exemptions.length; i++) {
20571             appOpExemptions[i] = APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.get(exemptions[i]);
20572         }
20573         DevicePolicyEventLogger
20574                 .createEvent(DevicePolicyEnums.SET_APPLICATION_EXEMPTIONS)
20575                 .setAdmin(caller.getPackageName())
20576                 .setStrings(packageName, appOpExemptions)
20577                 .write();
20578     }
20579 
20580     static void setBgUsageAppOp(AppOpsManager appOpsMgr, ApplicationInfo appInfo) {
20581         appOpsMgr.setMode(OP_RUN_ANY_IN_BACKGROUND, appInfo.uid, appInfo.packageName, MODE_ALLOWED);
20582         if (appInfo.targetSdkVersion < Build.VERSION_CODES.O) {
20583             appOpsMgr.setMode(OP_RUN_IN_BACKGROUND, appInfo.uid, appInfo.packageName, MODE_ALLOWED);
20584         }
20585     }
20586 
20587     @Override
20588     public int[] getApplicationExemptions(String packageName) {
20589         if (!mHasFeature) {
20590             return new int[0];
20591         }
20592         Preconditions.checkStringNotEmpty(packageName, "Package name cannot be empty.");
20593         Preconditions.checkCallAuthorization(
20594                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_POLICY_APP_EXEMPTIONS));
20595 
20596         final CallerIdentity caller = getCallerIdentity();
20597         final ApplicationInfo packageInfo;
20598         packageInfo = getPackageInfoWithNullCheck(packageName, caller);
20599 
20600         IntArray appliedExemptions = new IntArray(0);
20601         for (Map.Entry<Integer, String> entry :
20602                 APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.entrySet()) {
20603             if (mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
20604                     entry.getValue(), packageInfo.uid, packageInfo.packageName) == MODE_ALLOWED) {
20605                 appliedExemptions.add(entry.getKey());
20606             }
20607         }
20608         return appliedExemptions.toArray();
20609     }
20610 
20611     private ApplicationInfo getPackageInfoWithNullCheck(String packageName, CallerIdentity caller) {
20612         final ApplicationInfo packageInfo =
20613                 mInjector.getPackageManagerInternal().getApplicationInfo(
20614                         packageName,
20615                         /* flags= */ 0,
20616                         caller.getUid(),
20617                         caller.getUserId());
20618         if (packageInfo == null) {
20619             throw new ServiceSpecificException(
20620                     DevicePolicyManager.ERROR_PACKAGE_NAME_NOT_FOUND,
20621                     "Package name not found.");
20622         }
20623         return packageInfo;
20624     }
20625 
20626     private boolean areApplicationExemptionsValid(int[] exemptions) {
20627         for (int exemption : exemptions) {
20628             if (!APPLICATION_EXEMPTION_CONSTANTS_TO_APP_OPS.containsKey(exemption)) {
20629                 return false;
20630             }
20631         }
20632         return true;
20633     }
20634 
20635     private boolean isCallingFromPackage(String packageName, int callingUid) {
20636         try (var snapshot = mInjector.getPackageManagerLocal().withUnfilteredSnapshot()) {
20637             var packageState = snapshot.getPackageStates().get(packageName);
20638             var userId = UserHandle.getUserId(callingUid);
20639             if (packageState == null) {
20640                 Slogf.d(LOG_TAG, "Calling UID " + callingUid + " not found");
20641                 return false;
20642             } else if (!packageState.getUserStateOrDefault(userId).isInstalled()) {
20643                 Slogf.d(LOG_TAG, "Calling UID " + callingUid + " not installed");
20644                 return false;
20645             } else {
20646                 return callingUid == UserHandle.getUid(userId, packageState.getAppId());
20647             }
20648         }
20649     }
20650 
20651     private DevicePolicyConstants loadConstants() {
20652         return DevicePolicyConstants.loadFromString(
20653                 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
20654     }
20655 
20656     @Override
20657     public void setUserControlDisabledPackages(ComponentName who, String callerPackageName,
20658             List<String> packages) {
20659         Objects.requireNonNull(packages, "packages is null");
20660         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
20661         checkCanExecuteOrThrowUnsafe(
20662                 DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES);
20663 
20664         EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
20665                 who,
20666                 MANAGE_DEVICE_POLICY_APPS_CONTROL,
20667                 caller.getPackageName(),
20668                 caller.getUserId());
20669         Binder.withCleanCallingIdentity(() -> {
20670             if (packages.isEmpty()) {
20671                 removeUserControlDisabledPackages(caller, enforcingAdmin);
20672             } else {
20673                 addUserControlDisabledPackages(caller, enforcingAdmin, new HashSet<>(packages));
20674             }
20675         });
20676 
20677         DevicePolicyEventLogger
20678                 .createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES)
20679                 .setAdmin(caller.getPackageName())
20680                 .setStrings(packages.toArray(new String[packages.size()]))
20681                 .write();
20682     }
20683 
20684     private void addUserControlDisabledPackages(CallerIdentity caller,
20685             EnforcingAdmin enforcingAdmin, Set<String> packages) {
20686         if (isDeviceOwner(caller)) {
20687             mDevicePolicyEngine.setGlobalPolicy(
20688                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20689                     enforcingAdmin,
20690                     new PackageSetPolicyValue(packages));
20691         } else {
20692             mDevicePolicyEngine.setLocalPolicy(
20693                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20694                     enforcingAdmin,
20695                     new PackageSetPolicyValue(packages),
20696                     caller.getUserId());
20697         }
20698     }
20699 
20700     private void removeUserControlDisabledPackages(CallerIdentity caller,
20701             EnforcingAdmin enforcingAdmin) {
20702         if (isDeviceOwner(caller)) {
20703             mDevicePolicyEngine.removeGlobalPolicy(
20704                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20705                     enforcingAdmin);
20706         } else {
20707             mDevicePolicyEngine.removeLocalPolicy(
20708                     PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20709                     enforcingAdmin,
20710                     caller.getUserId());
20711         }
20712     }
20713 
20714     @Override
20715     public List<String> getUserControlDisabledPackages(ComponentName who,
20716             String callerPackageName) {
20717         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
20718         enforceCanQuery(
20719                 MANAGE_DEVICE_POLICY_APPS_CONTROL,
20720                 caller.getPackageName(),
20721                 caller.getUserId());
20722         // This retrieves the policy for the calling user only, DOs for example can't know
20723         // what's enforced globally or on another user.
20724         Set<String> packages = mDevicePolicyEngine.getResolvedPolicy(
20725                 PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
20726                 caller.getUserId());
20727         return packages == null ? Collections.emptyList() : packages.stream().toList();
20728     }
20729 
20730     @Override
20731     public void setCommonCriteriaModeEnabled(ComponentName who, String callerPackageName,
20732             boolean enabled) {
20733         CallerIdentity caller;
20734         if (isPermissionCheckFlagEnabled()) {
20735             caller = getCallerIdentity(who, callerPackageName);
20736         } else {
20737             caller = getCallerIdentity(who);
20738         }
20739         final ActiveAdmin admin;
20740 
20741         if (isPermissionCheckFlagEnabled()) {
20742             EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
20743                     who,
20744                     MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
20745                     caller.getPackageName(),
20746                     caller.getUserId());
20747             admin = enforcingAdmin.getActiveAdmin();
20748         } else {
20749             Objects.requireNonNull(who, "ComponentName is null");
20750             Preconditions.checkCallAuthorization(
20751                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
20752                     "Common Criteria mode can only be controlled by a device owner or "
20753                             + "a profile owner on an organization-owned device.");
20754             synchronized (getLockObject()) {
20755                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
20756             }
20757         }
20758         synchronized (getLockObject()) {
20759             admin.mCommonCriteriaMode = enabled;
20760             saveSettingsLocked(caller.getUserId());
20761         }
20762         DevicePolicyEventLogger
20763                 .createEvent(DevicePolicyEnums.SET_COMMON_CRITERIA_MODE)
20764                 .setAdmin(caller.getPackageName())
20765                 .setBoolean(enabled)
20766                 .write();
20767     }
20768 
20769     @Override
20770     public boolean isCommonCriteriaModeEnabled(ComponentName who) {
20771         if (who != null) {
20772             final CallerIdentity caller = getCallerIdentity(who);
20773             Preconditions.checkCallAuthorization(
20774                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
20775                     "Common Criteria mode can only be controlled by a device owner or "
20776                             + "a profile owner on an organization-owned device.");
20777 
20778             synchronized (getLockObject()) {
20779                 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
20780                 return admin.mCommonCriteriaMode;
20781             }
20782         }
20783 
20784         // Return aggregated state if caller is not admin (who == null).
20785         synchronized (getLockObject()) {
20786             // Only DO or COPE PO can turn on CC mode, so take a shortcut here and only look at
20787             // their ActiveAdmin, instead of iterating through all admins.
20788             ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
20789 
20790             return admin != null ? admin.mCommonCriteriaMode : false;
20791         }
20792     }
20793 
20794     @Override
20795     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(ComponentName who) {
20796         Objects.requireNonNull(who, "ComponentName is null");
20797 
20798         final CallerIdentity caller = getCallerIdentity(who);
20799         // DO shouldn't be able to use this method.
20800         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
20801 
20802         synchronized (getLockObject()) {
20803             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
20804             final long deadline = admin.mProfileOffDeadline;
20805             final int result = makeSuspensionReasons(admin.mSuspendPersonalApps,
20806                     deadline != 0 && mInjector.systemCurrentTimeMillis() > deadline);
20807             Slogf.d(LOG_TAG, "getPersonalAppsSuspendedReasons user: %d; result: %d",
20808                     mInjector.userHandleGetCallingUserId(), result);
20809             return result;
20810         }
20811     }
20812 
20813     private @PersonalAppsSuspensionReason int makeSuspensionReasons(
20814             boolean explicit, boolean timeout) {
20815         int result = PERSONAL_APPS_NOT_SUSPENDED;
20816         if (explicit) {
20817             result |= PERSONAL_APPS_SUSPENDED_EXPLICITLY;
20818         }
20819         if (timeout) {
20820             result |= PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT;
20821         }
20822         return result;
20823     }
20824 
20825     @Override
20826     public void setPersonalAppsSuspended(ComponentName who, boolean suspended) {
20827         Objects.requireNonNull(who, "ComponentName is null");
20828 
20829         final CallerIdentity caller = getCallerIdentity(who);
20830         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
20831         Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller));
20832 
20833         final int callingUserId = caller.getUserId();
20834         synchronized (getLockObject()) {
20835             final ActiveAdmin admin = getProfileOwnerLocked(callingUserId);
20836             boolean shouldSaveSettings = false;
20837             if (admin.mSuspendPersonalApps != suspended) {
20838                 admin.mSuspendPersonalApps = suspended;
20839                 shouldSaveSettings = true;
20840             }
20841             if (admin.mProfileOffDeadline != 0) {
20842                 admin.mProfileOffDeadline = 0;
20843                 shouldSaveSettings = true;
20844             }
20845             if (shouldSaveSettings) {
20846                 saveSettingsLocked(callingUserId);
20847             }
20848         }
20849 
20850         mInjector.binderWithCleanCallingIdentity(() -> updatePersonalAppsSuspension(
20851                 callingUserId));
20852 
20853         DevicePolicyEventLogger
20854                 .createEvent(DevicePolicyEnums.SET_PERSONAL_APPS_SUSPENDED)
20855                 .setAdmin(caller.getComponentName())
20856                 .setBoolean(suspended)
20857                 .write();
20858     }
20859 
20860     /** Starts an activity to check policy compliance or request compliance acknowledgement. */
20861     private void triggerPolicyComplianceCheckIfNeeded(int profileUserId, boolean suspended) {
20862         synchronized (getLockObject()) {
20863             final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
20864             if (profileOwner == null) {
20865                 Slogf.wtf(LOG_TAG, "Profile owner not found for compliance check");
20866                 return;
20867             }
20868             if (suspended) {
20869                 // If suspended, DPC will need to show an activity.
20870                 final Intent intent = new Intent(ACTION_CHECK_POLICY_COMPLIANCE);
20871                 intent.setPackage(profileOwner.info.getPackageName());
20872                 mContext.startActivityAsUser(intent, UserHandle.of(profileUserId));
20873             } else if (profileOwner.mProfileOffDeadline > 0) {
20874                 // If not suspended, but deadline set, DPC needs to acknowledge compliance so that
20875                 // the deadline can be reset.
20876                 sendAdminCommandLocked(profileOwner, ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED,
20877                         /* adminExtras= */ null, /* receiver= */ null, /* inForeground = */ true);
20878             }
20879         }
20880     }
20881 
20882     /**
20883      * Checks whether personal apps should be suspended according to the policy and applies the
20884      * change if needed.
20885      */
20886     private boolean updatePersonalAppsSuspension(int profileUserId) {
20887         final boolean shouldSuspend;
20888         synchronized (getLockObject()) {
20889             final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
20890             if (profileOwner != null) {
20891                 // Profile is considered "off" when it is either not running or is running locked
20892                 // or is in quiet mode, i.e. when the admin cannot sync policies or show UI.
20893                 boolean profileUserOff =
20894                         !mUserManagerInternal.isUserUnlockingOrUnlocked(profileUserId)
20895                         || mUserManager.isQuietModeEnabled(UserHandle.of(profileUserId));
20896                 final int notificationState = updateProfileOffDeadlineLocked(
20897                         profileUserId, profileOwner, profileUserOff);
20898                 final boolean suspendedExplicitly = profileOwner.mSuspendPersonalApps;
20899                 final boolean suspendedByTimeout = profileOwner.mProfileOffDeadline == -1;
20900                 Slogf.d(LOG_TAG,
20901                         "Personal apps suspended explicitly: %b, by timeout: %b, notification: %d",
20902                         suspendedExplicitly, suspendedByTimeout, notificationState);
20903                 updateProfileOffDeadlineNotificationLocked(
20904                         profileUserId, profileOwner, notificationState);
20905                 shouldSuspend = suspendedExplicitly || suspendedByTimeout;
20906             } else {
20907                 shouldSuspend = false;
20908             }
20909         }
20910 
20911         final int parentUserId = getProfileParentId(profileUserId);
20912         suspendPersonalAppsInternal(parentUserId, profileUserId, shouldSuspend);
20913         return shouldSuspend;
20914     }
20915 
20916     /**
20917      * Checks work profile time off policy, scheduling personal apps suspension via alarm if
20918      * necessary.
20919      * @return notification state
20920      */
20921     private int updateProfileOffDeadlineLocked(
20922             int profileUserId, ActiveAdmin profileOwner, boolean off) {
20923         final long now = mInjector.systemCurrentTimeMillis();
20924         if (profileOwner.mProfileOffDeadline != 0 && now > profileOwner.mProfileOffDeadline) {
20925             Slogf.i(LOG_TAG, "Profile off deadline has been reached, off: " + off);
20926             if (profileOwner.mProfileOffDeadline != -1) {
20927                 // Move the deadline far to the past so that it cannot be rolled back by TZ change.
20928                 profileOwner.mProfileOffDeadline = -1;
20929                 saveSettingsLocked(profileUserId);
20930             }
20931             return off ? PROFILE_OFF_NOTIFICATION_SUSPENDED : PROFILE_OFF_NOTIFICATION_NONE;
20932         }
20933         boolean shouldSaveSettings = false;
20934         if (profileOwner.mSuspendPersonalApps) {
20935             // When explicit suspension is active, deadline shouldn't be set.
20936             if (profileOwner.mProfileOffDeadline != 0) {
20937                 profileOwner.mProfileOffDeadline = 0;
20938                 shouldSaveSettings = true;
20939             }
20940         } else if (profileOwner.mProfileOffDeadline != 0
20941                 && (profileOwner.mProfileMaximumTimeOffMillis == 0)) {
20942             // There is a deadline but either there is no policy -> clear
20943             // the deadline.
20944             Slogf.i(LOG_TAG, "Profile off deadline is reset to zero");
20945             profileOwner.mProfileOffDeadline = 0;
20946             shouldSaveSettings = true;
20947         } else if (profileOwner.mProfileOffDeadline == 0
20948                 && (profileOwner.mProfileMaximumTimeOffMillis != 0 && off)) {
20949             // There profile is locked and there is a policy, but the deadline is not set -> set the
20950             // deadline.
20951             Slogf.i(LOG_TAG, "Profile off deadline is set.");
20952             profileOwner.mProfileOffDeadline = now + profileOwner.mProfileMaximumTimeOffMillis;
20953             shouldSaveSettings = true;
20954         }
20955 
20956         if (shouldSaveSettings) {
20957             saveSettingsLocked(profileUserId);
20958         }
20959 
20960         final long alarmTime;
20961         final int notificationState;
20962         if (!off || profileOwner.mProfileOffDeadline == 0) {
20963             alarmTime = 0;
20964             notificationState = PROFILE_OFF_NOTIFICATION_NONE;
20965         } else if (profileOwner.mProfileOffDeadline - now < MANAGED_PROFILE_OFF_WARNING_PERIOD) {
20966             // The deadline is close, upon the alarm personal apps should be suspended.
20967             alarmTime = profileOwner.mProfileOffDeadline;
20968             notificationState = PROFILE_OFF_NOTIFICATION_WARNING;
20969         } else {
20970             // The deadline is quite far, upon the alarm we should warn the user first, so the
20971             // alarm is scheduled earlier than the actual deadline.
20972             alarmTime = profileOwner.mProfileOffDeadline - MANAGED_PROFILE_OFF_WARNING_PERIOD;
20973             notificationState = PROFILE_OFF_NOTIFICATION_NONE;
20974         }
20975 
20976         final AlarmManager am = mInjector.getAlarmManager();
20977         final Intent intent = new Intent(ACTION_PROFILE_OFF_DEADLINE);
20978         intent.setPackage(mContext.getPackageName());
20979         // Broadcast alarms sent by system are immutable
20980         final PendingIntent pi = mInjector.pendingIntentGetBroadcast(
20981                 mContext, REQUEST_PROFILE_OFF_DEADLINE, intent,
20982                 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
20983                         | PendingIntent.FLAG_IMMUTABLE);
20984 
20985         if (alarmTime == 0) {
20986             Slogf.i(LOG_TAG, "Profile off deadline alarm is removed.");
20987             am.cancel(pi);
20988         } else {
20989             Slogf.i(LOG_TAG, "Profile off deadline alarm is set.");
20990             am.set(AlarmManager.RTC, alarmTime, pi);
20991         }
20992 
20993         return notificationState;
20994     }
20995 
20996     private void suspendPersonalAppsInternal(
20997             int parentUserId, int profileUserId, boolean suspended) {
20998         if (getUserData(parentUserId).mAppsSuspended == suspended) {
20999             return;
21000         }
21001         Slogf.i(LOG_TAG, "%s personal apps for user %d", suspended ? "Suspending" : "Unsuspending",
21002                 parentUserId);
21003 
21004         // TODO(b/280602237): migrate properly
21005         ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
21006         if (profileOwner != null) {
21007             EnforcingAdmin admin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
21008                     profileOwner.info.getComponent(),
21009                     profileUserId,
21010                     profileOwner);
21011             mDevicePolicyEngine.setLocalPolicy(
21012                     PolicyDefinition.PERSONAL_APPS_SUSPENDED,
21013                     admin,
21014                     new BooleanPolicyValue(suspended),
21015                     parentUserId);
21016         }
21017 
21018         synchronized (getLockObject()) {
21019             getUserData(parentUserId).mAppsSuspended = suspended;
21020             saveSettingsLocked(parentUserId);
21021         }
21022     }
21023 
21024     private void notifyIfManagedSubscriptionsAreUnavailable(
21025             UserHandle managedProfile, boolean managedProfileAvailable) {
21026         if (!isManagedProfile(managedProfile.getIdentifier())) {
21027             Slog.wtf(
21028                     LOG_TAG,
21029                     "Expected managed profile when notified of profile availability change.");
21030         }
21031         if (getManagedSubscriptionsPolicy().getPolicyType()
21032                 != ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
21033             // There may be a subscription in the personal profile, in which case calls and
21034             // texts may still be available. No need to notify the user.
21035             return;
21036         }
21037         if (managedProfileAvailable) {
21038             // When quiet mode is switched off calls and texts then become available to the user,
21039             // so no need to keep showing the notification.
21040             mInjector
21041                     .getNotificationManager()
21042                     .cancel(SystemMessage.NOTE_ALL_MANAGED_SUBSCRIPTIONS_AND_MANAGED_PROFILE_OFF);
21043             return;
21044         }
21045         final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION);
21046         intent.putExtra(Intent.EXTRA_USER_HANDLE, managedProfile.getIdentifier());
21047         final PendingIntent pendingIntent =
21048                 mInjector.pendingIntentGetBroadcast(
21049                         mContext,
21050                         /* requestCode= */ 0,
21051                         intent,
21052                         PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
21053         final Notification.Action turnProfileOnButton =
21054                 new Notification.Action.Builder(
21055                         /* icon= */ null, getUnpauseWorkAppsButtonText(), pendingIntent)
21056                         .build();
21057 
21058         final Bundle extras = new Bundle();
21059         extras.putString(
21060                 Notification.EXTRA_SUBSTITUTE_APP_NAME, getWorkProfileContentDescription());
21061         final Notification notification =
21062                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
21063                         .setSmallIcon(R.drawable.ic_phone_disabled)
21064                         .setContentTitle(getUnpauseWorkAppsForTelephonyTitle())
21065                         .setContentText(getUnpauseWorkAppsForTelephonyText())
21066                         .setStyle(new Notification.BigTextStyle().bigText(
21067                                 getUnpauseWorkAppsForTelephonyText()))
21068                         .addAction(turnProfileOnButton)
21069                         .addExtras(extras)
21070                         .setOngoing(false)
21071                         .setShowWhen(true)
21072                         .setAutoCancel(true)
21073                         .build();
21074 
21075         mInjector
21076                 .getNotificationManager()
21077                 .notifyAsUser(
21078                         /* tag= */ null,
21079                         SystemMessage.NOTE_ALL_MANAGED_SUBSCRIPTIONS_AND_MANAGED_PROFILE_OFF,
21080                         notification,
21081                         UserHandle.of(getProfileParentId(managedProfile.getIdentifier())));
21082     }
21083 
21084     private String getUnpauseWorkAppsButtonText() {
21085         return getUpdatableString(
21086                 WORK_PROFILE_TELEPHONY_PAUSED_TURN_ON_BUTTON,
21087                 R.string.work_profile_telephony_paused_turn_on_button);
21088     }
21089 
21090     private String getUnpauseWorkAppsForTelephonyTitle() {
21091         return getUpdatableString(
21092                 WORK_PROFILE_TELEPHONY_PAUSED_TITLE, R.string.work_profile_telephony_paused_title);
21093     }
21094 
21095     private String getUnpauseWorkAppsForTelephonyText() {
21096         return getUpdatableString(
21097                 WORK_PROFILE_TELEPHONY_PAUSED_BODY,
21098                 R.string.work_profile_telephony_paused_text);
21099     }
21100 
21101     @GuardedBy("getLockObject()")
21102     private void updateProfileOffDeadlineNotificationLocked(
21103             int profileUserId, ActiveAdmin profileOwner, int notificationState) {
21104         if (notificationState == PROFILE_OFF_NOTIFICATION_NONE) {
21105             mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED);
21106             return;
21107         }
21108 
21109         final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION);
21110         intent.setPackage(mContext.getPackageName());
21111         intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
21112 
21113         // Simple notification action button clicks are immutable
21114         final PendingIntent pendingIntent = mInjector.pendingIntentGetBroadcast(mContext,
21115                 0 /* requestCode */, intent,
21116                 PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
21117 
21118         final Notification.Action turnProfileOnButton = new Notification.Action.Builder(
21119                 /* icon= */ null, getPersonalAppSuspensionButtonText(), pendingIntent).build();
21120 
21121         final String text;
21122         final boolean ongoing;
21123         if (notificationState == PROFILE_OFF_NOTIFICATION_WARNING) {
21124             // Round to the closest integer number of days.
21125             final int maxDays = (int)
21126                     ((profileOwner.mProfileMaximumTimeOffMillis + MS_PER_DAY / 2) / MS_PER_DAY);
21127             final String date = DateUtils.formatDateTime(
21128                     mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_DATE);
21129             final String time = DateUtils.formatDateTime(
21130                     mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_TIME);
21131             text = getPersonalAppSuspensionSoonText(date, time, maxDays);
21132             ongoing = false;
21133         } else {
21134             text = getPersonalAppSuspensionText();
21135             ongoing = true;
21136         }
21137         final int color = mContext.getColor(R.color.personal_apps_suspension_notification_color);
21138         final Bundle extras = new Bundle();
21139         // TODO: Create a separate string for this.
21140         extras.putString(
21141                 Notification.EXTRA_SUBSTITUTE_APP_NAME, getWorkProfileContentDescription());
21142 
21143         final Notification notification =
21144                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
21145                         .setSmallIcon(R.drawable.ic_corp_badge_no_background)
21146                         .setOngoing(ongoing)
21147                         .setAutoCancel(false)
21148                         .setContentTitle(getPersonalAppSuspensionTitle())
21149                         .setContentText(text)
21150                         .setStyle(new Notification.BigTextStyle().bigText(text))
21151                         .setColor(color)
21152                         .addAction(turnProfileOnButton)
21153                         .addExtras(extras)
21154                         .build();
21155 
21156         mHandler.post(() -> mInjector.getNotificationManager().notifyAsUser(
21157                 null, SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED, notification,
21158                 UserHandle.of(getProfileParentId(profileUserId))));
21159     }
21160 
21161     private String getPersonalAppSuspensionButtonText() {
21162         return getUpdatableString(
21163                 PERSONAL_APP_SUSPENSION_TURN_ON_PROFILE,
21164                 R.string.personal_apps_suspended_turn_profile_on);
21165     }
21166 
21167     private String getPersonalAppSuspensionTitle() {
21168         return getUpdatableString(
21169                 PERSONAL_APP_SUSPENSION_TITLE, R.string.personal_apps_suspension_title);
21170     }
21171 
21172     private String getPersonalAppSuspensionText() {
21173         return getUpdatableString(
21174                 PERSONAL_APP_SUSPENSION_MESSAGE, R.string.personal_apps_suspension_text);
21175     }
21176 
21177     private String getPersonalAppSuspensionSoonText(String date, String time, int maxDays) {
21178         return getUpdatableString(
21179                 PERSONAL_APP_SUSPENSION_SOON_MESSAGE, R.string.personal_apps_suspension_soon_text,
21180                 date, time, maxDays);
21181     }
21182 
21183     private String getWorkProfileContentDescription() {
21184         return getUpdatableString(
21185                 NOTIFICATION_WORK_PROFILE_CONTENT_DESCRIPTION,
21186                 R.string.notification_work_profile_content_description);
21187     }
21188 
21189     @Override
21190     public void setManagedProfileMaximumTimeOff(ComponentName who, long timeoutMillis) {
21191         Objects.requireNonNull(who, "ComponentName is null");
21192         Preconditions.checkArgumentNonnegative(timeoutMillis, "Timeout must be non-negative.");
21193 
21194         final CallerIdentity caller = getCallerIdentity(who);
21195         // DO shouldn't be able to use this method.
21196         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
21197         Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller));
21198 
21199         final int userId = caller.getUserId();
21200         synchronized (getLockObject()) {
21201             final ActiveAdmin admin = getProfileOwnerLocked(userId);
21202 
21203             // Ensure the timeout is long enough to avoid having bad user experience.
21204             if (timeoutMillis > 0 && timeoutMillis < MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD
21205                     && !isAdminTestOnlyLocked(who, userId)) {
21206                 timeoutMillis = MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD;
21207             }
21208             if (admin.mProfileMaximumTimeOffMillis == timeoutMillis) {
21209                 return;
21210             }
21211             admin.mProfileMaximumTimeOffMillis = timeoutMillis;
21212             saveSettingsLocked(userId);
21213         }
21214 
21215         mInjector.binderWithCleanCallingIdentity(
21216                 () -> updatePersonalAppsSuspension(userId));
21217 
21218         DevicePolicyEventLogger
21219                 .createEvent(DevicePolicyEnums.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF)
21220                 .setAdmin(caller.getComponentName())
21221                 .setTimePeriod(timeoutMillis)
21222                 .write();
21223     }
21224 
21225     private boolean canHandleCheckPolicyComplianceIntent(CallerIdentity caller) {
21226         mInjector.binderWithCleanCallingIdentity(() -> {
21227             final Intent intent = new Intent(DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE);
21228             intent.setPackage(caller.getPackageName());
21229             final List<ResolveInfo> handlers =
21230                     mInjector.getPackageManager().queryIntentActivitiesAsUser(intent, /* flags= */
21231                             0, caller.getUserId());
21232             return !handlers.isEmpty();
21233         });
21234         return true;
21235     }
21236 
21237     @Override
21238     public long getManagedProfileMaximumTimeOff(ComponentName who) {
21239         Objects.requireNonNull(who, "ComponentName is null");
21240 
21241         final CallerIdentity caller = getCallerIdentity(who);
21242         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
21243 
21244         synchronized (getLockObject()) {
21245             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
21246             return admin.mProfileMaximumTimeOffMillis;
21247         }
21248     }
21249 
21250     @Override
21251     public void acknowledgeDeviceCompliant() {
21252         final CallerIdentity caller = getCallerIdentity();
21253         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
21254         enforceUserUnlocked(caller.getUserId());
21255 
21256         synchronized (getLockObject()) {
21257             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
21258             if (admin.mProfileOffDeadline > 0) {
21259                 admin.mProfileOffDeadline = 0;
21260                 saveSettingsLocked(caller.getUserId());
21261             }
21262         }
21263     }
21264 
21265     @Override
21266     public boolean isComplianceAcknowledgementRequired() {
21267         final CallerIdentity caller = getCallerIdentity();
21268         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
21269         enforceUserUnlocked(caller.getUserId());
21270 
21271         synchronized (getLockObject()) {
21272             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
21273             return admin.mProfileOffDeadline != 0;
21274         }
21275     }
21276 
21277     @Override
21278     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
21279         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
21280                 String.format(NOT_SYSTEM_CALLER_MSG,
21281                         "call canProfileOwnerResetPasswordWhenLocked"));
21282         synchronized (getLockObject()) {
21283             final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(userId);
21284             DevicePolicyData policy = getUserData(userId);
21285             if (poAdmin == null
21286                     || getEncryptionStatus() != ENCRYPTION_STATUS_ACTIVE_PER_USER
21287                     || !isResetPasswordTokenActiveForUserLocked(
21288                             policy.mPasswordTokenHandle, userId)) {
21289                 return false;
21290             }
21291             final ApplicationInfo poAppInfo;
21292             try {
21293                 poAppInfo = mIPackageManager.getApplicationInfo(
21294                         poAdmin.info.getPackageName(), 0 /* flags */, userId);
21295             } catch (RemoteException e) {
21296                 Slogf.e(LOG_TAG, "Failed to query PO app info", e);
21297                 return false;
21298             }
21299             if (poAppInfo == null) {
21300                 Slogf.wtf(LOG_TAG, "Cannot find AppInfo for profile owner");
21301                 return false;
21302             }
21303             if (!poAppInfo.isEncryptionAware()) {
21304                 return false;
21305             }
21306             Slogf.d(LOG_TAG, "PO should be able to reset password from direct boot");
21307             return true;
21308         }
21309     }
21310 
21311     @Override
21312     public String getEnrollmentSpecificId(String callerPackage) {
21313         if (!mHasFeature) {
21314             return "";
21315         }
21316 
21317         final CallerIdentity caller = getCallerIdentity(callerPackage);
21318 
21319         if (Flags.permissionMigrationForZeroTrustImplEnabled()) {
21320             enforcePermission(MANAGE_DEVICE_POLICY_CERTIFICATES, caller.getPackageName());
21321         } else {
21322             Preconditions.checkCallAuthorization(
21323                     isDefaultDeviceOwner(caller) || isProfileOwner(caller)
21324                             || isCallerDelegate(caller, DELEGATION_CERT_INSTALL));
21325         }
21326         synchronized (getLockObject()) {
21327             final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
21328                     caller.getUserId());
21329             final String esid = requiredAdmin != null ? requiredAdmin.mEnrollmentSpecificId : null;
21330             return esid != null ? esid : "";
21331         }
21332     }
21333 
21334     @Override
21335     public void setOrganizationIdForUser(
21336             @NonNull String callerPackage, @NonNull String organizationId, int userId) {
21337         if (!mHasFeature) {
21338             return;
21339         }
21340         Objects.requireNonNull(callerPackage);
21341 
21342         final CallerIdentity caller = getCallerIdentity(callerPackage);
21343         // Only the DPC can set this ID.
21344         Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller) || isProfileOwner(caller),
21345                 "Only a Device Owner or Profile Owner may set the Enterprise ID.");
21346         // Empty enterprise ID must not be provided in calls to this method.
21347         Preconditions.checkArgument(!TextUtils.isEmpty(organizationId),
21348                 "Enterprise ID may not be empty.");
21349 
21350         Slogf.i(LOG_TAG, "Setting Enterprise ID to %s for user %d", organizationId, userId);
21351 
21352         synchronized (mESIDInitilizationLock) {
21353             if (mEsidCalculator == null) {
21354                 mInjector.binderWithCleanCallingIdentity(() -> {
21355                     mEsidCalculator = mInjector.newEnterpriseSpecificIdCalculator();
21356                 });
21357             }
21358         }
21359 
21360         final String ownerPackage;
21361         synchronized (getLockObject()) {
21362             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
21363             // As the caller is the system, it must specify the component name of the profile owner
21364             // as a safety check.
21365             Preconditions.checkCallAuthorization(
21366                     owner != null && owner.getUserHandle().getIdentifier() == userId,
21367                     String.format("The Profile Owner or Device Owner may only set the Enterprise ID"
21368                             + " on its own user, called on user %d but owner user is %d", userId,
21369                             owner.getUserHandle().getIdentifier()));
21370             ownerPackage = owner.info.getPackageName();
21371             Preconditions.checkState(
21372                     TextUtils.isEmpty(owner.mOrganizationId) || owner.mOrganizationId.equals(
21373                             organizationId),
21374                     "The organization ID has been previously set to a different value and cannot "
21375                             + "be changed");
21376             final String dpcPackage = owner.info.getPackageName();
21377             final String esid = mEsidCalculator.calculateEnterpriseId(dpcPackage,
21378                     organizationId);
21379             owner.mOrganizationId = organizationId;
21380             owner.mEnrollmentSpecificId = esid;
21381             saveSettingsLocked(userId);
21382         }
21383 
21384         DevicePolicyEventLogger
21385                 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_ID)
21386                 .setAdmin(ownerPackage)
21387                 .setBoolean(isManagedProfile(userId))
21388                 .write();
21389     }
21390 
21391     @Override
21392     public void clearOrganizationIdForUser(int userHandle) {
21393         Preconditions.checkCallAuthorization(
21394                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
21395 
21396         synchronized (getLockObject()) {
21397             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userHandle);
21398             owner.mOrganizationId = null;
21399             owner.mEnrollmentSpecificId = null;
21400             saveSettingsLocked(userHandle);
21401         }
21402     }
21403 
21404     @Override
21405     public UserHandle createAndProvisionManagedProfile(
21406             @NonNull ManagedProfileProvisioningParams provisioningParams,
21407             @NonNull String callerPackage) {
21408         Objects.requireNonNull(provisioningParams, "provisioningParams is null");
21409         Objects.requireNonNull(callerPackage, "callerPackage is null");
21410 
21411         final ComponentName admin = provisioningParams.getProfileAdminComponentName();
21412         Objects.requireNonNull(admin, "admin is null");
21413 
21414         final CallerIdentity caller = getCallerIdentity(callerPackage);
21415         Preconditions.checkCallAuthorization(
21416                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
21417 
21418         provisioningParams.logParams(callerPackage);
21419 
21420         UserInfo userInfo = null;
21421         final long identity = Binder.clearCallingIdentity();
21422         try {
21423             final int result = checkProvisioningPreconditionSkipPermission(
21424                     ACTION_PROVISION_MANAGED_PROFILE, admin, caller.getUserId());
21425             if (result != STATUS_OK) {
21426                 throw new ServiceSpecificException(
21427                         ERROR_PRE_CONDITION_FAILED,
21428                         "Provisioning preconditions failed with result: " + result);
21429             }
21430 
21431             final long startTime = SystemClock.elapsedRealtime();
21432 
21433             onCreateAndProvisionManagedProfileStarted(provisioningParams);
21434 
21435             final Set<String> nonRequiredApps = provisioningParams.isLeaveAllSystemAppsEnabled()
21436                     ? Collections.emptySet()
21437                     : mOverlayPackagesProvider.getNonRequiredApps(
21438                             admin, caller.getUserId(), ACTION_PROVISION_MANAGED_PROFILE);
21439             if (nonRequiredApps.isEmpty()) {
21440                 Slogf.i(LOG_TAG, "No disallowed packages for the managed profile.");
21441             } else {
21442                 for (String packageName : nonRequiredApps) {
21443                     Slogf.i(LOG_TAG, "Disallowed package [" + packageName + "]");
21444                 }
21445             }
21446 
21447             userInfo = mUserManager.createProfileForUserEvenWhenDisallowed(
21448                     provisioningParams.getProfileName(),
21449                     UserManager.USER_TYPE_PROFILE_MANAGED,
21450                     UserInfo.FLAG_DISABLED,
21451                     caller.getUserId(),
21452                     nonRequiredApps.toArray(new String[nonRequiredApps.size()]));
21453             if (userInfo == null) {
21454                 throw new ServiceSpecificException(
21455                         ERROR_PROFILE_CREATION_FAILED,
21456                         "Error creating profile, createProfileForUserEvenWhenDisallowed "
21457                                 + "returned null.");
21458             }
21459             resetInteractAcrossProfilesAppOps(caller.getUserId());
21460             logEventDuration(
21461                     DevicePolicyEnums.PLATFORM_PROVISIONING_CREATE_PROFILE_MS,
21462                     startTime,
21463                     callerPackage);
21464 
21465             maybeInstallDevicePolicyManagementRoleHolderInUser(userInfo.id);
21466 
21467             installExistingAdminPackage(userInfo.id, admin.getPackageName());
21468             if (!enableAdminAndSetProfileOwner(userInfo.id, caller.getUserId(), admin)) {
21469                 throw new ServiceSpecificException(
21470                         ERROR_SETTING_PROFILE_OWNER_FAILED,
21471                         "Error setting profile owner.");
21472             }
21473             setUserSetupComplete(userInfo.id);
21474 
21475             startProfileForSetup(userInfo.id, callerPackage);
21476             maybeMigrateAccount(
21477                     userInfo.id, caller.getUserId(), provisioningParams.getAccountToMigrate(),
21478                     provisioningParams.isKeepingAccountOnMigration(), callerPackage);
21479 
21480             if (provisioningParams.isOrganizationOwnedProvisioning()) {
21481                 synchronized (getLockObject()) {
21482                     setProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(admin, userInfo.id,
21483                             true);
21484                 }
21485             }
21486 
21487             onCreateAndProvisionManagedProfileCompleted(provisioningParams);
21488 
21489             sendProvisioningCompletedBroadcast(
21490                     userInfo.id,
21491                     ACTION_PROVISION_MANAGED_PROFILE,
21492                     provisioningParams.isLeaveAllSystemAppsEnabled());
21493 
21494             return userInfo.getUserHandle();
21495         } catch (Exception e) {
21496             DevicePolicyEventLogger
21497                     .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
21498                     .setStrings(callerPackage)
21499                     .write();
21500             // In case of any errors during provisioning, remove the newly created profile.
21501             if (userInfo != null) {
21502                 mUserManager.removeUserEvenWhenDisallowed(userInfo.id);
21503             }
21504             throw e;
21505         } finally {
21506             Binder.restoreCallingIdentity(identity);
21507         }
21508     }
21509 
21510     @Override
21511     public void finalizeWorkProfileProvisioning(UserHandle managedProfileUser,
21512             Account migratedAccount) {
21513         Preconditions.checkCallAuthorization(
21514                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
21515 
21516         if (!isManagedProfile(managedProfileUser.getIdentifier())) {
21517             throw new IllegalStateException("Given user is not a managed profile");
21518         }
21519         ComponentName profileOwnerComponent =
21520                 mOwners.getProfileOwnerComponent(managedProfileUser.getIdentifier());
21521         if (profileOwnerComponent == null) {
21522             throw new IllegalStateException("There is no profile owner on the given profile");
21523         }
21524         Intent primaryProfileSuccessIntent = new Intent(ACTION_MANAGED_PROFILE_PROVISIONED);
21525         primaryProfileSuccessIntent.setPackage(profileOwnerComponent.getPackageName());
21526         primaryProfileSuccessIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES
21527                 | Intent.FLAG_RECEIVER_FOREGROUND);
21528         primaryProfileSuccessIntent.putExtra(Intent.EXTRA_USER, managedProfileUser);
21529 
21530         if (migratedAccount != null) {
21531             primaryProfileSuccessIntent.putExtra(EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE,
21532                     migratedAccount);
21533         }
21534 
21535         mContext.sendBroadcastAsUser(primaryProfileSuccessIntent,
21536                 UserHandle.of(getProfileParentId(managedProfileUser.getIdentifier())));
21537     }
21538 
21539     /**
21540      * Callback called at the beginning of {@link #createAndProvisionManagedProfile(
21541      * ManagedProfileProvisioningParams, String)} after the relevant prechecks have passed.
21542      *
21543      * <p>The logic in this method blocks provisioning.
21544      *
21545      * <p>This method is meant to be overridden by OEMs.
21546      */
21547     private void onCreateAndProvisionManagedProfileStarted(
21548             ManagedProfileProvisioningParams provisioningParams) {}
21549 
21550     /**
21551      * Callback called at the end of {@link #createAndProvisionManagedProfile(
21552      * ManagedProfileProvisioningParams, String)} after all the other provisioning tasks
21553      * have completed successfully.
21554      *
21555      * <p>The logic in this method blocks provisioning.
21556      *
21557      * <p>This method is meant to be overridden by OEMs.
21558      */
21559     private void onCreateAndProvisionManagedProfileCompleted(
21560             ManagedProfileProvisioningParams provisioningParams) {}
21561 
21562     private void maybeInstallDevicePolicyManagementRoleHolderInUser(int targetUserId) {
21563         String devicePolicyManagerRoleHolderPackageName =
21564                 getRoleHolderPackageName(mContext, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT);
21565         if (devicePolicyManagerRoleHolderPackageName == null) {
21566             Slogf.d(LOG_TAG, "No device policy management role holder specified.");
21567             return;
21568         }
21569         try {
21570             if (mIPackageManager.isPackageAvailable(
21571                     devicePolicyManagerRoleHolderPackageName, targetUserId)) {
21572                 Slogf.d(LOG_TAG, "The device policy management role holder "
21573                         + devicePolicyManagerRoleHolderPackageName + " is already installed in "
21574                         + "user " + targetUserId);
21575                 return;
21576             }
21577             Slogf.d(LOG_TAG, "Installing the device policy management role holder "
21578                     + devicePolicyManagerRoleHolderPackageName + " in user " + targetUserId);
21579             mIPackageManager.installExistingPackageAsUser(
21580                     devicePolicyManagerRoleHolderPackageName,
21581                     targetUserId,
21582                     PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
21583                     PackageManager.INSTALL_REASON_POLICY,
21584                     /* whiteListedPermissions= */ null);
21585         } catch (RemoteException e) {
21586             // Does not happen, same process
21587         }
21588     }
21589 
21590     /**
21591      * If multiple packages hold the role, returns the first package in the list.
21592      */
21593     @Nullable
21594     private String getRoleHolderPackageName(Context context, String role) {
21595         return getRoleHolderPackageNameOnUser(context, role, Process.myUserHandle());
21596     }
21597 
21598     /**
21599      * If multiple packages hold the role, returns the first package in the list.
21600      */
21601     @Nullable
21602     private String getRoleHolderPackageNameOnUser(Context context, String role, UserHandle user) {
21603         RoleManager roleManager = context.getSystemService(RoleManager.class);
21604 
21605         // Calling identity needs to be cleared as this method is used in the permissions checks.
21606         return mInjector.binderWithCleanCallingIdentity(() -> {
21607             List<String> roleHolders = roleManager.getRoleHoldersAsUser(role, user);
21608             if (roleHolders.isEmpty()) {
21609                 return null;
21610             }
21611             return roleHolders.get(0);
21612         });
21613     }
21614 
21615     private boolean isCallerDevicePolicyManagementRoleHolder(CallerIdentity caller) {
21616         return doesCallerHoldRole(caller, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT);
21617     }
21618 
21619     private boolean isCallerSystemSupervisionRoleHolder(CallerIdentity caller) {
21620         return doesCallerHoldRole(caller, RoleManager.ROLE_SYSTEM_SUPERVISION);
21621     }
21622 
21623     /**
21624      * Check if the caller is holding the given role on the calling user.
21625      *
21626      * @param caller the caller you wish to check
21627      * @param role the name of the role to check for.
21628      * @return {@code true} if the caller holds the role, {@code false} otherwise.
21629      */
21630     private boolean doesCallerHoldRole(CallerIdentity caller, String role) {
21631         int callerUid = caller.getUid();
21632         String roleHolderPackageName =
21633                 getRoleHolderPackageNameOnUser(role, caller.getUserId());
21634         int roleHolderUid = mInjector.getPackageManagerInternal().getPackageUid(
21635                 roleHolderPackageName, 0, caller.getUserId());
21636 
21637         return callerUid == roleHolderUid;
21638     }
21639 
21640     /**
21641      * Return the package name of the role holder on the given user.
21642      *
21643      * <p>If the userId passed in is {@link UserHandle.USER_ALL} then every user will be checked and
21644      * the package name of the role holder on the first user where there is a role holder is
21645      * returned.
21646      *
21647      * @param role the name of the role to check for.
21648      * @param userId the userId to check for the role holder on.
21649      * @return the package name of the role holder
21650      */
21651     @Nullable
21652     private String getRoleHolderPackageNameOnUser(String role, int userId) {
21653         RoleManager roleManager = mContext.getSystemService(RoleManager.class);
21654 
21655         // Clear calling identity as the RoleManager APIs require privileged permissions.
21656         return mInjector.binderWithCleanCallingIdentity(() -> {
21657             List<UserInfo> users;
21658             // Interpret USER_ALL as meaning "any" user.
21659             if (userId == UserHandle.USER_ALL) {
21660                 users = mInjector.getUserManagerInternal().getUsers(/*excludeDying=*/ true);
21661             } else {
21662                 users = List.of(new UserInfo(userId, /*name=*/ null, /*flags=*/ 0));
21663             }
21664             for (UserInfo user : users) {
21665                 List<String> roleHolders =
21666                         roleManager.getRoleHoldersAsUser(role, user.getUserHandle());
21667                 if (!roleHolders.isEmpty()) {
21668                     return roleHolders.get(0);
21669                 }
21670             }
21671             return null;
21672         });
21673     }
21674 
21675     private void resetInteractAcrossProfilesAppOps(@UserIdInt int userId) {
21676         mInjector.getCrossProfileApps(userId).clearInteractAcrossProfilesAppOps();
21677         pregrantDefaultInteractAcrossProfilesAppOps(userId);
21678     }
21679 
21680     private void pregrantDefaultInteractAcrossProfilesAppOps(@UserIdInt int userId) {
21681         final String op =
21682                 AppOpsManager.permissionToOp(Manifest.permission.INTERACT_ACROSS_PROFILES);
21683         for (String packageName : getConfigurableDefaultCrossProfilePackages(userId)) {
21684             if (!appOpIsDefaultOrAllowed(userId, op, packageName)) {
21685                 continue;
21686             }
21687             mInjector.getCrossProfileApps(userId).setInteractAcrossProfilesAppOp(
21688                     packageName, MODE_ALLOWED);
21689         }
21690     }
21691 
21692     private Set<String> getConfigurableDefaultCrossProfilePackages(@UserIdInt int userId) {
21693         List<String> defaultPackages = getDefaultCrossProfilePackages();
21694         return defaultPackages.stream().filter(
21695                 mInjector.getCrossProfileApps(userId)::canConfigureInteractAcrossProfiles).collect(
21696                 Collectors.toSet());
21697     }
21698 
21699     private boolean appOpIsDefaultOrAllowed(@UserIdInt int userId, String op, String packageName) {
21700         try {
21701             final int uid = mContext.createContextAsUser(UserHandle.of(userId), /* flags= */ 0).
21702                     getPackageManager().getPackageUid(packageName, /* flags= */ 0);
21703             int mode = mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
21704                     op, uid, packageName);
21705             return mode == MODE_ALLOWED || mode == MODE_DEFAULT;
21706         } catch (NameNotFoundException e) {
21707             return false;
21708         }
21709     }
21710 
21711     private void installExistingAdminPackage(int userId, String packageName) {
21712         try {
21713             final int status = mContext.getPackageManager().installExistingPackageAsUser(
21714                     packageName,
21715                     userId);
21716             if (status != PackageManager.INSTALL_SUCCEEDED) {
21717                 throw new ServiceSpecificException(
21718                         ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED,
21719                         String.format("Failed to install existing package %s for user %d with "
21720                                         + "result code %d",
21721                                 packageName, userId, status));
21722             }
21723         } catch (NameNotFoundException e) {
21724             throw new ServiceSpecificException(
21725                     ERROR_ADMIN_PACKAGE_INSTALLATION_FAILED,
21726                     String.format("Failed to install existing package %s for user %d: %s",
21727                             packageName, userId, e.getMessage()));
21728         }
21729     }
21730 
21731     private boolean enableAdminAndSetProfileOwner(
21732             @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) {
21733         enableAndSetActiveAdmin(userId, callingUserId, adminComponent);
21734         return setProfileOwner(adminComponent, userId);
21735     }
21736 
21737     private void enableAndSetActiveAdmin(
21738             @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) {
21739         final String adminPackage = adminComponent.getPackageName();
21740         enablePackage(adminPackage, callingUserId);
21741         setActiveAdmin(adminComponent, /* refreshing= */ true, userId);
21742     }
21743 
21744     private void enablePackage(String packageName, @UserIdInt int userId) {
21745         try {
21746             final int enabledSetting = mIPackageManager.getApplicationEnabledSetting(
21747                     packageName, userId);
21748             if (enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21749                     && enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21750                 mIPackageManager.setApplicationEnabledSetting(
21751                         packageName,
21752                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
21753                         // Device policy app may have launched ManagedProvisioning, play nice and
21754                         // don't kill it as a side-effect of this call.
21755                         PackageManager.DONT_KILL_APP,
21756                         userId,
21757                         mContext.getOpPackageName());
21758             }
21759         } catch (RemoteException e) {
21760             // Shouldn't happen.
21761             Slogf.wtf(LOG_TAG, "Error setting application enabled", e);
21762         }
21763     }
21764 
21765     private void setUserSetupComplete(@UserIdInt int userId) {
21766         Settings.Secure.putIntForUser(
21767                 mContext.getContentResolver(), USER_SETUP_COMPLETE, 1, userId);
21768     }
21769 
21770     private void startProfileForSetup(@UserIdInt int userId, String callerPackage)
21771             throws IllegalStateException {
21772         Slogf.i(LOG_TAG, "Starting profile %d as requested by package %s", userId, callerPackage);
21773         final long startTime = SystemClock.elapsedRealtime();
21774         final UserUnlockedBlockingReceiver unlockedReceiver = new UserUnlockedBlockingReceiver(
21775                 userId);
21776         mContext.registerReceiverAsUser(
21777                 unlockedReceiver,
21778                 new UserHandle(userId),
21779                 new IntentFilter(Intent.ACTION_USER_UNLOCKED),
21780                 /* broadcastPermission = */ null,
21781                 /* scheduler= */ null);
21782         try {
21783             // Must call startProfileEvenWhenDisabled(), as profile is not enabled yet
21784             if (!mInjector.getActivityManagerInternal().startProfileEvenWhenDisabled(userId)) {
21785                 throw new ServiceSpecificException(ERROR_STARTING_PROFILE_FAILED,
21786                         String.format("Unable to start user %d in background", userId));
21787             }
21788 
21789             if (!unlockedReceiver.waitForUserUnlocked()) {
21790                 throw new ServiceSpecificException(ERROR_STARTING_PROFILE_FAILED,
21791                         String.format("Timeout whilst waiting for unlock of user %d.", userId));
21792             }
21793             logEventDuration(
21794                     DevicePolicyEnums.PLATFORM_PROVISIONING_START_PROFILE_MS,
21795                     startTime,
21796                     callerPackage);
21797         } finally {
21798             mContext.unregisterReceiver(unlockedReceiver);
21799         }
21800     }
21801 
21802     private void maybeMigrateAccount(
21803             @UserIdInt int targetUserId, @UserIdInt int sourceUserId, Account accountToMigrate,
21804             boolean keepAccountMigrated, String callerPackage) {
21805         final UserHandle sourceUser = UserHandle.of(sourceUserId);
21806         final UserHandle targetUser = UserHandle.of(targetUserId);
21807         if (accountToMigrate == null) {
21808             Slogf.d(LOG_TAG, "No account to migrate.");
21809             return;
21810         }
21811         if (sourceUser.equals(targetUser)) {
21812             Slogf.w(LOG_TAG, "sourceUser and targetUser are the same, won't migrate account.");
21813             return;
21814         }
21815 
21816         if (Flags.copyAccountWithRetryEnabled()) {
21817             boolean copySucceeded = false;
21818             int retryAttemptsLeft = RETRY_COPY_ACCOUNT_ATTEMPTS;
21819             while (!copySucceeded && (retryAttemptsLeft > 0)) {
21820                 Slogf.i(LOG_TAG, "Copying account. Attempts left : " + retryAttemptsLeft);
21821                 copySucceeded =
21822                         copyAccount(targetUser, sourceUser, accountToMigrate, callerPackage);
21823                 retryAttemptsLeft--;
21824             }
21825         } else {
21826             copyAccount(targetUser, sourceUser, accountToMigrate, callerPackage);
21827         }
21828         if (!keepAccountMigrated) {
21829             removeAccount(accountToMigrate, sourceUserId);
21830         }
21831 
21832     }
21833 
21834     private boolean copyAccount(
21835             UserHandle targetUser, UserHandle sourceUser, Account accountToMigrate,
21836             String callerPackage) {
21837         final long startTime = SystemClock.elapsedRealtime();
21838         try {
21839             final AccountManager accountManager = mContext.getSystemService(AccountManager.class);
21840             final boolean copySucceeded = accountManager.copyAccountToUser(
21841                     accountToMigrate,
21842                     sourceUser,
21843                     targetUser,
21844                     /* callback= */ null, /* handler= */ null)
21845                     .getResult(60 * 3, TimeUnit.SECONDS);
21846             if (copySucceeded) {
21847                 logCopyAccountStatus(COPY_ACCOUNT_SUCCEEDED, callerPackage);
21848                 logEventDuration(
21849                         DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_MS,
21850                         startTime,
21851                         callerPackage);
21852                 Slogf.i(LOG_TAG, "Copy account successful to " + targetUser);
21853                 return true;
21854             } else {
21855                 logCopyAccountStatus(COPY_ACCOUNT_FAILED, callerPackage);
21856                 Slogf.e(LOG_TAG, "Failed to copy account to " + targetUser);
21857             }
21858         } catch (OperationCanceledException e) {
21859             // Account migration is not considered a critical operation.
21860             logCopyAccountStatus(COPY_ACCOUNT_TIMED_OUT, callerPackage);
21861             Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e);
21862         } catch (AuthenticatorException | IOException e) {
21863             logCopyAccountStatus(COPY_ACCOUNT_EXCEPTION, callerPackage);
21864             Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e);
21865         }
21866         return false;
21867     }
21868 
21869     private static void logCopyAccountStatus(@CopyAccountStatus int status, String callerPackage) {
21870         DevicePolicyEventLogger
21871                 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_STATUS)
21872                 .setInt(status)
21873                 .setStrings(callerPackage)
21874                 .write();
21875     }
21876 
21877     private void removeAccount(Account account, @UserIdInt int sourceUserId) {
21878         final AccountManager accountManager = mContext.createContextAsUser(
21879                         UserHandle.of(sourceUserId), /* flags= */ 0)
21880                 .getSystemService(AccountManager.class);
21881         try {
21882             final Bundle result = accountManager.removeAccount(account,
21883                     null, null /* callback */, null /* handler */).getResult(60, TimeUnit.SECONDS);
21884             if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, /* default */ false)) {
21885                 Slogf.i(LOG_TAG, "Account removed from the primary user.");
21886             } else {
21887                 // TODO(174768447): Revisit start activity logic.
21888                 final Intent removeIntent = result.getParcelable(AccountManager.KEY_INTENT, android.content.Intent.class);
21889                 removeIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
21890                 if (removeIntent != null) {
21891                     Slogf.i(LOG_TAG, "Starting activity to remove account");
21892                     new Handler(Looper.getMainLooper()).post(() -> {
21893                         mContext.startActivity(removeIntent);
21894                     });
21895                 } else {
21896                     Slogf.e(LOG_TAG, "Could not remove account from the primary user.");
21897                 }
21898             }
21899         } catch (OperationCanceledException | AuthenticatorException | IOException e) {
21900             Slogf.e(LOG_TAG, "Exception removing account from the primary user.", e);
21901         }
21902     }
21903 
21904     @Override
21905     public void provisionFullyManagedDevice(
21906             @NonNull FullyManagedDeviceProvisioningParams provisioningParams,
21907             @NonNull String callerPackage) {
21908         Objects.requireNonNull(provisioningParams, "provisioningParams is null.");
21909         Objects.requireNonNull(callerPackage, "callerPackage is null.");
21910 
21911         ComponentName deviceAdmin = provisioningParams.getDeviceAdminComponentName();
21912         Objects.requireNonNull(deviceAdmin, "admin is null.");
21913         Objects.requireNonNull(provisioningParams.getOwnerName(), "owner name is null.");
21914 
21915         final CallerIdentity caller = getCallerIdentity(callerPackage);
21916         Preconditions.checkCallAuthorization(
21917                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS)
21918                         || (hasCallingOrSelfPermission(permission.PROVISION_DEMO_DEVICE)
21919                         && provisioningParams.isDemoDevice()));
21920 
21921         provisioningParams.logParams(callerPackage);
21922 
21923         final long identity = Binder.clearCallingIdentity();
21924         try {
21925             boolean isSingleUserMode;
21926             if (Flags.headlessDeviceOwnerProvisioningFixEnabled()) {
21927                 int headlessDeviceOwnerMode = getHeadlessDeviceOwnerModeForDeviceAdmin(
21928                         deviceAdmin, caller.getUserId());
21929                 isSingleUserMode =
21930                         headlessDeviceOwnerMode == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER;
21931             } else {
21932                 isSingleUserMode =
21933                         getHeadlessDeviceOwnerModeForDeviceOwner()
21934                                 == HEADLESS_DEVICE_OWNER_MODE_SINGLE_USER;
21935             }
21936 
21937             if (Flags.headlessSingleMinTargetSdk()
21938                     && mInjector.userManagerIsHeadlessSystemUserMode()
21939                     && isSingleUserMode
21940                     && !mInjector.isChangeEnabled(
21941                             PROVISION_SINGLE_USER_MODE, deviceAdmin.getPackageName(),
21942                     caller.getUserId())) {
21943                 throw new IllegalStateException("Device admin is not targeting Android V.");
21944             }
21945 
21946             int result = checkProvisioningPreconditionSkipPermission(
21947                     ACTION_PROVISION_MANAGED_DEVICE, deviceAdmin, caller.getUserId());
21948             if (result != STATUS_OK) {
21949                 throw new ServiceSpecificException(
21950                         ERROR_PRE_CONDITION_FAILED,
21951                         "Provisioning preconditions failed with result: " + result);
21952             }
21953             onProvisionFullyManagedDeviceStarted(provisioningParams);
21954 
21955             // These properties are global so will apply on all users
21956             setTimeAndTimezone(provisioningParams.getTimeZone(), provisioningParams.getLocalTime());
21957             setLocale(provisioningParams.getLocale());
21958 
21959             int deviceOwnerUserId = Flags.headlessDeviceOwnerSingleUserEnabled()
21960                     && isSingleUserMode && mInjector.userManagerIsHeadlessSystemUserMode()
21961                     ? mUserManagerInternal.getMainUserId() : UserHandle.USER_SYSTEM;
21962 
21963             if (!removeNonRequiredAppsForManagedDevice(
21964                     deviceOwnerUserId,
21965                     provisioningParams.isLeaveAllSystemAppsEnabled(),
21966                     deviceAdmin)) {
21967                 throw new ServiceSpecificException(
21968                         ERROR_REMOVE_NON_REQUIRED_APPS_FAILED,
21969                         "PackageManager failed to remove non required apps.");
21970             }
21971 
21972             if (!setActiveAdminAndDeviceOwner(deviceOwnerUserId, deviceAdmin)) {
21973                 throw new ServiceSpecificException(
21974                         ERROR_SET_DEVICE_OWNER_FAILED, "Failed to set device owner.");
21975             }
21976 
21977             disallowAddUser();
21978             setAdminCanGrantSensorsPermissionForUserUnchecked(
21979                     deviceOwnerUserId, provisioningParams.canDeviceOwnerGrantSensorsPermissions());
21980             setDemoDeviceStateUnchecked(deviceOwnerUserId, provisioningParams.isDemoDevice());
21981             onProvisionFullyManagedDeviceCompleted(provisioningParams);
21982             sendProvisioningCompletedBroadcast(
21983                     deviceOwnerUserId,
21984                     ACTION_PROVISION_MANAGED_DEVICE,
21985                     provisioningParams.isLeaveAllSystemAppsEnabled());
21986         } catch (Exception e) {
21987             DevicePolicyEventLogger
21988                     .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
21989                     .setStrings(callerPackage)
21990                     .write();
21991             throw e;
21992         } finally {
21993             Binder.restoreCallingIdentity(identity);
21994         }
21995     }
21996 
21997     /**
21998      * Callback called at the beginning of {@link #provisionFullyManagedDevice(
21999      * FullyManagedDeviceProvisioningParams, String)} after the relevant prechecks have passed.
22000      *
22001      * <p>The logic in this method blocks provisioning.
22002      *
22003      * <p>This method is meant to be overridden by OEMs.
22004      */
22005     private void onProvisionFullyManagedDeviceStarted(
22006             FullyManagedDeviceProvisioningParams provisioningParams) {}
22007 
22008     /**
22009      * Callback called at the end of {@link #provisionFullyManagedDevice(
22010      * FullyManagedDeviceProvisioningParams, String)} after all the other provisioning tasks
22011      * have completed successfully.
22012      *
22013      * <p>The logic in this method blocks provisioning.
22014      *
22015      * <p>This method is meant to be overridden by OEMs.
22016      */
22017     private void onProvisionFullyManagedDeviceCompleted(
22018             FullyManagedDeviceProvisioningParams provisioningParams) {}
22019 
22020     private void setTimeAndTimezone(String timeZone, long localTime) {
22021         try {
22022             final AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class);
22023             if (timeZone != null) {
22024                 alarmManager.setTimeZone(timeZone);
22025             }
22026             if (localTime > 0) {
22027                 alarmManager.setTime(localTime);
22028             }
22029         } catch (Exception e) {
22030             // Do not stop provisioning and ignore this error.
22031             Slogf.e(LOG_TAG, "Alarm manager failed to set the system time/timezone.", e);
22032         }
22033     }
22034 
22035     private void setLocale(Locale locale) {
22036         if (locale == null || locale.equals(Locale.getDefault())) {
22037             return;
22038         }
22039         try {
22040             // If locale is different from current locale this results in a configuration change,
22041             // which will trigger the restarting of the activity.
22042             LocalePicker.updateLocale(locale);
22043         } catch (Exception e) {
22044             // Do not stop provisioning and ignore this error.
22045             Slogf.e(LOG_TAG, "Failed to set the system locale.", e);
22046         }
22047     }
22048 
22049     private boolean removeNonRequiredAppsForManagedDevice(
22050             @UserIdInt int userId, boolean leaveAllSystemAppsEnabled, ComponentName admin) {
22051         Set<String> packagesToDelete = leaveAllSystemAppsEnabled
22052                 ? Collections.emptySet()
22053                 : mOverlayPackagesProvider.getNonRequiredApps(
22054                         admin, userId, ACTION_PROVISION_MANAGED_DEVICE);
22055 
22056         removeNonInstalledPackages(packagesToDelete, userId);
22057         if (packagesToDelete.isEmpty()) {
22058             Slogf.i(LOG_TAG, "No packages to delete on user " + userId);
22059             return true;
22060         }
22061 
22062         NonRequiredPackageDeleteObserver packageDeleteObserver =
22063                 new NonRequiredPackageDeleteObserver(packagesToDelete.size());
22064         for (String packageName : packagesToDelete) {
22065             Slogf.i(LOG_TAG, "Deleting package [" + packageName + "] as user " + userId);
22066             mContext.getPackageManager().deletePackageAsUser(
22067                     packageName,
22068                     packageDeleteObserver,
22069                     PackageManager.DELETE_SYSTEM_APP,
22070                     userId);
22071         }
22072         Slogf.i(LOG_TAG, "Waiting for non required apps to be deleted");
22073         return packageDeleteObserver.awaitPackagesDeletion();
22074     }
22075 
22076     private void removeNonInstalledPackages(Set<String> packages, @UserIdInt int userId) {
22077         final Set<String> toBeRemoved = new HashSet<>();
22078         for (String packageName : packages) {
22079             if (!isPackageInstalledForUser(packageName, userId)) {
22080                 toBeRemoved.add(packageName);
22081             }
22082         }
22083         packages.removeAll(toBeRemoved);
22084     }
22085 
22086     private void disallowAddUser() {
22087         if (mIsAutomotive) {
22088             // Auto still enables adding users due to the communal nature of those devices
22089             if (mInjector.userManagerIsHeadlessSystemUserMode()) {
22090                 Slogf.i(LOG_TAG, "Not setting DISALLOW_ADD_USER on headless system user mode.");
22091                 return;
22092             }
22093         }
22094         for (UserInfo userInfo : mUserManager.getUsers()) {
22095             UserHandle userHandle = userInfo.getUserHandle();
22096             if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
22097                 mUserManager.setUserRestriction(
22098                         UserManager.DISALLOW_ADD_USER, /* value= */ true, userHandle);
22099             }
22100         }
22101     }
22102 
22103     private boolean setActiveAdminAndDeviceOwner(
22104             @UserIdInt int userId, ComponentName adminComponent) {
22105         enableAndSetActiveAdmin(userId, userId, adminComponent);
22106         // TODO(b/178187130): Directly set DO and remove the check once silent provisioning is no
22107         //  longer used.
22108         if (getDeviceOwnerComponent(/* callingUserOnly= */ true) == null) {
22109             return setDeviceOwner(adminComponent, userId,
22110                     /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
22111         }
22112         return true;
22113     }
22114 
22115     private static void logEventDuration(int eventId, long startTime, String callerPackage) {
22116         final long duration = SystemClock.elapsedRealtime() - startTime;
22117         DevicePolicyEventLogger
22118                 .createEvent(eventId)
22119                 .setTimePeriod(duration)
22120                 .setStrings(callerPackage)
22121                 .write();
22122     }
22123 
22124     @Override
22125     public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
22126         Preconditions.checkCallAuthorization(
22127                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
22128 
22129         mInjector.binderWithCleanCallingIdentity(() -> {
22130             try {
22131                 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
22132                 final int numOfProfiles = profiles.size();
22133                 if (numOfProfiles <= 1) {
22134                     return;
22135                 }
22136 
22137                 final String managedProvisioningPackageName = getManagedProvisioningPackage(
22138                         mContext);
22139                 // Removes cross profile intent filters from the parent to all the profiles.
22140                 mIPackageManager.clearCrossProfileIntentFilters(
22141                         userId, mContext.getOpPackageName());
22142                 // Setting and resetting default cross profile intent filters was previously handled
22143                 // by Managed Provisioning. For backwards compatibility, clear any intent filters
22144                 // that were set by ManagedProvisioning.
22145                 mIPackageManager.clearCrossProfileIntentFilters(
22146                         userId, managedProvisioningPackageName);
22147 
22148                 // For each profile reset cross profile intent filters
22149                 for (int i = 0; i < numOfProfiles; i++) {
22150                     UserInfo profile = profiles.get(i);
22151                     mIPackageManager.clearCrossProfileIntentFilters(
22152                             profile.id, mContext.getOpPackageName());
22153                     // Clear any intent filters that were set by ManagedProvisioning.
22154                     mIPackageManager.clearCrossProfileIntentFilters(
22155                             profile.id, managedProvisioningPackageName);
22156 
22157                     mUserManagerInternal.setDefaultCrossProfileIntentFilters(userId, profile.id);
22158                 }
22159             } catch (RemoteException e) {
22160                 // Shouldn't happen.
22161                 Slogf.wtf(LOG_TAG, "Error resetting default cross profile intent filters", e);
22162             }
22163         });
22164     }
22165 
22166     private void setAdminCanGrantSensorsPermissionForUserUnchecked(@UserIdInt int userId,
22167             boolean canGrant) {
22168         Slogf.d(LOG_TAG, "setAdminCanGrantSensorsPermissionForUserUnchecked(%d, %b)",
22169                 userId, canGrant);
22170         synchronized (getLockObject()) {
22171             ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
22172 
22173             Preconditions.checkState(
22174                     isDeviceOwner(owner) && owner.getUserHandle().getIdentifier() == userId,
22175                     "May only be set on a the user of a device owner.");
22176 
22177             owner.mAdminCanGrantSensorsPermissions = canGrant;
22178             mPolicyCache.setAdminCanGrantSensorsPermissions(canGrant);
22179             saveSettingsLocked(userId);
22180         }
22181     }
22182 
22183     private void setDemoDeviceStateUnchecked(@UserIdInt int userId, boolean isDemoDevice) {
22184         Slogf.d(LOG_TAG, "setDemoDeviceStateUnchecked(%d, %b)",
22185                 userId, isDemoDevice);
22186         if (!isDemoDevice) {
22187             return;
22188         }
22189         synchronized (getLockObject()) {
22190             mInjector.settingsGlobalPutStringForUser(
22191                     Settings.Global.DEVICE_DEMO_MODE, Integer.toString(/* value= */ 1), userId);
22192         }
22193 
22194         setUserProvisioningState(STATE_USER_SETUP_FINALIZED, userId);
22195     }
22196 
22197     private void updateAdminCanGrantSensorsPermissionCache(@UserIdInt int userId) {
22198         synchronized (getLockObject()) {
22199 
22200             ActiveAdmin owner;
22201             // If the user is affiliated the device (either a DO itself, or an affiliated PO),
22202             // use mAdminCanGrantSensorsPermissions from the DO
22203             if (isUserAffiliatedWithDeviceLocked(userId)) {
22204                 owner = getDeviceOwnerAdminLocked();
22205             } else {
22206                 owner = getDeviceOrProfileOwnerAdminLocked(userId);
22207             }
22208             boolean canGrant = owner != null ? owner.mAdminCanGrantSensorsPermissions : false;
22209             mPolicyCache.setAdminCanGrantSensorsPermissions(canGrant);
22210         }
22211     }
22212 
22213     private void updateNetworkPreferenceForUser(int userId,
22214             List<PreferentialNetworkServiceConfig> preferentialNetworkServiceConfigs) {
22215         if (!isManagedProfile(userId) && !isDeviceOwnerUserId(userId)) {
22216             return;
22217         }
22218         List<ProfileNetworkPreference> preferences = new ArrayList<>();
22219         for (PreferentialNetworkServiceConfig preferentialNetworkServiceConfig :
22220                 preferentialNetworkServiceConfigs) {
22221             ProfileNetworkPreference.Builder preferenceBuilder =
22222                     new ProfileNetworkPreference.Builder();
22223             if (preferentialNetworkServiceConfig.isEnabled()) {
22224                 if (preferentialNetworkServiceConfig.isFallbackToDefaultConnectionAllowed()) {
22225                     preferenceBuilder.setPreference(PROFILE_NETWORK_PREFERENCE_ENTERPRISE);
22226                 } else if (preferentialNetworkServiceConfig.shouldBlockNonMatchingNetworks()) {
22227                     preferenceBuilder.setPreference(
22228                             PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING);
22229                 } else {
22230                     preferenceBuilder.setPreference(
22231                             PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK);
22232                 }
22233                 preferenceBuilder.setIncludedUids(
22234                         preferentialNetworkServiceConfig.getIncludedUids());
22235                 preferenceBuilder.setExcludedUids(
22236                         preferentialNetworkServiceConfig.getExcludedUids());
22237                 preferenceBuilder.setPreferenceEnterpriseId(
22238                         preferentialNetworkServiceConfig.getNetworkId());
22239             } else {
22240                 preferenceBuilder.setPreference(PROFILE_NETWORK_PREFERENCE_DEFAULT);
22241             }
22242 
22243 
22244             preferences.add(preferenceBuilder.build());
22245         }
22246         Slogf.d(LOG_TAG, "updateNetworkPreferenceForUser to " + preferences);
22247         mInjector.binderWithCleanCallingIdentity(() ->
22248                 mInjector.getConnectivityManager().setProfileNetworkPreferences(
22249                         UserHandle.of(userId), preferences,
22250                         null /* executor */, null /* listener */));
22251     }
22252 
22253     @Override
22254     public boolean canAdminGrantSensorsPermissions() {
22255         if (!mHasFeature) {
22256             return false;
22257         }
22258 
22259         return mPolicyCache.canAdminGrantSensorsPermissions();
22260     }
22261 
22262     @Override
22263     public void setDeviceOwnerType(@NonNull ComponentName admin,
22264             @DeviceOwnerType int deviceOwnerType) {
22265         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22266                 MANAGE_PROFILE_AND_DEVICE_OWNERS));
22267 
22268         synchronized (getLockObject()) {
22269             setDeviceOwnerTypeLocked(admin, deviceOwnerType);
22270         }
22271     }
22272 
22273     private void setDeviceOwnerTypeLocked(ComponentName admin,
22274             @DeviceOwnerType int deviceOwnerType) {
22275         String packageName = admin.getPackageName();
22276         boolean isAdminTestOnly;
22277 
22278         verifyDeviceOwnerTypePreconditionsLocked(admin);
22279 
22280         isAdminTestOnly = isAdminTestOnlyLocked(admin, mOwners.getDeviceOwnerUserId());
22281         Preconditions.checkState(isAdminTestOnly
22282                         || !mOwners.isDeviceOwnerTypeSetForDeviceOwner(packageName),
22283                 "Test only admins can only set the device owner type more than once");
22284 
22285         mOwners.setDeviceOwnerType(packageName, deviceOwnerType, isAdminTestOnly);
22286         setGlobalSettingDeviceOwnerType(deviceOwnerType);
22287     }
22288 
22289     // TODO(b/237065504): Allow mainline modules to get the device owner type. This is a workaround
22290     // to get the device owner type in PermissionController. See HibernationPolicy.kt.
22291     private void setGlobalSettingDeviceOwnerType(int deviceOwnerType) {
22292         mInjector.binderWithCleanCallingIdentity(
22293                 () -> mInjector.settingsGlobalPutInt("device_owner_type", deviceOwnerType));
22294     }
22295 
22296     @Override
22297     @DeviceOwnerType
22298     public int getDeviceOwnerType(@NonNull ComponentName admin) {
22299         synchronized (getLockObject()) {
22300             verifyDeviceOwnerTypePreconditionsLocked(admin);
22301             return getDeviceOwnerTypeLocked(admin.getPackageName());
22302         }
22303     }
22304 
22305     @DeviceOwnerType
22306     private int getDeviceOwnerTypeLocked(String packageName) {
22307         return mOwners.getDeviceOwnerType(packageName);
22308     }
22309 
22310     /**
22311      * {@code true} is returned <b>only if</b> the caller is the device owner and the device owner
22312      * type is {@link DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}. {@code false} is returned for
22313      * the case where the caller is not the device owner, there is no device owner, or the device
22314      * owner type is not {@link DevicePolicyManager#DEVICE_OWNER_TYPE_FINANCED}.
22315      */
22316     private boolean isFinancedDeviceOwner(CallerIdentity caller) {
22317         synchronized (getLockObject()) {
22318             return isDeviceOwnerLocked(caller) && getDeviceOwnerTypeLocked(
22319                     mOwners.getDeviceOwnerPackageName()) == DEVICE_OWNER_TYPE_FINANCED;
22320         }
22321     }
22322 
22323     private void verifyDeviceOwnerTypePreconditionsLocked(@NonNull ComponentName admin) {
22324         Preconditions.checkState(mOwners.hasDeviceOwner(), "there is no device owner");
22325         Preconditions.checkState(mOwners.getDeviceOwnerComponent().equals(admin),
22326                 "admin is not the device owner");
22327     }
22328 
22329     @Override
22330     public void setUsbDataSignalingEnabled(String packageName, boolean enabled) {
22331         Objects.requireNonNull(packageName, "Admin package name must be provided");
22332         final CallerIdentity caller = getCallerIdentity(packageName);
22333 
22334         if (!Flags.policyEngineMigrationV2Enabled()) {
22335             Preconditions.checkCallAuthorization(
22336                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
22337                     "USB data signaling can only be controlled by a device owner or "
22338                             + "a profile owner on an organization-owned device.");
22339             Preconditions.checkState(canUsbDataSignalingBeDisabled(),
22340                     "USB data signaling cannot be disabled.");
22341         }
22342 
22343         synchronized (getLockObject()) {
22344             if (Flags.policyEngineMigrationV2Enabled()) {
22345                 EnforcingAdmin enforcingAdmin = enforcePermissionAndGetEnforcingAdmin(
22346                         /* admin= */ null, MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
22347                         caller.getPackageName(),
22348                         caller.getUserId());
22349                 Preconditions.checkState(canUsbDataSignalingBeDisabled(),
22350                         "USB data signaling cannot be disabled.");
22351                 mDevicePolicyEngine.setGlobalPolicy(
22352                         PolicyDefinition.USB_DATA_SIGNALING,
22353                         enforcingAdmin,
22354                         new BooleanPolicyValue(enabled));
22355             } else {
22356                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
22357                 if (admin.mUsbDataSignalingEnabled != enabled) {
22358                     admin.mUsbDataSignalingEnabled = enabled;
22359                     saveSettingsLocked(caller.getUserId());
22360                     updateUsbDataSignal(mContext, isUsbDataSignalingEnabledInternalLocked());
22361                 }
22362             }
22363         }
22364         DevicePolicyEventLogger
22365                 .createEvent(DevicePolicyEnums.SET_USB_DATA_SIGNALING)
22366                 .setAdmin(packageName)
22367                 .setBoolean(enabled)
22368                 .write();
22369     }
22370 
22371     static void updateUsbDataSignal(Context context, boolean value) {
22372         if (!canUsbDataSignalingBeDisabledInternal(context)) {
22373             return;
22374         }
22375         if (!Binder.withCleanCallingIdentity(
22376                 () -> context.getSystemService(UsbManager.class).enableUsbDataSignal(value))) {
22377             Slogf.w(LOG_TAG, "Failed to set usb data signaling state");
22378         }
22379     }
22380 
22381     @Override
22382     public boolean isUsbDataSignalingEnabled(String packageName) {
22383         final CallerIdentity caller = getCallerIdentity(packageName);
22384         if (Flags.policyEngineMigrationV2Enabled()) {
22385             Boolean enabled = mDevicePolicyEngine.getResolvedPolicy(
22386                     PolicyDefinition.USB_DATA_SIGNALING,
22387                     caller.getUserId());
22388             return enabled == null || enabled;
22389         } else {
22390             synchronized (getLockObject()) {
22391                 // If the caller is an admin, return the policy set by itself. Otherwise
22392                 // return the device-wide policy.
22393                 if (isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(
22394                         caller)) {
22395                     return getProfileOwnerOrDeviceOwnerLocked(
22396                             caller.getUserId()).mUsbDataSignalingEnabled;
22397                 } else {
22398                     return isUsbDataSignalingEnabledInternalLocked();
22399                 }
22400             }
22401         }
22402     }
22403 
22404     private boolean isUsbDataSignalingEnabledInternalLocked() {
22405         ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
22406         return admin == null || admin.mUsbDataSignalingEnabled;
22407     }
22408 
22409     @Override
22410     public boolean canUsbDataSignalingBeDisabled() {
22411         return canUsbDataSignalingBeDisabledInternal(mContext);
22412     }
22413 
22414     private static boolean canUsbDataSignalingBeDisabledInternal(Context context) {
22415         return Binder.withCleanCallingIdentity(() ->
22416             context.getSystemService(UsbManager.class) != null
22417                   && context.getSystemService(UsbManager.class).getUsbHalVersion()
22418                   >= UsbManager.USB_HAL_V1_3
22419         );
22420     }
22421 
22422     private void notifyMinimumRequiredWifiSecurityLevelChanged(int level) {
22423         mInjector.binderWithCleanCallingIdentity(
22424                 () -> mInjector.getWifiManager()
22425                         .notifyMinimumRequiredWifiSecurityLevelChanged(level));
22426     }
22427 
22428     private void notifyWifiSsidPolicyChanged(WifiSsidPolicy policy) {
22429         if (policy == null) {
22430             // If policy doesn't limit SSIDs, no need to disconnect anything.
22431             return;
22432         }
22433         mInjector.binderWithCleanCallingIdentity(
22434                 () -> mInjector.getWifiManager().notifyWifiSsidPolicyChanged(policy));
22435     }
22436 
22437     @Override
22438     public void setMinimumRequiredWifiSecurityLevel(String callerPackageName, int level) {
22439         CallerIdentity caller;
22440         if (isPermissionCheckFlagEnabled()) {
22441             caller = getCallerIdentity(callerPackageName);
22442         } else {
22443             caller = getCallerIdentity();
22444             Preconditions.checkCallAuthorization(
22445                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
22446                     "Wi-Fi minimum security level can only be controlled by a device owner or "
22447                             + "a profile owner on an organization-owned device.");
22448         }
22449 
22450         boolean valueChanged = false;
22451         synchronized (getLockObject()) {
22452             ActiveAdmin admin;
22453             if (isPermissionCheckFlagEnabled()) {
22454                 admin = enforcePermissionAndGetEnforcingAdmin(/* admin= */ null,
22455                         MANAGE_DEVICE_POLICY_WIFI, caller.getPackageName(), caller.getUserId())
22456                         .getActiveAdmin();
22457             } else {
22458                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
22459             }
22460             if (admin.mWifiMinimumSecurityLevel != level) {
22461                 admin.mWifiMinimumSecurityLevel = level;
22462                 saveSettingsLocked(caller.getUserId());
22463                 valueChanged = true;
22464             }
22465         }
22466         if (valueChanged) notifyMinimumRequiredWifiSecurityLevelChanged(level);
22467     }
22468 
22469     @Override
22470     public int getMinimumRequiredWifiSecurityLevel() {
22471         synchronized (getLockObject()) {
22472             ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
22473             return (admin == null) ? DevicePolicyManager.WIFI_SECURITY_OPEN
22474                     : admin.mWifiMinimumSecurityLevel;
22475         }
22476     }
22477 
22478     @Override
22479     public WifiSsidPolicy getWifiSsidPolicy(String callerPackageName) {
22480         final CallerIdentity caller = getCallerIdentity();
22481         if (isPermissionCheckFlagEnabled()) {
22482             enforcePermission(MANAGE_DEVICE_POLICY_WIFI, callerPackageName,
22483                     caller.getUserId());
22484         } else {
22485             Preconditions.checkCallAuthorization(
22486                     isDefaultDeviceOwner(caller)
22487                             || isProfileOwnerOfOrganizationOwnedDevice(caller)
22488                             || canQueryAdminPolicy(caller),
22489                     "SSID policy can only be retrieved by a device owner or "
22490                             + "a profile owner on an organization-owned device or "
22491                             + "an app with the QUERY_ADMIN_POLICY permission.");
22492         }
22493         synchronized (getLockObject()) {
22494             ActiveAdmin admin;
22495             admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceOrSystemPermissionBasedAdminLocked();
22496             return admin != null ? admin.mWifiSsidPolicy : null;
22497         }
22498     }
22499 
22500     @Override
22501     public boolean isDevicePotentiallyStolen(String callerPackageName) {
22502         final CallerIdentity caller = getCallerIdentity(callerPackageName);
22503         if (!android.app.admin.flags.Flags.deviceTheftImplEnabled()) {
22504             return false;
22505         }
22506         enforcePermission(QUERY_DEVICE_STOLEN_STATE, caller.getPackageName(),
22507                 caller.getUserId());
22508 
22509         return mInjector.binderWithCleanCallingIdentity(() ->
22510                 0 != (mLockPatternUtils.getStrongAuthForUser(caller.getUserId())
22511                         & SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST));
22512     }
22513 
22514     @Override
22515     public void setWifiSsidPolicy(String callerPackageName, WifiSsidPolicy policy) {
22516         CallerIdentity caller;
22517 
22518         if (isPermissionCheckFlagEnabled()) {
22519             caller = getCallerIdentity(callerPackageName);
22520         } else {
22521             caller = getCallerIdentity();
22522             Preconditions.checkCallAuthorization(
22523                     isDefaultDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
22524                     "SSID denylist can only be controlled by a device owner or "
22525                             + "a profile owner on an organization-owned device.");
22526         }
22527 
22528         boolean changed = false;
22529         synchronized (getLockObject()) {
22530             ActiveAdmin admin;
22531             if (isPermissionCheckFlagEnabled()) {
22532                 admin = enforcePermissionAndGetEnforcingAdmin(
22533                         /* admin= */ null, MANAGE_DEVICE_POLICY_WIFI,
22534                         caller.getPackageName(),
22535                         caller.getUserId()).getActiveAdmin();
22536             } else {
22537                 admin = getProfileOwnerOrDeviceOwnerLocked(caller.getUserId());
22538             }
22539             if (!Objects.equals(policy, admin.mWifiSsidPolicy)) {
22540                 admin.mWifiSsidPolicy = policy;
22541                 changed = true;
22542             }
22543             if (changed) saveSettingsLocked(caller.getUserId());
22544         }
22545         if (changed) {
22546             notifyWifiSsidPolicyChanged(policy);
22547         }
22548     }
22549 
22550     @Override
22551     public void setDrawables(@NonNull List<DevicePolicyDrawableResource> drawables) {
22552         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22553                 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
22554 
22555         Objects.requireNonNull(drawables, "drawables must be provided.");
22556 
22557         mInjector.binderWithCleanCallingIdentity(() -> {
22558             if (mDeviceManagementResourcesProvider.updateDrawables(drawables)) {
22559                 sendDrawableUpdatedBroadcast(
22560                         drawables.stream().map(s -> s.getDrawableId()).collect(
22561                                 Collectors.toList()));
22562             }
22563         });
22564     }
22565 
22566     @Override
22567     public void resetDrawables(@NonNull List<String> drawableIds) {
22568         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22569                 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
22570 
22571         Objects.requireNonNull(drawableIds, "drawableIds must be provided.");
22572 
22573         mInjector.binderWithCleanCallingIdentity(() -> {
22574             if (mDeviceManagementResourcesProvider.removeDrawables(drawableIds)) {
22575                 sendDrawableUpdatedBroadcast(drawableIds);
22576             }
22577         });
22578     }
22579 
22580     @Override
22581     public ParcelableResource getDrawable(
22582             String drawableId, String drawableStyle, String drawableSource) {
22583         return mInjector.binderWithCleanCallingIdentity(() ->
22584                 mDeviceManagementResourcesProvider.getDrawable(
22585                         drawableId, drawableStyle, drawableSource));
22586     }
22587 
22588     private void sendDrawableUpdatedBroadcast(List<String> drawableIds) {
22589         sendResourceUpdatedBroadcast(EXTRA_RESOURCE_TYPE_DRAWABLE, drawableIds);
22590     }
22591 
22592     @Override
22593     public void setStrings(@NonNull List<DevicePolicyStringResource> strings) {
22594         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22595                 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
22596 
22597         Objects.requireNonNull(strings, "strings must be provided.");
22598 
22599         mInjector.binderWithCleanCallingIdentity(() -> {
22600             if (mDeviceManagementResourcesProvider.updateStrings(strings)) {
22601                 sendStringsUpdatedBroadcast(
22602                         strings.stream().map(s -> s.getStringId()).collect(Collectors.toList()));
22603             }
22604         });
22605     }
22606 
22607     @Override
22608     public void resetStrings(@NonNull List<String> stringIds) {
22609         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22610                 android.Manifest.permission.UPDATE_DEVICE_MANAGEMENT_RESOURCES));
22611 
22612         mInjector.binderWithCleanCallingIdentity(() -> {
22613             if (mDeviceManagementResourcesProvider.removeStrings(stringIds)) {
22614                 sendStringsUpdatedBroadcast(stringIds);
22615             }
22616         });
22617     }
22618 
22619     @Override
22620     public ParcelableResource getString(String stringId) {
22621         return mInjector.binderWithCleanCallingIdentity(() ->
22622                 mDeviceManagementResourcesProvider.getString(stringId));
22623     }
22624 
22625     private void sendStringsUpdatedBroadcast(List<String> stringIds) {
22626         sendResourceUpdatedBroadcast(EXTRA_RESOURCE_TYPE_STRING, stringIds);
22627     }
22628 
22629     private void sendResourceUpdatedBroadcast(int resourceType, List<String> resourceIds) {
22630         final Intent intent = new Intent(ACTION_DEVICE_POLICY_RESOURCE_UPDATED);
22631         intent.putExtra(EXTRA_RESOURCE_IDS, resourceIds.toArray(String[]::new));
22632         intent.putExtra(EXTRA_RESOURCE_TYPE, resourceType);
22633         intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
22634         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
22635 
22636         List<UserInfo> users = mUserManager.getAliveUsers();
22637         for (int i = 0; i < users.size(); i++) {
22638             UserHandle user = users.get(i).getUserHandle();
22639             mContext.sendBroadcastAsUser(intent, user);
22640         }
22641     }
22642 
22643     private String getUpdatableString(
22644             String updatableStringId, int defaultStringId, Object... formatArgs) {
22645         ParcelableResource resource = mDeviceManagementResourcesProvider.getString(
22646                 updatableStringId);
22647         if (resource == null) {
22648             return ParcelableResource.loadDefaultString(() ->
22649                     mContext.getString(defaultStringId, formatArgs));
22650         }
22651         return resource.getString(
22652                 mContext, () -> mContext.getString(defaultStringId, formatArgs), formatArgs);
22653     }
22654 
22655     public boolean isDpcDownloaded() {
22656         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22657                 MANAGE_PROFILE_AND_DEVICE_OWNERS));
22658 
22659         ContentResolver cr = mContext.getContentResolver();
22660 
22661         return mInjector.binderWithCleanCallingIdentity(() -> Settings.Secure.getIntForUser(
22662                 cr, MANAGED_PROVISIONING_DPC_DOWNLOADED,
22663                 /* def= */ 0, /* userHandle= */ cr.getUserId())
22664                 == 1);
22665     }
22666 
22667     public void setDpcDownloaded(boolean downloaded) {
22668         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22669                 MANAGE_PROFILE_AND_DEVICE_OWNERS));
22670 
22671         int setTo = downloaded ? 1 : 0;
22672 
22673         mInjector.binderWithCleanCallingIdentity(() -> Settings.Secure.putInt(
22674                 mContext.getContentResolver(), MANAGED_PROVISIONING_DPC_DOWNLOADED, setTo));
22675     }
22676 
22677     @Override
22678     public void resetShouldAllowBypassingDevicePolicyManagementRoleQualificationState() {
22679         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22680                 android.Manifest.permission.MANAGE_ROLE_HOLDERS));
22681         setBypassDevicePolicyManagementRoleQualificationStateInternal(
22682                 /* currentRoleHolder= */ null, /* allowBypass= */ false);
22683     }
22684 
22685     @Override
22686     public boolean shouldAllowBypassingDevicePolicyManagementRoleQualification() {
22687         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22688                 android.Manifest.permission.MANAGE_ROLE_HOLDERS));
22689         return mInjector.binderWithCleanCallingIdentity(() -> {
22690             if (getUserData(
22691                     UserHandle.USER_SYSTEM).mBypassDevicePolicyManagementRoleQualifications) {
22692                 return true;
22693             }
22694             return shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal();
22695         });
22696     }
22697 
22698     private boolean shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal() {
22699         if (nonTestNonPrecreatedUsersExist()) {
22700             return false;
22701         }
22702 
22703 
22704         return !hasIncompatibleAccountsOnAnyUser();
22705     }
22706 
22707     private boolean hasAccountsOnAnyUser() {
22708         long callingIdentity = Binder.clearCallingIdentity();
22709         try {
22710             for (UserInfo user : mUserManagerInternal.getUsers(/* excludeDying= */ true)) {
22711                 AccountManager am = mContext.createContextAsUser(
22712                                 UserHandle.of(user.id), /* flags= */ 0)
22713                         .getSystemService(AccountManager.class);
22714                 Account[] accounts = am.getAccounts();
22715                 if (accounts.length != 0) {
22716                     return true;
22717                 }
22718             }
22719 
22720             return false;
22721         } finally {
22722             Binder.restoreCallingIdentity(callingIdentity);
22723         }
22724     }
22725 
22726     private void setBypassDevicePolicyManagementRoleQualificationStateInternal(
22727             String currentRoleHolder, boolean allowBypass) {
22728         boolean stateChanged = false;
22729         DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
22730         if (policy.mBypassDevicePolicyManagementRoleQualifications != allowBypass) {
22731             policy.mBypassDevicePolicyManagementRoleQualifications = allowBypass;
22732             stateChanged = true;
22733         }
22734         if (!Objects.equals(currentRoleHolder, policy.mCurrentRoleHolder)) {
22735             policy.mCurrentRoleHolder = currentRoleHolder;
22736             stateChanged = true;
22737         }
22738         if (stateChanged) {
22739             synchronized (getLockObject()) {
22740                 saveSettingsLocked(UserHandle.USER_SYSTEM);
22741             }
22742         }
22743     }
22744 
22745     private final class DevicePolicyManagementRoleObserver implements OnRoleHoldersChangedListener {
22746         private RoleManager mRm;
22747         private final Executor mExecutor;
22748         private final Context mContext;
22749 
22750         DevicePolicyManagementRoleObserver(@NonNull Context context) {
22751             mContext = context;
22752             mExecutor = mContext.getMainExecutor();
22753             mRm = mContext.getSystemService(RoleManager.class);
22754         }
22755 
22756         public void register() {
22757             mRm.addOnRoleHoldersChangedListenerAsUser(mExecutor, this, UserHandle.ALL);
22758         }
22759 
22760         @Override
22761         public void onRoleHoldersChanged(@NonNull String roleName, @NonNull UserHandle user) {
22762             mDevicePolicyEngine.handleRoleChanged(roleName, user.getIdentifier());
22763             if (RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT.equals(roleName)) {
22764                 handleDevicePolicyManagementRoleChange(user);
22765                 return;
22766             }
22767             if (RoleManager.ROLE_FINANCED_DEVICE_KIOSK.equals(roleName)) {
22768                 handleFinancedDeviceKioskRoleChange();
22769                 return;
22770             }
22771         }
22772 
22773         private void handleDevicePolicyManagementRoleChange(UserHandle user) {
22774             String newRoleHolder = getDeviceManagementRoleHolder(user);
22775             if (isDefaultRoleHolder(newRoleHolder)) {
22776                 Slogf.i(LOG_TAG,
22777                         "onRoleHoldersChanged: Default role holder is set, returning early");
22778                 return;
22779             }
22780             if (newRoleHolder == null) {
22781                 Slogf.i(LOG_TAG,
22782                         "onRoleHoldersChanged: New role holder is null, returning early");
22783                 return;
22784             }
22785             if (shouldAllowBypassingDevicePolicyManagementRoleQualificationInternal()) {
22786                 Slogf.w(LOG_TAG,
22787                         "onRoleHoldersChanged: Updating current role holder to " + newRoleHolder);
22788                 setBypassDevicePolicyManagementRoleQualificationStateInternal(
22789                         newRoleHolder, /* allowBypass= */ true);
22790                 return;
22791             }
22792             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
22793             if (!newRoleHolder.equals(policy.mCurrentRoleHolder)) {
22794                 Slogf.w(LOG_TAG,
22795                         "onRoleHoldersChanged: You can't set a different role holder, role "
22796                                 + "is getting revoked from " + newRoleHolder);
22797                 setBypassDevicePolicyManagementRoleQualificationStateInternal(
22798                         /* currentRoleHolder= */ null, /* allowBypass= */ false);
22799                 mRm.removeRoleHolderAsUser(
22800                         RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT,
22801                         newRoleHolder,
22802                         /* flags= */ 0,
22803                         user,
22804                         mExecutor,
22805                         successful -> {});
22806             }
22807         }
22808 
22809         private void handleFinancedDeviceKioskRoleChange() {
22810             Slog.i(LOG_TAG, "Handling action " + ACTION_DEVICE_FINANCING_STATE_CHANGED);
22811             Intent intent = new Intent(ACTION_DEVICE_FINANCING_STATE_CHANGED);
22812             mInjector.binderWithCleanCallingIdentity(() -> {
22813                 for (UserInfo userInfo : mUserManager.getUsers()) {
22814                     UserHandle user = userInfo.getUserHandle();
22815                     broadcastExplicitIntentToRoleHolder(
22816                             intent, RoleManager.ROLE_SYSTEM_SUPERVISION, user);
22817                     broadcastExplicitIntentToRoleHolder(
22818                             intent, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, user);
22819                     ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(user.getIdentifier());
22820                     if (admin == null) {
22821                         continue;
22822                     }
22823                     if (!isProfileOwnerOfOrganizationOwnedDevice(
22824                             admin.info.getComponent(), user.getIdentifier())
22825                             && !isDeviceOwner(admin)
22826                             && !(isProfileOwner(admin.info.getComponent(), user.getIdentifier())
22827                             && admin.getUserHandle().isSystem())) {
22828                         continue;
22829                     }
22830                     // Don't send the broadcast twice if the DPC is the same package as the
22831                     // DMRH
22832                     if (admin.info.getPackageName().equals(getDeviceManagementRoleHolder(user))) {
22833                         continue;
22834                     }
22835                     broadcastExplicitIntentToPackage(
22836                             intent, admin.info.getPackageName(), admin.getUserHandle());
22837                 }
22838             });
22839         }
22840 
22841         private String getDeviceManagementRoleHolder(UserHandle user) {
22842             return DevicePolicyManagerService.this.getRoleHolderPackageNameOnUser(
22843                     mContext, RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, user);
22844         }
22845 
22846         private boolean isDefaultRoleHolder(String packageName) {
22847             String defaultRoleHolder = getDefaultRoleHolderPackageName();
22848             if (packageName == null || defaultRoleHolder == null) {
22849                 return false;
22850             }
22851             if (!defaultRoleHolder.equals(packageName)) {
22852                 return false;
22853             }
22854             return hasSigningCertificate(
22855                     packageName, getDefaultRoleHolderPackageSignature());
22856         }
22857 
22858         private boolean hasSigningCertificate(String packageName, String  certificateString) {
22859             if (packageName == null || certificateString == null) {
22860                 return false;
22861             }
22862             byte[] certificate;
22863             try {
22864                 certificate = new Signature(certificateString).toByteArray();
22865             } catch (IllegalArgumentException e) {
22866                 Slogf.w(LOG_TAG, "Cannot parse signing certificate: " + certificateString, e);
22867                 return false;
22868             }
22869             PackageManager pm = mInjector.getPackageManager();
22870             return pm.hasSigningCertificate(
22871                     packageName, certificate, PackageManager.CERT_INPUT_SHA256);
22872         }
22873 
22874         private String getDefaultRoleHolderPackageName() {
22875             String[] info = getDefaultRoleHolderPackageNameAndSignature();
22876             if (info == null) {
22877                 return null;
22878             }
22879             return info[0];
22880         }
22881 
22882         private String getDefaultRoleHolderPackageSignature() {
22883             String[] info = getDefaultRoleHolderPackageNameAndSignature();
22884             if (info == null || info.length < 2) {
22885                 return null;
22886             }
22887             return info[1];
22888         }
22889 
22890         private String[] getDefaultRoleHolderPackageNameAndSignature() {
22891             String packageNameAndSignature = mContext.getString(
22892                     R.string.config_devicePolicyManagement);
22893             if (TextUtils.isEmpty(packageNameAndSignature)) {
22894                 return null;
22895             }
22896             if (packageNameAndSignature.contains(":")) {
22897                 return packageNameAndSignature.split(":");
22898             }
22899             return new String[]{packageNameAndSignature};
22900         }
22901     }
22902 
22903     private void broadcastExplicitIntentToRoleHolder(
22904             Intent intent, String role, UserHandle userHandle) {
22905         String packageName = getRoleHolderPackageNameOnUser(mContext, role, userHandle);
22906         if (packageName == null) {
22907             return;
22908         }
22909         broadcastExplicitIntentToPackage(intent, packageName, userHandle);
22910     }
22911 
22912     private void broadcastExplicitIntentToPackage(
22913             Intent intent, String packageName, UserHandle userHandle) {
22914         int userId = userHandle.getIdentifier();
22915         if (packageName == null) {
22916             return;
22917         }
22918         Intent packageIntent = new Intent(intent)
22919                 .setPackage(packageName);
22920         List<ResolveInfo> receivers = mContext.getPackageManager().queryBroadcastReceiversAsUser(
22921                 packageIntent,
22922                 PackageManager.ResolveInfoFlags.of(PackageManager.GET_RECEIVERS),
22923                 userId);
22924         if (receivers.isEmpty()) {
22925             Slog.i(LOG_TAG, "Found no receivers to handle intent " + intent
22926                     + " in package " + packageName);
22927             return;
22928         }
22929         for (ResolveInfo receiver : receivers) {
22930             Intent componentIntent = new Intent(packageIntent)
22931                     .setComponent(receiver.getComponentInfo().getComponentName())
22932                     .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
22933             mContext.sendBroadcastAsUser(componentIntent, userHandle);
22934         }
22935     }
22936 
22937     @Override
22938     public List<UserHandle> getPolicyManagedProfiles(@NonNull UserHandle user) {
22939         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
22940                 MANAGE_PROFILE_AND_DEVICE_OWNERS));
22941         int userId = user.getIdentifier();
22942         return mInjector.binderWithCleanCallingIdentity(() -> {
22943             List<UserInfo> userProfiles = mUserManager.getProfiles(userId);
22944             List<UserHandle> result = new ArrayList<>();
22945             for (int i = 0; i < userProfiles.size(); i++) {
22946                 UserInfo userInfo = userProfiles.get(i);
22947                 if (userInfo.isManagedProfile() && hasProfileOwner(userInfo.id)) {
22948                     result.add(new UserHandle(userInfo.id));
22949                 }
22950             }
22951             return result;
22952         });
22953     }
22954 
22955     // DPC types
22956     private static final int NOT_A_DPC = -1;
22957     private static final int DEFAULT_DEVICE_OWNER = 0;
22958     private static final int FINANCED_DEVICE_OWNER = 1;
22959     private static final int PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE = 2;
22960     private static final int PROFILE_OWNER_ON_USER_0 = 3;
22961     private static final int PROFILE_OWNER = 4;
22962     private static final int PROFILE_OWNER_ON_USER = 5;
22963     private static final int AFFILIATED_PROFILE_OWNER_ON_USER = 6;
22964     // DPC types
22965     @IntDef(value = {
22966             NOT_A_DPC,
22967             DEFAULT_DEVICE_OWNER,
22968             FINANCED_DEVICE_OWNER,
22969             PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE,
22970             PROFILE_OWNER_ON_USER_0,
22971             PROFILE_OWNER,
22972             PROFILE_OWNER_ON_USER,
22973             AFFILIATED_PROFILE_OWNER_ON_USER
22974     })
22975     private @interface DpcType {}
22976 
22977     // Permissions of existing DPC types.
22978     private static final List<String> DEFAULT_DEVICE_OWNER_PERMISSIONS = List.of(
22979             MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
22980             MANAGE_DEVICE_POLICY_ACROSS_USERS,
22981             MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL,
22982             MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
22983             MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
22984             MANAGE_DEVICE_POLICY_APPS_CONTROL,
22985             MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
22986             MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
22987             MANAGE_DEVICE_POLICY_AUTOFILL,
22988             MANAGE_DEVICE_POLICY_BLUETOOTH,
22989             MANAGE_DEVICE_POLICY_CALLS,
22990             MANAGE_DEVICE_POLICY_CAMERA,
22991             MANAGE_DEVICE_POLICY_CERTIFICATES,
22992             MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
22993             MANAGE_DEVICE_POLICY_CONTENT_PROTECTION,
22994             MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
22995             MANAGE_DEVICE_POLICY_DEFAULT_SMS,
22996             MANAGE_DEVICE_POLICY_DISPLAY,
22997             MANAGE_DEVICE_POLICY_FACTORY_RESET,
22998             MANAGE_DEVICE_POLICY_FUN,
22999             MANAGE_DEVICE_POLICY_INPUT_METHODS,
23000             MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
23001             MANAGE_DEVICE_POLICY_KEYGUARD,
23002             MANAGE_DEVICE_POLICY_LOCALE,
23003             MANAGE_DEVICE_POLICY_LOCATION,
23004             MANAGE_DEVICE_POLICY_LOCK,
23005             MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
23006             MANAGE_DEVICE_POLICY_LOCK_TASK,
23007             MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS,
23008             MANAGE_DEVICE_POLICY_MICROPHONE,
23009             MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
23010             MANAGE_DEVICE_POLICY_MODIFY_USERS,
23011             MANAGE_DEVICE_POLICY_MTE,
23012             MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
23013             MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
23014             MANAGE_DEVICE_POLICY_PACKAGE_STATE,
23015             MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
23016             MANAGE_DEVICE_POLICY_PRINTING,
23017             MANAGE_DEVICE_POLICY_PROFILES,
23018             MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
23019             MANAGE_DEVICE_POLICY_RESET_PASSWORD,
23020             MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
23021             MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
23022             MANAGE_DEVICE_POLICY_SAFE_BOOT,
23023             MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
23024             MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
23025             MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
23026             MANAGE_DEVICE_POLICY_SMS,
23027             MANAGE_DEVICE_POLICY_STATUS_BAR,
23028             MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
23029             MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
23030             MANAGE_DEVICE_POLICY_SYSTEM_UPDATES,
23031             MANAGE_DEVICE_POLICY_TIME,
23032             MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
23033             MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
23034             MANAGE_DEVICE_POLICY_VPN,
23035             MANAGE_DEVICE_POLICY_WALLPAPER,
23036             MANAGE_DEVICE_POLICY_WIFI,
23037             MANAGE_DEVICE_POLICY_WINDOWS,
23038             MANAGE_DEVICE_POLICY_WIPE_DATA,
23039             SET_TIME,
23040             SET_TIME_ZONE,
23041             MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES
23042     );
23043     private static final List<String> FINANCED_DEVICE_OWNER_PERMISSIONS = List.of(
23044             MANAGE_DEVICE_POLICY_ACROSS_USERS,
23045             MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL,
23046             MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
23047             MANAGE_DEVICE_POLICY_APPS_CONTROL,
23048             MANAGE_DEVICE_POLICY_CALLS,
23049             MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
23050             MANAGE_DEVICE_POLICY_FACTORY_RESET,
23051             MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
23052             MANAGE_DEVICE_POLICY_KEYGUARD,
23053             MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
23054             MANAGE_DEVICE_POLICY_LOCK_TASK,
23055             MANAGE_DEVICE_POLICY_MODIFY_USERS,
23056             MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
23057             MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
23058             MANAGE_DEVICE_POLICY_SAFE_BOOT,
23059             MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
23060             MANAGE_DEVICE_POLICY_TIME,
23061             MANAGE_DEVICE_POLICY_WIPE_DATA
23062     );
23063 
23064     /**
23065      * All the permissions granted to a profile owner.
23066      */
23067     private static final List<String> PROFILE_OWNER_PERMISSIONS  =
23068             List.of(
23069                     MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
23070                     MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL,
23071                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
23072                     MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
23073                     MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
23074                     MANAGE_DEVICE_POLICY_AUTOFILL,
23075                     MANAGE_DEVICE_POLICY_BLUETOOTH,
23076                     MANAGE_DEVICE_POLICY_CALLS,
23077                     MANAGE_DEVICE_POLICY_CAMERA,
23078                     MANAGE_DEVICE_POLICY_CERTIFICATES,
23079                     MANAGE_DEVICE_POLICY_CONTENT_PROTECTION,
23080                     MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
23081                     MANAGE_DEVICE_POLICY_DISPLAY,
23082                     MANAGE_DEVICE_POLICY_FACTORY_RESET,
23083                     MANAGE_DEVICE_POLICY_INPUT_METHODS,
23084                     MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
23085                     MANAGE_DEVICE_POLICY_KEYGUARD,
23086                     MANAGE_DEVICE_POLICY_LOCALE,
23087                     MANAGE_DEVICE_POLICY_LOCATION,
23088                     MANAGE_DEVICE_POLICY_LOCK,
23089                     MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
23090                     MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS,
23091                     MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
23092                     MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
23093                     MANAGE_DEVICE_POLICY_PACKAGE_STATE,
23094                     MANAGE_DEVICE_POLICY_PRINTING,
23095                     MANAGE_DEVICE_POLICY_PROFILES,
23096                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
23097                     MANAGE_DEVICE_POLICY_RESET_PASSWORD,
23098                     MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
23099                     MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
23100                     MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
23101                     MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
23102                     MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
23103                     MANAGE_DEVICE_POLICY_TIME,
23104                     MANAGE_DEVICE_POLICY_VPN,
23105                     MANAGE_DEVICE_POLICY_WIPE_DATA,
23106                     MANAGE_DEVICE_POLICY_QUERY_SYSTEM_UPDATES
23107             );
23108 
23109     /**
23110      * All the additional permissions granted to an organisation owned profile owner.
23111      */
23112     private static final List<String>
23113             ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS =
23114             List.of(
23115                     MANAGE_DEVICE_POLICY_ACROSS_USERS,
23116                     MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
23117                     MANAGE_DEVICE_POLICY_APPS_CONTROL,
23118                     MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
23119                     MANAGE_DEVICE_POLICY_DEFAULT_SMS,
23120                     MANAGE_DEVICE_POLICY_LOCALE,
23121                     MANAGE_DEVICE_POLICY_MICROPHONE,
23122                     MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
23123                     MANAGE_DEVICE_POLICY_MTE,
23124                     MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
23125                     MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
23126                     MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
23127                     MANAGE_DEVICE_POLICY_SAFE_BOOT,
23128                     MANAGE_DEVICE_POLICY_SECURITY_LOGGING,
23129                     MANAGE_DEVICE_POLICY_SMS,
23130                     MANAGE_DEVICE_POLICY_SYSTEM_UPDATES,
23131                     MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING,
23132                     MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
23133                     MANAGE_DEVICE_POLICY_WIFI,
23134                     SET_TIME,
23135                     SET_TIME_ZONE
23136             );
23137 
23138     /**
23139      * All the additional permissions granted to a Profile Owner on user 0.
23140      */
23141     private static final List<String> ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS =
23142             List.of(
23143                     MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
23144                     MANAGE_DEVICE_POLICY_DISPLAY,
23145                     MANAGE_DEVICE_POLICY_FUN,
23146                     MANAGE_DEVICE_POLICY_LOCK_TASK,
23147                     MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
23148                     MANAGE_DEVICE_POLICY_MODIFY_USERS,
23149                     MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
23150                     MANAGE_DEVICE_POLICY_PRINTING,
23151                     MANAGE_DEVICE_POLICY_PROFILES,
23152                     MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
23153                     MANAGE_DEVICE_POLICY_SAFE_BOOT,
23154                     MANAGE_DEVICE_POLICY_SMS,
23155                     MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
23156                     MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
23157                     MANAGE_DEVICE_POLICY_WINDOWS,
23158                     SET_TIME,
23159                     SET_TIME_ZONE
23160             );
23161 
23162     /**
23163      * All the additional permissions granted to a Profile Owner on an unaffiliated user.
23164      */
23165     private static final List<String> ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS =
23166             List.of(
23167                     MANAGE_DEVICE_POLICY_LOCK_TASK
23168             );
23169 
23170     /**
23171      * All the additional permissions granted to a Profile Owner on an affiliated user.
23172      */
23173     private static final List<String> ADDITIONAL_AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS =
23174             List.of(
23175                     MANAGE_DEVICE_POLICY_STATUS_BAR
23176             );
23177 
23178     /**
23179      * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
23180      * {@link ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS}.
23181      */
23182     private static final List<String> PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS =
23183             new ArrayList();
23184 
23185     /**
23186      * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
23187      * {@link ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS}.
23188      */
23189     private static final List<String> PROFILE_OWNER_ON_USER_0_PERMISSIONS  =
23190             new ArrayList();
23191 
23192     /**
23193      * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
23194      * {@link ADDITIONAL_AFFILIATED_PROFIL_OWNER_ON_USER_PERMISSIONS}.
23195      */
23196     private static final List<String> AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS =
23197             new ArrayList();
23198 
23199     /**
23200      * Combination of {@link PROFILE_OWNER_PERMISSIONS} and
23201      * {@link ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS}.
23202      */
23203     private static final List<String> PROFILE_OWNER_ON_USER_PERMISSIONS =
23204             new ArrayList();
23205 
23206 
23207     private static final HashMap<Integer, List<String>> DPC_PERMISSIONS = new HashMap<>();
23208     {
23209         // Organisation owned profile owners have all the permission of a profile owner plus
23210         // some extra permissions.
23211         PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
23212         PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS.addAll(
23213                 ADDITIONAL_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS);
23214         // Profile owners on user 0 have all the permission of a profile owner plus
23215         // some extra permissions.
23216         PROFILE_OWNER_ON_USER_0_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
23217         PROFILE_OWNER_ON_USER_0_PERMISSIONS.addAll(ADDITIONAL_PROFILE_OWNER_ON_USER_0_PERMISSIONS);
23218         // Profile owners on users have all the permission of a profile owner plus
23219         // some extra permissions.
23220         PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(PROFILE_OWNER_PERMISSIONS);
23221         PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(
23222                 ADDITIONAL_PROFILE_OWNER_ON_USER_PERMISSIONS);
23223         // Profile owners on affiliated users have all the permission of a profile owner on a user
23224         // plus some extra permissions.
23225         AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(PROFILE_OWNER_ON_USER_PERMISSIONS);
23226         AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS.addAll(
23227                 ADDITIONAL_AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS);
23228 
23229         DPC_PERMISSIONS.put(DEFAULT_DEVICE_OWNER, DEFAULT_DEVICE_OWNER_PERMISSIONS);
23230         DPC_PERMISSIONS.put(FINANCED_DEVICE_OWNER, FINANCED_DEVICE_OWNER_PERMISSIONS);
23231         DPC_PERMISSIONS.put(PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE,
23232                 PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE_PERMISSIONS);
23233         DPC_PERMISSIONS.put(PROFILE_OWNER_ON_USER_0, PROFILE_OWNER_ON_USER_0_PERMISSIONS);
23234         DPC_PERMISSIONS.put(PROFILE_OWNER, PROFILE_OWNER_PERMISSIONS);
23235         DPC_PERMISSIONS.put(PROFILE_OWNER_ON_USER, PROFILE_OWNER_ON_USER_PERMISSIONS);
23236         DPC_PERMISSIONS.put(AFFILIATED_PROFILE_OWNER_ON_USER,
23237                 AFFILIATED_PROFILE_OWNER_ON_USER_PERMISSIONS);
23238     }
23239     //Map of Permission to Delegate Scope.
23240     private static final HashMap<String, String> DELEGATE_SCOPES = new HashMap<>();
23241     {
23242         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_APP_RESTRICTIONS, DELEGATION_APP_RESTRICTIONS);
23243         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL, DELEGATION_BLOCK_UNINSTALL);
23244         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_CERTIFICATES, DELEGATION_CERT_INSTALL);
23245         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_PACKAGE_STATE, DELEGATION_PACKAGE_ACCESS);
23246         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS, DELEGATION_PERMISSION_GRANT);
23247         DELEGATE_SCOPES.put(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, DELEGATION_SECURITY_LOGGING);
23248     }
23249 
23250     private static final HashMap<String, String> CROSS_USER_PERMISSIONS =
23251             new HashMap<>();
23252     {
23253         // The permissions are all intrinsically global and therefore have no cross-user permission.
23254         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_FACTORY_RESET, null);
23255         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MTE, null);
23256         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SECURITY_LOGGING, null);
23257         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_STATUS_BAR, null);
23258         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SYSTEM_UPDATES, null);
23259         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_USB_DATA_SIGNALLING, null);
23260         CROSS_USER_PERMISSIONS.put(SET_TIME, null);
23261         CROSS_USER_PERMISSIONS.put(SET_TIME_ZONE, null);
23262 
23263         // The permissions are all critical for securing data within the current user and
23264         // therefore are protected with MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL for
23265         // cross-user calls.
23266         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_INSTALL_UNKNOWN_SOURCES,
23267                 MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);
23268         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_KEYGUARD,
23269                 MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);
23270         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK_CREDENTIALS,
23271                 MANAGE_DEVICE_POLICY_ACROSS_USERS_SECURITY_CRITICAL);
23272 
23273         // These permissions are required for securing device ownership without accessing user data
23274         // and therefore are protected with MANAGE_DEVICE_POLICY_ACROSS_USERS for cross-user calls.
23275         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_ACCOUNT_MANAGEMENT,
23276                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23277         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AIRPLANE_MODE,
23278                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23279         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_BLUETOOTH,
23280                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23281         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CALLS,
23282                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23283         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CAMERA,
23284                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23285         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DEFAULT_SMS,
23286                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23287         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_INPUT_METHODS,
23288                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23289         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MICROPHONE,
23290                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23291         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MOBILE_NETWORK,
23292                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23293         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_NEARBY_COMMUNICATION,
23294                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23295         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PHYSICAL_MEDIA,
23296                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23297         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PACKAGE_STATE,
23298                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23299         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RESTRICT_PRIVATE_DNS,
23300                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23301         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SCREEN_CAPTURE,
23302                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23303         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SMS,
23304                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23305         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SAFE_BOOT,
23306                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23307         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_TIME,
23308                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23309         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_USB_FILE_TRANSFER,
23310                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23311         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WIFI,
23312                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23313         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WIPE_DATA,
23314                 MANAGE_DEVICE_POLICY_ACROSS_USERS);
23315 
23316         // These permissions may grant access to user data and therefore must be protected with
23317         // MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL for cross-user calls.
23318         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_APPS_CONTROL,
23319                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23320         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_APP_RESTRICTIONS,
23321                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23322         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AUDIO_OUTPUT,
23323                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23324         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_AUTOFILL,
23325                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23326         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_BLOCK_UNINSTALL,
23327                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23328         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_CAMERA_TOGGLE,
23329                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23330         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_COMMON_CRITERIA_MODE,
23331                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23332         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DEBUGGING_FEATURES,
23333                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23334         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_DISPLAY,
23335                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23336         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_FUN,
23337                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23338         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCALE,
23339                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23340         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCATION,
23341                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23342         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK,
23343                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23344         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_LOCK_TASK,
23345                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23346         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MODIFY_USERS,
23347                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23348         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_MICROPHONE_TOGGLE,
23349                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23350         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_ORGANIZATION_IDENTITY,
23351                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23352         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PROFILES,
23353                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23354         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PROFILE_INTERACTION,
23355                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23356         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_PRINTING,
23357                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23358         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RESET_PASSWORD,
23359                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23360         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_RUNTIME_PERMISSIONS,
23361                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23362         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SCREEN_CONTENT,
23363                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23364         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SUPPORT_MESSAGE,
23365                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23366         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_SYSTEM_DIALOGS,
23367                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23368         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_VPN,
23369                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23370         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WALLPAPER,
23371                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23372         CROSS_USER_PERMISSIONS.put(MANAGE_DEVICE_POLICY_WINDOWS,
23373                 MANAGE_DEVICE_POLICY_ACROSS_USERS_FULL);
23374     }
23375 
23376     /**
23377      * Checks if the calling process has been granted permission to apply a device policy on a
23378      * specific user. Only one permission provided in the list needs to be granted to pass this
23379      * check.
23380      * The given permissions will be checked along with their associated cross-user permissions if
23381      * they exists and the target user is different to the calling user.
23382      * Returns an {@link EnforcingAdmin} for the caller.
23383      *
23384      * @param admin the component name of the admin.
23385      * @param callerPackageName The package name of the calling application.
23386      * @param permissions an array of permission names to be checked.
23387      * @param targetUserId The userId of the user which the caller needs permission to act on.
23388      * @throws SecurityException if the caller has not been granted the given permission,
23389      * the associated cross-user permission if the caller's user is different to the target user.
23390      */
23391     private EnforcingAdmin enforcePermissionsAndGetEnforcingAdmin(@Nullable ComponentName admin,
23392             String[] permissions, String callerPackageName, int targetUserId) {
23393         enforcePermissions(permissions, callerPackageName, targetUserId);
23394         return getEnforcingAdminForCaller(admin, callerPackageName);
23395     }
23396 
23397     /**
23398      * Checks if the calling process has been granted permission to apply a device policy on a
23399      * specific user.
23400      * The given permission will be checked along with its associated cross-user permission if it
23401      * exists and the target user is different to the calling user.
23402      * Returns an {@link EnforcingAdmin} for the caller.
23403      *
23404      * @param admin the component name of the admin.
23405      * @param callerPackageName The package name of the calling application.
23406      * @param permission The name of the permission being checked.
23407      * @param targetUserId The userId of the user which the caller needs permission to act on.
23408      * @throws SecurityException if the caller has not been granted the given permission,
23409      * the associated cross-user permission if the caller's user is different to the target user.
23410      */
23411     private EnforcingAdmin enforcePermissionAndGetEnforcingAdmin(@Nullable ComponentName admin,
23412             String permission, String callerPackageName, int targetUserId) {
23413         enforcePermission(permission, callerPackageName, targetUserId);
23414         return getEnforcingAdminForCaller(admin, callerPackageName);
23415     }
23416 
23417     /**
23418      * Checks if the calling process has been granted permission to apply a device policy on a
23419      * specific user.
23420      * The given permission will be checked along with its associated cross-user permission if it
23421      * exists and the target user is different to the calling user.
23422      * Returns an {@link EnforcingAdmin} for the caller.
23423      *
23424      * @param admin the component name of the admin.
23425      * @param callerPackageName The package name  of the calling application.
23426      * @param permission The name of the permission being checked.
23427      * @param deviceAdminPolicy The userId of the user which the caller needs permission to act on.
23428      * @throws SecurityException if the caller has not been granted the given permission,
23429      * the associated cross-user permission if the caller's user is different to the target user.
23430      */
23431     private EnforcingAdmin enforcePermissionAndGetEnforcingAdmin(@Nullable ComponentName admin,
23432             String permission, int deviceAdminPolicy, String callerPackageName, int targetUserId) {
23433         enforcePermission(permission, deviceAdminPolicy, callerPackageName, targetUserId);
23434         return getEnforcingAdminForCaller(admin, callerPackageName);
23435     }
23436 
23437     /**
23438      * Checks if the calling process has been granted permission to apply a device policy on a
23439      * specific user.  Only one permission provided in the list needs to be granted to pass this
23440      * check.
23441      * The given permissions will be checked along with their associated cross-user permissions if
23442      * they exist and the target user is different to the calling user.
23443      * Returns an {@link EnforcingAdmin} for the caller.
23444      *
23445      * @param admin the component name of the admin.
23446      * @param callerPackageName The package name of the calling application.
23447      * @param permissions The names of the permissions being checked.
23448      * @param deviceAdminPolicy The userId of the user which the caller needs permission to act on.
23449      * @throws SecurityException if the caller has not been granted the given permission,
23450      * the associated cross-user permission if the caller's user is different to the target user.
23451      */
23452     private EnforcingAdmin enforcePermissionsAndGetEnforcingAdmin(@Nullable ComponentName admin,
23453             String[] permissions, int deviceAdminPolicy, String callerPackageName,
23454             int targetUserId) {
23455         enforcePermissions(permissions, deviceAdminPolicy, callerPackageName, targetUserId);
23456         return getEnforcingAdminForCaller(admin, callerPackageName);
23457     }
23458 
23459     /**
23460      * Checks whether the calling process has been granted permission to query a device policy on
23461      * a specific user.
23462      * The given permission will be checked along with its associated cross-user permission if it
23463      * exists and the target user is different to the calling user.
23464      *
23465      * @param permission The name of the permission being checked.
23466      * @param targetUserId The userId of the user which the caller needs permission to act on.
23467      * @throws SecurityException if the caller has not been granted the given permission,
23468      * the associated cross-user permission if the caller's user is different to the target user.
23469      */
23470     private EnforcingAdmin enforceCanQueryAndGetEnforcingAdmin(@Nullable ComponentName admin,
23471             String permission, String callerPackageName, int targetUserId) {
23472         enforceCanQuery(permission, callerPackageName, targetUserId);
23473         return getEnforcingAdminForCaller(admin, callerPackageName);
23474     }
23475 
23476     /**
23477      * Checks if the calling process has been granted permission to apply a device policy.
23478      *
23479      * @param callerPackageName The package name  of the calling application.
23480      * @param permission The name of the permission being checked.
23481      * @throws SecurityException if the caller has not been granted the given permission,
23482      * the associated cross-user permission if the caller's user is different to the target user.
23483      */
23484     private void enforcePermission(String permission, String callerPackageName)
23485             throws SecurityException {
23486         if (!hasPermission(permission, callerPackageName)) {
23487             throw new SecurityException("Caller does not have the required permissions for "
23488                     + "this user. Permission required: "
23489                     + permission
23490                     + ".");
23491         }
23492     }
23493 
23494     /**
23495      * Checks if the calling process has been granted permission to apply a device policy on a
23496      * specific user. Only one permission provided in the list needs to be granted to pass this
23497      * check.
23498      * The given permissions will be checked along with their associated cross-user permissions if
23499      * they exists and the target user is different to the calling user.
23500      *
23501      * @param callerPackageName The package name  of the calling application.
23502      * @param permissions The names of the permissions being checked.
23503      * @param targetUserId The userId of the user which the caller needs permission to act on.
23504      * @throws SecurityException if the caller has not been granted the given permission,
23505      * the associated cross-user permission if the caller's user is different to the target user.
23506      */
23507     private void enforcePermission(String permission, String callerPackageName, int targetUserId)
23508             throws SecurityException {
23509         enforcePermission(permission, callerPackageName);
23510         if (targetUserId != getCallerIdentity(callerPackageName).getUserId()) {
23511             enforcePermission(CROSS_USER_PERMISSIONS.get(permission), callerPackageName);
23512         }
23513     }
23514 
23515     /**
23516      * Checks if the calling process has been granted permission to apply a device policy on a
23517      * specific user. Only one of the given permissions will be required to be held to pass this
23518      * check.
23519      * The given permissions will be checked along with their associated cross-user permissions if
23520      * they exist and the target user is different to the calling user.
23521      *
23522      * @param permissions An array of the names of the permissions being checked.
23523      * @param callerPackageName The package name  of the calling application.
23524      * @param targetUserId The userId of the user which the caller needs permission to act on.
23525      * @throws SecurityException if the caller has not been granted the given permission,
23526      * the associated cross-user permission if the caller's user is different to the target user.
23527      */
23528     private void enforcePermissions(String[] permissions, String callerPackageName,
23529             int targetUserId) throws SecurityException {
23530         String heldPermission = "";
23531         for (String permission : permissions) {
23532             if (hasPermission(permission, callerPackageName)) {
23533                 heldPermission = permission;
23534                 break;
23535             }
23536         }
23537         if (heldPermission.isEmpty()) {
23538             throw new SecurityException("Caller does not have the required permissions for "
23539                     + "this user. One of the following permission required: "
23540                     + Arrays.toString(permissions));
23541         }
23542         enforcePermission(heldPermission, callerPackageName, targetUserId);
23543     }
23544 
23545     /**
23546      * Checks if the calling process has been granted permission to apply a device policy on a
23547      * specific user.
23548      * The given permission will be checked along with its associated cross-user permission if it
23549      * exists and the target user is different to the calling user.
23550      *
23551      * @param callerPackageName The package name  of the calling application.
23552      * @param adminPolicy The admin policy that should grant holders permission.
23553      * @param permission The name of the permission being checked.
23554      * @param targetUserId The userId of the user which the caller needs permission to act on.
23555      * @throws SecurityException if the caller has not been granted the given permission,
23556      * the associated cross-user permission if the caller's user is different to the target user.
23557      */
23558     private void enforcePermission(String permission, int adminPolicy,
23559             String callerPackageName, int targetUserId) throws SecurityException {
23560         if (hasAdminPolicy(adminPolicy, callerPackageName)) {
23561             return;
23562         }
23563         enforcePermission(permission, callerPackageName, targetUserId);
23564     }
23565 
23566     /**
23567      * Checks if the calling process has been granted permission to apply a device policy on a
23568      * specific user.
23569      * The given permission will be checked along with its associated cross-user permission if it
23570      * exists and the target user is different to the calling user.
23571      *
23572      * @param callerPackageName The package name  of the calling application.
23573      * @param adminPolicy The admin policy that should grant holders permission.
23574      * @param permissions The names of the permissions being checked.
23575      * @param targetUserId The userId of the user which the caller needs permission to act on.
23576      * @throws SecurityException if the caller has not been granted the given permission,
23577      * the associated cross-user permission if the caller's user is different to the target user.
23578      */
23579     private void enforcePermissions(String[] permissions, int adminPolicy,
23580             String callerPackageName, int targetUserId) throws SecurityException {
23581         if (hasAdminPolicy(adminPolicy, callerPackageName)
23582                 && mInjector.userHandleGetCallingUserId() == targetUserId) {
23583             return;
23584         }
23585         enforcePermissions(permissions, callerPackageName, targetUserId);
23586     }
23587 
23588     /**
23589      * Checks whether the calling process has been granted permission to query a device policy on
23590      * a specific user.
23591      * The given permission will be checked along with its associated cross-user permission if it
23592      * exists and the target user is different to the calling user.
23593      *
23594      * @param callerPackageName The package name  of the calling application.
23595      * @param permission The name of the permission being checked.
23596      * @param targetUserId The userId of the user which the caller needs permission to act on.
23597      * @throws SecurityException if the caller has not been granted the given permission,
23598      * the associated cross-user permission if the caller's user is different to the target user
23599      * and if the user has not been granted {@link QUERY_ADMIN_POLICY}.
23600      */
23601     private void enforceCanQuery(String permission, String callerPackageName, int targetUserId)
23602             throws SecurityException {
23603         if (hasPermission(QUERY_ADMIN_POLICY, callerPackageName)) {
23604             return;
23605         }
23606         enforcePermission(permission, callerPackageName, targetUserId);
23607     }
23608 
23609     private boolean hasAdminPolicy(int adminPolicy, String callerPackageName) {
23610         synchronized (getLockObject()) {
23611             CallerIdentity caller = getCallerIdentity(callerPackageName);
23612             ActiveAdmin deviceAdmin = getActiveAdminWithPolicyForUidLocked(
23613                     null, adminPolicy, caller.getUid());
23614             return deviceAdmin != null;
23615         }
23616     }
23617 
23618     /**
23619      * Return whether the calling process has been granted permission to apply a device policy on
23620      * a specific user.
23621      *
23622      * @param callerPackageName The package name  of the calling application.
23623      * @param permission The name of the permission being checked.
23624      * @param targetUserId The userId of the user which the caller needs permission to act on.
23625      */
23626     private boolean hasPermission(String permission, String callerPackageName, int targetUserId) {
23627         CallerIdentity caller = getCallerIdentity(callerPackageName);
23628         boolean hasPermissionOnOwnUser = hasPermission(permission, caller.getPackageName());
23629         boolean hasPermissionOnTargetUser = true;
23630         if (hasPermissionOnOwnUser && caller.getUserId() != targetUserId) {
23631             hasPermissionOnTargetUser = hasPermissionOnTargetUser
23632                     && hasPermission(CROSS_USER_PERMISSIONS.get(permission),
23633                         caller.getPackageName());
23634         }
23635 
23636         return hasPermissionOnOwnUser && hasPermissionOnTargetUser;
23637     }
23638 
23639     /**
23640      * Return whether the calling process has been granted the given permission.
23641      *
23642      * @param callerPackageName The package name  of the calling application.
23643      * @param permission The name of the permission being checked.
23644      */
23645     private boolean hasPermission(String permission, @NonNull String callerPackageName) {
23646         Objects.requireNonNull(callerPackageName, "callerPackageName is null");
23647         if (permission == null) {
23648             return true;
23649         }
23650 
23651         CallerIdentity caller = getCallerIdentity(callerPackageName);
23652 
23653         // Check if the caller holds the permission
23654         if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
23655             return true;
23656         }
23657         int dpcType = getDpcType(caller);
23658         if (dpcType != NOT_A_DPC) {
23659             return DPC_PERMISSIONS.get(dpcType).contains(permission);
23660         }
23661         // Check the permission for the role-holder
23662         if (isCallerDevicePolicyManagementRoleHolder(caller)) {
23663             return anyDpcHasPermission(permission, caller.getUserId());
23664         }
23665         if (DELEGATE_SCOPES.containsKey(permission)) {
23666             return isCallerDelegate(caller, DELEGATE_SCOPES.get(permission));
23667         }
23668         return false;
23669     }
23670 
23671     /**
23672      * Returns whether there is a DPC on the given user that has been granted the given permission.
23673      *
23674      * @param permission The name of the permission being checked.
23675      * @param userId The id of the user to check.
23676      */
23677     private boolean anyDpcHasPermission(String permission, int userId) {
23678         if (mOwners.isDefaultDeviceOwnerUserId(userId)) {
23679             return DPC_PERMISSIONS.get(DEFAULT_DEVICE_OWNER).contains(permission);
23680         }
23681         if (mOwners.isFinancedDeviceOwnerUserId(userId)) {
23682             return DPC_PERMISSIONS.get(FINANCED_DEVICE_OWNER).contains(permission);
23683         }
23684         if (mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId)) {
23685             return DPC_PERMISSIONS.get(PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE).contains(
23686                     permission);
23687         }
23688         if (userId == 0 && mOwners.hasProfileOwner(0)) {
23689             return DPC_PERMISSIONS.get(PROFILE_OWNER_ON_USER_0).contains(permission);
23690         }
23691         if (mOwners.hasProfileOwner(userId)) {
23692             return DPC_PERMISSIONS.get(PROFILE_OWNER).contains(permission);
23693         }
23694         return false;
23695     }
23696 
23697     private EnforcingAdmin getEnforcingAdminForCaller(@Nullable ComponentName who,
23698             String callerPackageName) {
23699         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
23700         int userId = caller.getUserId();
23701         ActiveAdmin admin;
23702         if (isDeviceOwner(caller) || isProfileOwner(caller) || isCallerDelegate(caller)) {
23703             ComponentName component;
23704             synchronized (getLockObject()) {
23705                 if (who != null) {
23706                     admin = getActiveAdminUncheckedLocked(who, userId);
23707                     component = who;
23708                 } else {
23709                     admin = getDeviceOrProfileOwnerAdminLocked(userId);
23710                     component = admin.info.getComponent();
23711                 }
23712             }
23713             return EnforcingAdmin.createEnterpriseEnforcingAdmin(component, userId, admin);
23714         }
23715         // Check for non-DPC active admins.
23716         admin = getActiveAdminForCaller(who, caller);
23717         if (admin != null) {
23718             return EnforcingAdmin.createDeviceAdminEnforcingAdmin(admin.info.getComponent(), userId,
23719                     admin);
23720         }
23721         admin = getUserData(userId).createOrGetPermissionBasedAdmin(userId);
23722         return  EnforcingAdmin.createEnforcingAdmin(caller.getPackageName(), userId, admin);
23723     }
23724 
23725     private EnforcingAdmin getEnforcingAdminForPackage(@Nullable ComponentName who,
23726             String packageName, int userId) {
23727         ActiveAdmin admin;
23728         if (who != null) {
23729             if (isDeviceOwner(who, userId) || isProfileOwner(who, userId)) {
23730                 synchronized (getLockObject()) {
23731                     admin = getActiveAdminUncheckedLocked(who, userId);
23732                 }
23733                 if (admin != null) {
23734                     return EnforcingAdmin.createEnterpriseEnforcingAdmin(who, userId, admin);
23735                 }
23736             } else {
23737                 // Check for non-DPC active admins.
23738                 admin = getActiveAdminUncheckedLocked(who, userId);
23739                 if (admin != null) {
23740                     return EnforcingAdmin.createDeviceAdminEnforcingAdmin(who, userId, admin);
23741                 }
23742             }
23743         }
23744 
23745         admin = getUserData(userId).createOrGetPermissionBasedAdmin(userId);
23746         return  EnforcingAdmin.createEnforcingAdmin(packageName, userId, admin);
23747     }
23748 
23749     private int getAffectedUser(boolean calledOnParent) {
23750         int callingUserId = mInjector.userHandleGetCallingUserId();
23751         return calledOnParent ? getProfileParentId(callingUserId) : callingUserId;
23752     }
23753 
23754     /**
23755      * Return the DPC type of the given caller.
23756      */
23757     private @DpcType int getDpcType(CallerIdentity caller) {
23758         // Check the permissions of DPCs
23759         if (isDefaultDeviceOwner(caller)) {
23760             return DEFAULT_DEVICE_OWNER;
23761         }
23762         if (isFinancedDeviceOwner(caller)) {
23763             return FINANCED_DEVICE_OWNER;
23764         }
23765         if (isProfileOwner(caller)) {
23766             if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
23767                 return PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;
23768             }
23769             if (isManagedProfile(caller.getUserId())) {
23770                 return PROFILE_OWNER;
23771             }
23772             if (isProfileOwnerOnUser0(caller)) {
23773                 return PROFILE_OWNER_ON_USER_0;
23774             }
23775             if (isUserAffiliatedWithDevice(caller.getUserId())) {
23776                 return AFFILIATED_PROFILE_OWNER_ON_USER;
23777             }
23778             return PROFILE_OWNER_ON_USER;
23779         }
23780         return NOT_A_DPC;
23781     }
23782 
23783     private boolean isPermissionCheckFlagEnabled() {
23784         return DeviceConfig.getBoolean(
23785                 NAMESPACE_DEVICE_POLICY_MANAGER,
23786                 PERMISSION_BASED_ACCESS_EXPERIMENT_FLAG,
23787                 DEFAULT_VALUE_PERMISSION_BASED_ACCESS_FLAG);
23788     }
23789 
23790     static boolean isUnicornFlagEnabled() {
23791         return false;
23792     }
23793 
23794     private void unsuspendWorkAppsIfNecessary() {
23795         synchronized (getLockObject()) {
23796             DevicePolicyData policyData = getUserDataUnchecked(UserHandle.USER_SYSTEM);
23797             if (!policyData.mEffectiveKeepProfilesRunning) {
23798                 return;
23799             }
23800             policyData.mEffectiveKeepProfilesRunning = false;
23801             saveSettingsLocked(UserHandle.USER_SYSTEM);
23802         }
23803 
23804         Slog.w(LOG_TAG, "Work apps may have been paused via suspension previously.");
23805         PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
23806         List<UserInfo> users = mUserManagerInternal.getUsers(true /* excludeDying */);
23807 
23808         for (UserInfo user : users) {
23809             if (!user.isManagedProfile() || !user.isQuietModeEnabled()) {
23810                 continue;
23811             }
23812             int userId = user.id;
23813             Set<String> suspendedByAdmin;
23814             synchronized (getLockObject()) {
23815                 ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
23816                 // This is legacy code from Turn off Work 2.0 which is before setPackagesSuspended
23817                 // is migrated to PolicyEngine, so we only need to query the legacy ActiveAdmin here
23818                 if (admin == null || admin.suspendedPackages == null) {
23819                     suspendedByAdmin = Collections.emptySet();
23820                 } else {
23821                     suspendedByAdmin = new ArraySet<>(admin.suspendedPackages);
23822                 }
23823             }
23824             var packagesToUnsuspend = mInjector.getPackageManager(userId)
23825                     .getInstalledPackages(PackageManager.PackageInfoFlags.of(
23826                             MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE))
23827                     .stream()
23828                     .map(packageInfo -> packageInfo.packageName)
23829                     .filter(pkg -> !suspendedByAdmin.contains(pkg))
23830                     .toArray(String[]::new);
23831 
23832             Slogf.i(LOG_TAG, "Unsuspending work apps for user %d", userId);
23833             // When app suspension was used for quiet mode, the apps were suspended by platform
23834             // package, just like when admin suspends them. So although it wasn't admin who
23835             // suspended, this method will remove the right suspension record.
23836             pmi.setPackagesSuspendedByAdmin(userId, packagesToUnsuspend, false /* suspended */);
23837         }
23838     }
23839 
23840     public void setMtePolicy(int flags, String callerPackageName) {
23841         final Set<Integer> allowedModes =
23842                 Set.of(
23843                         DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY,
23844                         DevicePolicyManager.MTE_DISABLED,
23845                         DevicePolicyManager.MTE_ENABLED);
23846         Preconditions.checkArgument(
23847                 allowedModes.contains(flags), "Provided mode is not one of the allowed values.");
23848         // In general, this API should be available when "bootctl_settings_toggle" is set, which
23849         // signals that there is a control for MTE in the user settings and this API fundamentally
23850         // is a way for the device admin to override that setting.
23851         // Allow bootctl_device_policy_manager as an override, e.g. to offer the
23852         // DevicePolicyManager only without a visible user setting.
23853         if (!mInjector.systemPropertiesGetBoolean(
23854                 "ro.arm64.memtag.bootctl_device_policy_manager",
23855                 mInjector.systemPropertiesGetBoolean(
23856                         "ro.arm64.memtag.bootctl_settings_toggle", false))) {
23857             throw new UnsupportedOperationException("device does not support MTE");
23858         }
23859         final CallerIdentity caller = getCallerIdentity(callerPackageName);
23860         // For now we continue to restrict the DISABLED setting to device owner - we might need
23861         // another permission for this in future.
23862         if (flags == DevicePolicyManager.MTE_DISABLED) {
23863             Preconditions.checkCallAuthorization(isDefaultDeviceOwner(caller));
23864         }
23865 
23866         if (isPermissionCheckFlagEnabled()) {
23867             enforcePermission(MANAGE_DEVICE_POLICY_MTE, caller.getPackageName(),
23868                     UserHandle.USER_ALL);
23869         } else {
23870             Preconditions.checkCallAuthorization(
23871                     isDefaultDeviceOwner(caller)
23872                             || isProfileOwnerOfOrganizationOwnedDevice(caller));
23873         }
23874         synchronized (getLockObject()) {
23875             ActiveAdmin admin =
23876                         getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
23877 
23878             if (admin != null) {
23879                 final String memtagProperty = "arm64.memtag.bootctl";
23880                 if (flags == DevicePolicyManager.MTE_ENABLED) {
23881                     mInjector.systemPropertiesSet(memtagProperty, "memtag");
23882                 } else if (flags == DevicePolicyManager.MTE_DISABLED) {
23883                     mInjector.systemPropertiesSet(memtagProperty, "memtag-off");
23884                 } else if (flags == DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY) {
23885                     if (admin.mtePolicy != DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY) {
23886                         mInjector.systemPropertiesSet(memtagProperty, "default");
23887                     }
23888                 }
23889                 admin.mtePolicy = flags;
23890                 saveSettingsLocked(caller.getUserId());
23891 
23892                 DevicePolicyEventLogger.createEvent(DevicePolicyEnums.SET_MTE_POLICY)
23893                         .setInt(flags)
23894                         .setAdmin(caller.getPackageName())
23895                         .write();
23896             }
23897         }
23898     }
23899 
23900     @Override
23901     public int getMtePolicy(String callerPackageName) {
23902         final CallerIdentity caller = getCallerIdentity(callerPackageName);
23903         if (isPermissionCheckFlagEnabled()) {
23904             enforcePermission(MANAGE_DEVICE_POLICY_MTE, caller.getPackageName(),
23905                     UserHandle.USER_ALL);
23906         } else {
23907             Preconditions.checkCallAuthorization(
23908                     isDefaultDeviceOwner(caller)
23909                             || isProfileOwnerOfOrganizationOwnedDevice(caller)
23910                             || isSystemUid(caller));
23911         }
23912         synchronized (getLockObject()) {
23913             ActiveAdmin admin =
23914                         getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
23915             return admin != null
23916                     ? admin.mtePolicy
23917                     : DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY;
23918         }
23919     }
23920 
23921     @Override
23922     public void setContentProtectionPolicy(
23923             ComponentName who, String callerPackageName, @ContentProtectionPolicy int policy)
23924             throws SecurityException {
23925         if (!android.view.contentprotection.flags.Flags.manageDevicePolicyEnabled()) {
23926             return;
23927         }
23928 
23929         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
23930         int userId = caller.getUserId();
23931         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_CONTENT_PROTECTION_POLICY);
23932         EnforcingAdmin enforcingAdmin =
23933                 enforcePermissionAndGetEnforcingAdmin(
23934                         who, MANAGE_DEVICE_POLICY_CONTENT_PROTECTION, callerPackageName, userId);
23935 
23936         if (policy == CONTENT_PROTECTION_DISABLED) {
23937             mDevicePolicyEngine.removeLocalPolicy(
23938                     PolicyDefinition.CONTENT_PROTECTION, enforcingAdmin, userId);
23939         } else {
23940             mDevicePolicyEngine.setLocalPolicy(
23941                     PolicyDefinition.CONTENT_PROTECTION,
23942                     enforcingAdmin,
23943                     new IntegerPolicyValue(policy),
23944                     userId);
23945         }
23946     }
23947 
23948     @Override
23949     public @ContentProtectionPolicy int getContentProtectionPolicy(
23950             ComponentName who, String callerPackageName) {
23951         if (!android.view.contentprotection.flags.Flags.manageDevicePolicyEnabled()) {
23952             return CONTENT_PROTECTION_DISABLED;
23953         }
23954 
23955         CallerIdentity caller = getCallerIdentity(who, callerPackageName);
23956         int userId = caller.getUserId();
23957         enforceCanQuery(MANAGE_DEVICE_POLICY_CONTENT_PROTECTION, callerPackageName, userId);
23958 
23959         Integer policy =
23960                 mDevicePolicyEngine.getResolvedPolicy(PolicyDefinition.CONTENT_PROTECTION, userId);
23961         if (policy == null) {
23962             return CONTENT_PROTECTION_DISABLED;
23963         } else {
23964             return policy;
23965         }
23966     }
23967 
23968     private void updateContentProtectionPolicyCache(@UserIdInt int userId) {
23969         mPolicyCache.setContentProtectionPolicy(
23970                 userId,
23971                 mDevicePolicyEngine.getResolvedPolicy(PolicyDefinition.CONTENT_PROTECTION, userId));
23972     }
23973 
23974     @Override
23975     public ManagedSubscriptionsPolicy getManagedSubscriptionsPolicy() {
23976         synchronized (getLockObject()) {
23977             ActiveAdmin admin = getProfileOwnerOfOrganizationOwnedDeviceLocked();
23978             if (admin != null && admin.mManagedSubscriptionsPolicy != null) {
23979                 return admin.mManagedSubscriptionsPolicy;
23980             }
23981         }
23982         return new ManagedSubscriptionsPolicy(
23983                 ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS);
23984     }
23985 
23986     @Override
23987     public void setManagedSubscriptionsPolicy(ManagedSubscriptionsPolicy policy) {
23988         CallerIdentity caller = getCallerIdentity();
23989 
23990         if (!isCallerDevicePolicyManagementRoleHolder(caller)
23991                 && !Objects.equals(mInjector.settingsGlobalGetString(
23992                         Global.ALLOW_WORK_PROFILE_TELEPHONY_FOR_NON_DPM_ROLE_HOLDERS), "1")) {
23993             throw new UnsupportedOperationException("This api is not enabled");
23994         }
23995 
23996         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller),
23997                 "This policy can only be set by a profile owner on an organization-owned "
23998                         + "device.");
23999 
24000         int parentUserId = getProfileParentId(caller.getUserId());
24001         synchronized (getLockObject()) {
24002             final ActiveAdmin admin = getProfileOwnerLocked(caller.getUserId());
24003             if (hasUserSetupCompleted(parentUserId) && !isAdminTestOnlyLocked(
24004                     admin.info.getComponent(), caller.getUserId())) {
24005                 throw new IllegalStateException("Not allowed to apply this policy after setup");
24006             }
24007             boolean changed = false;
24008             if (!Objects.equals(policy, admin.mManagedSubscriptionsPolicy)) {
24009                 admin.mManagedSubscriptionsPolicy = policy;
24010                 changed = true;
24011             }
24012             if (changed) {
24013                 saveSettingsLocked(caller.getUserId());
24014             } else {
24015                 return;
24016             }
24017         }
24018 
24019         applyManagedSubscriptionsPolicyIfRequired();
24020 
24021         int policyType = getManagedSubscriptionsPolicy().getPolicyType();
24022         final long id = mInjector.binderClearCallingIdentity();
24023         try {
24024             if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_MANAGED_SUBSCRIPTIONS) {
24025                 installOemDefaultDialerAndSmsApp(caller.getUserId());
24026                 updateTelephonyCrossProfileIntentFilters(parentUserId, caller.getUserId(), true);
24027             } else if (policyType == ManagedSubscriptionsPolicy.TYPE_ALL_PERSONAL_SUBSCRIPTIONS) {
24028                 updateTelephonyCrossProfileIntentFilters(parentUserId, caller.getUserId(), false);
24029             }
24030         } finally {
24031             mInjector.binderRestoreCallingIdentity(id);
24032         }
24033     }
24034 
24035     private void installOemDefaultDialerAndSmsApp(int targetUserId) {
24036         try {
24037             String defaultDialerPackageName = getOemDefaultDialerPackage();
24038             String defaultSmsPackageName = getOemDefaultSmsPackage();
24039 
24040             if (defaultDialerPackageName != null) {
24041                 mIPackageManager.installExistingPackageAsUser(defaultDialerPackageName,
24042                         targetUserId, PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
24043                         PackageManager.INSTALL_REASON_POLICY, null);
24044             } else {
24045                 Slogf.w(LOG_TAG, "Couldn't install dialer app, dialer app package is null");
24046             }
24047 
24048             if (defaultSmsPackageName != null) {
24049                 mIPackageManager.installExistingPackageAsUser(defaultSmsPackageName, targetUserId,
24050                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
24051                         PackageManager.INSTALL_REASON_POLICY, null);
24052             } else {
24053                 Slogf.w(LOG_TAG, "Couldn't install sms app, sms app package is null");
24054             }
24055 
24056             updateDialerAndSmsManagedShortcutsOverrideCache();
24057         } catch (RemoteException re) {
24058             // shouldn't happen
24059             Slogf.wtf(LOG_TAG, "Failed to install dialer/sms app", re);
24060         }
24061     }
24062 
24063     private String getOemDefaultDialerPackage() {
24064         TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class);
24065         return telecomManager.getSystemDialerPackage();
24066     }
24067 
24068     private String getOemDefaultSmsPackage() {
24069         return mContext.getString(R.string.config_defaultSms);
24070     }
24071 
24072     private void updateDialerAndSmsManagedShortcutsOverrideCache() {
24073         ArrayMap<String, String> shortcutOverrides = new ArrayMap<>();
24074         int managedUserId = getManagedUserId();
24075         List<String> dialerRoleHolders = mRoleManager.getRoleHoldersAsUser(RoleManager.ROLE_DIALER,
24076                 UserHandle.of(managedUserId));
24077         List<String> smsRoleHolders = mRoleManager.getRoleHoldersAsUser(RoleManager.ROLE_SMS,
24078                 UserHandle.of(managedUserId));
24079 
24080         String dialerPackageToOverride = getOemDefaultDialerPackage();
24081         String smsPackageToOverride = getOemDefaultSmsPackage();
24082 
24083         // To get the default app, we can get all the role holders and get the first element.
24084         if (dialerPackageToOverride != null) {
24085             shortcutOverrides.put(dialerPackageToOverride,
24086                     dialerRoleHolders.isEmpty() ? dialerPackageToOverride
24087                             : dialerRoleHolders.get(0));
24088         }
24089         if (smsPackageToOverride != null) {
24090             shortcutOverrides.put(smsPackageToOverride,
24091                     smsRoleHolders.isEmpty() ? smsPackageToOverride : smsRoleHolders.get(0));
24092         }
24093 
24094         mPolicyCache.setLauncherShortcutOverrides(shortcutOverrides);
24095     }
24096 
24097     private void registerListenerToAssignSubscriptionsToUser(int userId) {
24098         synchronized (mSubscriptionsChangedListenerLock) {
24099             if (mSubscriptionsChangedListener != null) {
24100                 return;
24101             }
24102             SubscriptionManager subscriptionManager = mContext.getSystemService(
24103                     SubscriptionManager.class);
24104             // Listener to assign all current and future subs to managed profile.
24105             mSubscriptionsChangedListener = new SubscriptionManager.OnSubscriptionsChangedListener(
24106                     mHandler.getLooper()) {
24107                 @Override
24108                 public void onSubscriptionsChanged() {
24109                     final long id = mInjector.binderClearCallingIdentity();
24110                     try {
24111                         int[] subscriptionIds = subscriptionManager.getActiveSubscriptionIdList(
24112                                 false);
24113                         for (int subId : subscriptionIds) {
24114                             UserHandle associatedUserHandle =
24115                                     subscriptionManager.getSubscriptionUserHandle(subId);
24116                             if (associatedUserHandle == null
24117                                     || associatedUserHandle.getIdentifier() != userId) {
24118                                 subscriptionManager.setSubscriptionUserHandle(subId,
24119                                         UserHandle.of(userId));
24120                             }
24121                         }
24122                     } finally {
24123                         mInjector.binderRestoreCallingIdentity(id);
24124                     }
24125                 }
24126             };
24127 
24128             final long id = mInjector.binderClearCallingIdentity();
24129             try {
24130                 // When listener is added onSubscriptionsChanged gets called immediately for once
24131                 // (even if subscriptions are not changed) and later on when subscriptions changes.
24132                 subscriptionManager.addOnSubscriptionsChangedListener(
24133                         mHandler::post,
24134                         mSubscriptionsChangedListener);
24135             } finally {
24136                 mInjector.binderRestoreCallingIdentity(id);
24137             }
24138         }
24139     }
24140 
24141     private void unregisterOnSubscriptionsChangedListener() {
24142         synchronized (mSubscriptionsChangedListenerLock) {
24143             if (mSubscriptionsChangedListener != null) {
24144                 SubscriptionManager subscriptionManager = mContext.getSystemService(
24145                         SubscriptionManager.class);
24146                 subscriptionManager.removeOnSubscriptionsChangedListener(
24147                         mSubscriptionsChangedListener);
24148                 mSubscriptionsChangedListener = null;
24149             }
24150         }
24151     }
24152 
24153     @Override
24154     public DevicePolicyState getDevicePolicyState() {
24155         Preconditions.checkCallAuthorization(
24156                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
24157         return mInjector.binderWithCleanCallingIdentity(mDevicePolicyEngine::getDevicePolicyState);
24158     }
24159 
24160     @Override
24161     public boolean triggerDevicePolicyEngineMigration(boolean forceMigration) {
24162         Preconditions.checkCallAuthorization(
24163                 hasCallingOrSelfPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS));
24164         return mInjector.binderWithCleanCallingIdentity(() -> {
24165             synchronized (getLockObject()) {
24166                 boolean canForceMigration = forceMigration && !hasNonTestOnlyActiveAdmins();
24167                 if (!canForceMigration && !shouldMigrateV1ToDevicePolicyEngine()) {
24168                     return false;
24169                 }
24170                 boolean migrated = migrateV1PoliciesToDevicePolicyEngine();
24171                 migrated &= migratePoliciesPostUpgradeToDevicePolicyEngineLocked();
24172                 return migrated;
24173             }
24174         });
24175     }
24176 
24177     private boolean hasNonTestOnlyActiveAdmins() {
24178         return mInjector.binderWithCleanCallingIdentity(() -> {
24179             for (UserInfo userInfo : mUserManager.getUsers()) {
24180                 synchronized (getLockObject()) {
24181                     List<ComponentName> activeAdmins = getActiveAdmins(userInfo.id);
24182                     if (activeAdmins == null) {
24183                         continue;
24184                     }
24185                     for (ComponentName admin : activeAdmins) {
24186                         if (!isAdminTestOnlyLocked(admin, userInfo.id)) {
24187                             return true;
24188                         }
24189                     }
24190                 }
24191             }
24192             return false;
24193         });
24194     }
24195 
24196     private boolean shouldMigrateV1ToDevicePolicyEngine() {
24197         return mInjector.binderWithCleanCallingIdentity(() -> !mOwners.isMigratedToPolicyEngine());
24198     }
24199 
24200     /**
24201      * Migrates the initial set of policies to use policy engine.
24202      * [b/318497672] Migrate policies that weren't migrated properly in the initial migration on
24203      * update from Android T to Android U
24204      */
24205     private void maybeMigratePoliciesPostUpgradeToDevicePolicyEngineLocked() {
24206         if (!mOwners.isMigratedToPolicyEngine() || mOwners.isMigratedPostUpdate()) {
24207             return;
24208         }
24209         migratePoliciesPostUpgradeToDevicePolicyEngineLocked();
24210         mOwners.markPostUpgradeMigration();
24211     }
24212 
24213     private boolean migratePoliciesPostUpgradeToDevicePolicyEngineLocked() {
24214         try {
24215             migrateScreenCapturePolicyLocked();
24216             migrateLockTaskPolicyLocked();
24217             migrateUserRestrictionsLocked();
24218             return true;
24219         } catch (Exception e) {
24220             Slogf.e(LOG_TAG, e, "Error occurred during post upgrade migration to the device "
24221                     + "policy engine.");
24222             return false;
24223         }
24224     }
24225 
24226     /**
24227      * @return {@code true} if policies were migrated successfully, {@code false} otherwise.
24228      */
24229     private boolean migrateV1PoliciesToDevicePolicyEngine() {
24230         return mInjector.binderWithCleanCallingIdentity(() -> {
24231             try {
24232                 synchronized (getLockObject()) {
24233                     Slogf.i(LOG_TAG,
24234                             "Started device policies migration to the device policy engine.");
24235                     if (isUnicornFlagEnabled()) {
24236                         migrateAutoTimezonePolicy();
24237                         migratePermissionGrantStatePolicies();
24238                     }
24239                     migratePermittedInputMethodsPolicyLocked();
24240                     migrateAccountManagementDisabledPolicyLocked();
24241                     migrateUserControlDisabledPackagesLocked();
24242 
24243                     mOwners.markMigrationToPolicyEngine();
24244                     return true;
24245                 }
24246             } catch (Exception e) {
24247                 mDevicePolicyEngine.clearAllPolicies();
24248                 Slogf.e(LOG_TAG, e, "Error occurred during device policy migration, will "
24249                         + "reattempt on the next system server restart.");
24250                 return false;
24251             }
24252         });
24253     }
24254 
24255     /**
24256      * Migrates the rest of policies to use policy engine.
24257      */
24258     @GuardedBy("getLockObject()")
24259     private void migratePoliciesToPolicyEngineLocked() {
24260         maybeMigrateSecurityLoggingPolicyLocked();
24261         // ID format: <sdk-int>.<auto_increment_id>.<descriptions>'
24262         String unmanagedBackupId = "35.1.unmanaged-mode";
24263         boolean migrated = false;
24264         migrated = migrated | maybeMigrateRequiredPasswordComplexityLocked(unmanagedBackupId);
24265         migrated = migrated | maybeMigrateSuspendedPackagesLocked(unmanagedBackupId);
24266         if (migrated) {
24267             Slogf.i(LOG_TAG, "Backup made: " + unmanagedBackupId);
24268         }
24269         // Additional migration steps should repeat the pattern above with a new backupId.
24270     }
24271 
24272     private void migrateAutoTimezonePolicy() {
24273         Slogf.i(LOG_TAG, "Skipping Migration of AUTO_TIMEZONE policy to device policy engine,"
24274                 + "as no way to identify if the value was set by the admin or the user.");
24275     }
24276 
24277     private void migratePermissionGrantStatePolicies() {
24278         Slogf.i(LOG_TAG, "Migrating PERMISSION_GRANT policy to device policy engine.");
24279         for (UserInfo userInfo : mUserManager.getUsers()) {
24280             ActiveAdmin admin = getMostProbableDPCAdminForLocalPolicy(userInfo.id);
24281             if (admin == null) {
24282                 Slogf.i(LOG_TAG, "No admin found that can set permission grant state on user "
24283                         + userInfo.id);
24284                 continue;
24285             }
24286             for (PackageInfo packageInfo : getInstalledPackagesOnUser(userInfo.id)) {
24287                 if (packageInfo.requestedPermissions == null) {
24288                     continue;
24289                 }
24290                 for (String permission : packageInfo.requestedPermissions) {
24291                     if (!isRuntimePermission(permission)) {
24292                         continue;
24293                     }
24294                     int grantState = DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
24295                     try {
24296                         grantState = getPermissionGrantStateForUser(
24297                                 packageInfo.packageName, permission,
24298                                 new CallerIdentity(
24299                                         mInjector.binderGetCallingUid(),
24300                                         admin.info.getComponent().getPackageName(),
24301                                         admin.info.getComponent()),
24302                                 userInfo.id);
24303                     } catch (RemoteException e) {
24304                         Slogf.e(LOG_TAG, e, "Error retrieving permission grant state for %s "
24305                                         + "and %s", packageInfo.packageName, permission);
24306                     }
24307                     if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
24308                         // Not Controlled by a policy
24309                         continue;
24310                     }
24311 
24312                     mDevicePolicyEngine.setLocalPolicy(
24313                             PolicyDefinition.PERMISSION_GRANT(packageInfo.packageName,
24314                                     permission),
24315                             EnforcingAdmin.createEnterpriseEnforcingAdmin(
24316                                     admin.info.getComponent(),
24317                                     admin.getUserHandle().getIdentifier()),
24318                             new IntegerPolicyValue(grantState),
24319                             userInfo.id,
24320                             /* skipEnforcePolicy= */ true);
24321                 }
24322             }
24323         }
24324     }
24325 
24326     private void migrateScreenCapturePolicyLocked() {
24327         Binder.withCleanCallingIdentity(() -> {
24328             ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked();
24329             if (admin != null
24330                     && ((isDeviceOwner(admin) && admin.disableScreenCapture)
24331                     || (admin.getParentActiveAdmin() != null
24332                     && admin.getParentActiveAdmin().disableScreenCapture))) {
24333 
24334                 EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24335                         admin.info.getComponent(),
24336                         admin.getUserHandle().getIdentifier(),
24337                         admin);
24338                 mDevicePolicyEngine.setGlobalPolicy(
24339                         PolicyDefinition.SCREEN_CAPTURE_DISABLED,
24340                         enforcingAdmin,
24341                         new BooleanPolicyValue(true));
24342             }
24343 
24344             List<UserInfo> users = mUserManager.getUsers();
24345             for (UserInfo userInfo : users) {
24346                 ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
24347                 if (profileOwner != null && profileOwner.disableScreenCapture) {
24348                     EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24349                             profileOwner.info.getComponent(),
24350                             profileOwner.getUserHandle().getIdentifier(),
24351                             profileOwner);
24352                     mDevicePolicyEngine.setLocalPolicy(
24353                             PolicyDefinition.SCREEN_CAPTURE_DISABLED,
24354                             enforcingAdmin,
24355                             new BooleanPolicyValue(true),
24356                             profileOwner.getUserHandle().getIdentifier());
24357                 }
24358             }
24359         });
24360     }
24361 
24362     private void migrateLockTaskPolicyLocked() {
24363         Binder.withCleanCallingIdentity(() -> {
24364             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
24365             if (deviceOwner != null) {
24366                 int doUserId = deviceOwner.getUserHandle().getIdentifier();
24367                 DevicePolicyData policies = getUserData(doUserId);
24368                 List<String> packages = policies.mLockTaskPackages;
24369                 int features = policies.mLockTaskFeatures;
24370                 // TODO: find out about persistent preferred activities
24371                 if (!packages.isEmpty()) {
24372                     setLockTaskPolicyInPolicyEngine(deviceOwner, doUserId, packages, features);
24373                 }
24374             }
24375 
24376             for (int userId : mUserManagerInternal.getUserIds()) {
24377                 ActiveAdmin profileOwner = getProfileOwnerLocked(userId);
24378                 if (profileOwner != null && canDPCManagedUserUseLockTaskLocked(userId)) {
24379                     DevicePolicyData policies = getUserData(userId);
24380                     List<String> packages = policies.mLockTaskPackages;
24381                     int features = policies.mLockTaskFeatures;
24382                     if (!packages.isEmpty()) {
24383                         setLockTaskPolicyInPolicyEngine(profileOwner, userId, packages, features);
24384                     }
24385                 }
24386             }
24387         });
24388     }
24389 
24390     private void setLockTaskPolicyInPolicyEngine(
24391             ActiveAdmin admin, int userId, List<String> packages, int features) {
24392         EnforcingAdmin enforcingAdmin =
24393                 EnforcingAdmin.createEnterpriseEnforcingAdmin(
24394                         admin.info.getComponent(),
24395                         userId,
24396                         admin);
24397         mDevicePolicyEngine.setLocalPolicy(
24398                 PolicyDefinition.LOCK_TASK,
24399                 enforcingAdmin,
24400                 new LockTaskPolicy(new HashSet<>(packages), features),
24401                 userId);
24402     }
24403 
24404     private void migratePermittedInputMethodsPolicyLocked() {
24405         Binder.withCleanCallingIdentity(() -> {
24406             List<UserInfo> users = mUserManager.getUsers();
24407             for (UserInfo userInfo : users) {
24408                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
24409                 if (admin != null) {
24410                     EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24411                             admin.info.getComponent(),
24412                             admin.getUserHandle().getIdentifier(),
24413                             admin);
24414                     if (admin.permittedInputMethods != null) {
24415                         mDevicePolicyEngine.setLocalPolicy(
24416                                 PolicyDefinition.PERMITTED_INPUT_METHODS,
24417                                 enforcingAdmin,
24418                                 new PackageSetPolicyValue(
24419                                         new HashSet<>(admin.permittedInputMethods)),
24420                                 admin.getUserHandle().getIdentifier());
24421                     }
24422                     if (admin.getParentActiveAdmin() != null
24423                             && admin.getParentActiveAdmin().permittedInputMethods != null) {
24424                         mDevicePolicyEngine.setLocalPolicy(
24425                                 PolicyDefinition.PERMITTED_INPUT_METHODS,
24426                                 enforcingAdmin,
24427                                 new PackageSetPolicyValue(
24428                                         new HashSet<>(admin.getParentActiveAdmin()
24429                                                 .permittedInputMethods)),
24430                                 getProfileParentId(admin.getUserHandle().getIdentifier()));
24431                     }
24432                 }
24433             }
24434         });
24435     }
24436 
24437     private void migrateAccountManagementDisabledPolicyLocked() {
24438         Binder.withCleanCallingIdentity(() -> {
24439             List<UserInfo> users = mUserManager.getUsers();
24440             for (UserInfo userInfo : users) {
24441                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
24442                 if (admin != null) {
24443                     EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24444                             admin.info.getComponent(),
24445                             admin.getUserHandle().getIdentifier(),
24446                             admin);
24447                     for (String accountType : admin.accountTypesWithManagementDisabled) {
24448                         mDevicePolicyEngine.setLocalPolicy(
24449                                 PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
24450                                 enforcingAdmin,
24451                                 new BooleanPolicyValue(true),
24452                                 admin.getUserHandle().getIdentifier());
24453                     }
24454                     if (admin.getParentActiveAdmin() != null) {
24455                         for (String accountType : admin.getParentActiveAdmin()
24456                                 .accountTypesWithManagementDisabled) {
24457                             mDevicePolicyEngine.setLocalPolicy(
24458                                     PolicyDefinition.ACCOUNT_MANAGEMENT_DISABLED(accountType),
24459                                     enforcingAdmin,
24460                                     new BooleanPolicyValue(true),
24461                                     getProfileParentId(admin.getUserHandle().getIdentifier()));
24462                         }
24463                     }
24464                 }
24465             }
24466         });
24467     }
24468 
24469     private void migrateUserControlDisabledPackagesLocked() {
24470         Binder.withCleanCallingIdentity(() -> {
24471             List<UserInfo> users = mUserManager.getUsers();
24472             for (UserInfo userInfo : users) {
24473                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
24474                 if (admin != null && admin.protectedPackages != null) {
24475                     EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24476                             admin.info.getComponent(),
24477                             admin.getUserHandle().getIdentifier(),
24478                             admin);
24479                     if (isDeviceOwner(admin)) {
24480                         mDevicePolicyEngine.setGlobalPolicy(
24481                                 PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
24482                                 enforcingAdmin,
24483                                 new PackageSetPolicyValue(
24484                                         new HashSet<>(admin.protectedPackages)));
24485                     } else {
24486                         mDevicePolicyEngine.setLocalPolicy(
24487                                 PolicyDefinition.USER_CONTROLLED_DISABLED_PACKAGES,
24488                                 enforcingAdmin,
24489                                 new PackageSetPolicyValue(
24490                                         new HashSet<>(admin.protectedPackages)),
24491                                 admin.getUserHandle().getIdentifier());
24492                     }
24493                 }
24494             }
24495         });
24496     }
24497 
24498     private void migrateUserRestrictionsLocked() {
24499         Binder.withCleanCallingIdentity(() -> {
24500             List<UserInfo> users = mUserManager.getUsers();
24501             for (UserInfo userInfo : users) {
24502                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
24503                 if (admin == null) continue;
24504                 ComponentName adminComponent = admin.info.getComponent();
24505                 int userId = userInfo.id;
24506                 EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24507                         adminComponent,
24508                         userId,
24509                         admin);
24510                 int ownerType;
24511                 if (isDeviceOwner(admin)) {
24512                     ownerType = OWNER_TYPE_DEVICE_OWNER;
24513                 } else if (isProfileOwnerOfOrganizationOwnedDevice(adminComponent, userId)) {
24514                     ownerType = OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;
24515                 } else if (isProfileOwner(adminComponent, userId)) {
24516                     ownerType = OWNER_TYPE_PROFILE_OWNER;
24517                 } else {
24518                     throw new IllegalStateException("Invalid DO/PO state");
24519                 }
24520 
24521                 for (final String restriction : admin.ensureUserRestrictions().keySet()) {
24522                     setBackwardCompatibleUserRestrictionLocked(ownerType, enforcingAdmin, userId,
24523                             restriction, /* enabled */ true, /* parent */ false);
24524                 }
24525                 for (final String restriction : admin.getParentActiveAdmin()
24526                         .ensureUserRestrictions().keySet()) {
24527                     setBackwardCompatibleUserRestrictionLocked(ownerType, enforcingAdmin, userId,
24528                             restriction, /* enabled */ true, /* parent */ true);
24529                 }
24530             }
24531         });
24532     }
24533 
24534     @GuardedBy("getLockObject()")
24535     private void iterateThroughDpcAdminsLocked(BiConsumer<ActiveAdmin, EnforcingAdmin> runner) {
24536         Binder.withCleanCallingIdentity(() -> {
24537             List<UserInfo> users = mUserManager.getUsers();
24538             for (UserInfo userInfo : users) {
24539                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(userInfo.id);
24540                 if (admin == null) continue;
24541                 EnforcingAdmin enforcingAdmin = EnforcingAdmin.createEnterpriseEnforcingAdmin(
24542                         admin.info.getComponent(),
24543                         userInfo.id,
24544                         admin);
24545 
24546                 runner.accept(admin, enforcingAdmin);
24547             }
24548         });
24549     }
24550 
24551     private List<PackageInfo> getInstalledPackagesOnUser(int userId) {
24552         return mInjector.binderWithCleanCallingIdentity(() ->
24553                 mContext.getPackageManager().getInstalledPackagesAsUser(
24554                         PackageManager.PackageInfoFlags.of(
24555                                 PackageManager.GET_PERMISSIONS), userId));
24556     }
24557 
24558     /**
24559      * Returns the most probable admin to have set a global policy according to the following
24560      * heuristics:
24561      *
24562      * <ul>
24563      * <li>The device owner on any user</li>
24564      * <li>The org owned profile owner on any user</li>
24565      * <li>The profile owner on any user</li>
24566      * </ul>
24567      */
24568     @Nullable
24569     // TODO(b/266928216): Check what the admin capabilities are when deciding which admin to return.
24570     private ActiveAdmin getMostProbableDPCAdminForGlobalPolicy() {
24571         synchronized (getLockObject()) {
24572             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
24573             if (deviceOwner != null) {
24574                 return deviceOwner;
24575             }
24576 
24577             List<UserInfo> users = mUserManager.getUsers();
24578             for (UserInfo userInfo : users) {
24579                 if (isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
24580                     return getProfileOwnerAdminLocked(userInfo.id);
24581                 }
24582             }
24583 
24584             for (UserInfo userInfo : users) {
24585                 ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
24586                 if (profileOwner != null) {
24587                     return profileOwner;
24588                 }
24589             }
24590             return null;
24591         }
24592     }
24593 
24594     /**
24595      * Returns the most probable admin to have set a policy on the given {@code userId} according
24596      * to the following heuristics:
24597      *
24598      * <ul>
24599      * <li>The device owner on the given userId</li>
24600      * <li>The profile owner on the given userId</li>
24601      * <li>The org owned profile owner of which the given userId is its parent</li>
24602      * <li>The profile owner of which the given userId is its parent</li>
24603      * <li>The device owner on any user</li>
24604      * <li>The profile owner on any user</li>
24605      * </ul>
24606      */
24607     @Nullable
24608     // TODO(b/266928216): Check what the admin capabilities are when deciding which admin to return.
24609     private ActiveAdmin getMostProbableDPCAdminForLocalPolicy(int userId) {
24610         synchronized (getLockObject()) {
24611             ActiveAdmin localDeviceOwner = getDeviceOwnerLocked(userId);
24612             if (localDeviceOwner != null) {
24613                 return localDeviceOwner;
24614             }
24615 
24616             ActiveAdmin localProfileOwner = getProfileOwnerLocked(userId);
24617             if (localProfileOwner != null) {
24618                 return localProfileOwner;
24619             }
24620 
24621             int[] profileIds = mUserManager.getProfileIds(userId, /* enabledOnly= */ false);
24622             for (int id : profileIds) {
24623                 if (id == userId) {
24624                     continue;
24625                 }
24626                 if (isProfileOwnerOfOrganizationOwnedDevice(id)) {
24627                     return getProfileOwnerAdminLocked(id);
24628                 }
24629             }
24630 
24631             for (int id : profileIds) {
24632                 if (id == userId) {
24633                     continue;
24634                 }
24635                 if (isManagedProfile(id)) {
24636                     return getProfileOwnerAdminLocked(id);
24637                 }
24638             }
24639 
24640             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
24641             if (deviceOwner != null) {
24642                 return deviceOwner;
24643             }
24644 
24645             for (UserInfo userInfo : mUserManager.getUsers()) {
24646                 ActiveAdmin profileOwner = getProfileOwnerLocked(userInfo.id);
24647                 if (profileOwner != null) {
24648                     return profileOwner;
24649                 }
24650             }
24651             return null;
24652         }
24653     }
24654 
24655     private ActiveAdmin getActiveAdminForCaller(@Nullable ComponentName who,
24656             CallerIdentity caller) {
24657         synchronized (getLockObject()) {
24658             if (who != null) {
24659                 return getActiveAdminUncheckedLocked(who, caller.getUserId());
24660             }
24661             return mInjector.binderWithCleanCallingIdentity(() -> {
24662                 List<ComponentName> activeAdmins = getActiveAdmins(caller.getUserId());
24663                 if (activeAdmins != null) {
24664                     for (ComponentName admin : activeAdmins) {
24665                         if (admin.getPackageName().equals(caller.getPackageName())) {
24666                             return getActiveAdminUncheckedLocked(admin, caller.getUserId());
24667                         }
24668                     }
24669                 }
24670                 return null;
24671             });
24672         }
24673     }
24674 
24675     @Override
24676     public boolean isDeviceFinanced(String callerPackageName) {
24677         CallerIdentity caller = getCallerIdentity(callerPackageName);
24678         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
24679                 || isProfileOwnerOfOrganizationOwnedDevice(caller)
24680                 || isProfileOwnerOnUser0(caller)
24681                 || isCallerDevicePolicyManagementRoleHolder(caller)
24682                 || isCallerSystemSupervisionRoleHolder(caller));
24683         return getFinancedDeviceKioskRoleHolderOnAnyUser() != null;
24684     };
24685 
24686     @Override
24687     public String getFinancedDeviceKioskRoleHolder(String callerPackageName) {
24688         CallerIdentity caller = getCallerIdentity(callerPackageName);
24689         enforcePermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, caller.getPackageName(),
24690                 caller.getUserId());
24691         return getFinancedDeviceKioskRoleHolderOnAnyUser();
24692     }
24693 
24694     private String getFinancedDeviceKioskRoleHolderOnAnyUser() {
24695         return getRoleHolderPackageNameOnUser(
24696                 RoleManager.ROLE_FINANCED_DEVICE_KIOSK, UserHandle.USER_ALL);
24697     }
24698 
24699     /**
24700      * TODO (b/278924166): this method is added for debugging the specified bug.
24701      * Remove once fixed.
24702      **/
24703     private void logStackTrace(String methodName) {
24704         try {
24705             StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
24706             String stackMethod;
24707             StringBuilder stackTrace = new StringBuilder();
24708             for (StackTraceElement s : stackTraceElements) {
24709                 stackMethod = s.getMethodName();
24710                 if (stackMethod == null || stackMethod.equals("getThreadStackTrace")
24711                         || stackMethod.equals("getStackTrace")
24712                         || stackMethod.equals("logStackTrace")) {
24713                     continue;
24714                 }
24715                 stackTrace.append(s.getMethodName() + ":" + s.getLineNumber() + "\n");
24716             }
24717             Slogf.d(LOG_TAG, "StackTrace for " + methodName + ": \n" + stackTrace);
24718         } catch (Exception e) {
24719             Slogf.d(LOG_TAG, "Unable to get stacktrace");
24720         }
24721     }
24722 
24723     @Override
24724     public int[] getSubscriptionIds(String callerPackageName) {
24725         final CallerIdentity caller = getCallerIdentity(callerPackageName);
24726         enforceCanQuery(
24727                 MANAGE_DEVICE_POLICY_MANAGED_SUBSCRIPTIONS,
24728                 caller.getPackageName(),
24729                 caller.getUserId());
24730         return getSubscriptionIdsInternal(callerPackageName).toArray();
24731     }
24732 
24733     private IntArray getSubscriptionIdsInternal(String callerPackageName) {
24734         SubscriptionManager subscriptionManager =
24735                 mContext.getSystemService(SubscriptionManager.class);
24736         return mInjector.binderWithCleanCallingIdentity(() -> {
24737             IntArray adminOwnedSubscriptions = new IntArray();
24738             List<SubscriptionInfo> subs = subscriptionManager.getAvailableSubscriptionInfoList();
24739             int subCount = (subs != null) ? subs.size() : 0;
24740             for (int i = 0; i < subCount; i++) {
24741                 SubscriptionInfo sub = subs.get(i);
24742                 if (sub.getGroupOwner()
24743                         .equals(callerPackageName)) {
24744                     adminOwnedSubscriptions.add(sub.getSubscriptionId());
24745                 }
24746             }
24747             return adminOwnedSubscriptions;
24748         });
24749 
24750     }
24751 
24752     @Override
24753     public void setMaxPolicyStorageLimit(String callerPackageName, int storageLimit) {
24754         if (!Flags.devicePolicySizeTrackingInternalBugFixEnabled()) {
24755             return;
24756         }
24757         CallerIdentity caller = getCallerIdentity(callerPackageName);
24758         enforcePermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, caller.getPackageName(),
24759                 caller.getUserId());
24760 
24761         if (storageLimit < DEFAULT_POLICY_SIZE_LIMIT && storageLimit != -1) {
24762             throw new IllegalArgumentException("Can't set a size limit less than the minimum "
24763                     + "allowed size.");
24764         }
24765         mDevicePolicyEngine.setMaxPolicyStorageLimit(storageLimit);
24766     }
24767 
24768     @Override
24769     public int getMaxPolicyStorageLimit(String callerPackageName) {
24770         if (!Flags.devicePolicySizeTrackingInternalBugFixEnabled()) {
24771             return -1;
24772         }
24773         CallerIdentity caller = getCallerIdentity(callerPackageName);
24774         enforcePermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, caller.getPackageName(),
24775                 caller.getUserId());
24776 
24777         return mDevicePolicyEngine.getMaxPolicyStorageLimit();
24778     }
24779 
24780     @Override
24781     public void forceSetMaxPolicyStorageLimit(String callerPackageName, int storageLimit) {
24782         if (!Flags.devicePolicySizeTrackingInternalBugFixEnabled()) {
24783             return;
24784         }
24785         CallerIdentity caller = getCallerIdentity(callerPackageName);
24786         enforcePermission(MANAGE_DEVICE_POLICY_STORAGE_LIMIT, caller.getPackageName(),
24787                 caller.getUserId());
24788 
24789         mDevicePolicyEngine.setMaxPolicyStorageLimit(storageLimit);
24790     }
24791 
24792     @Override
24793     public int getPolicySizeForAdmin(
24794             String callerPackageName, android.app.admin.EnforcingAdmin admin) {
24795         if (!Flags.devicePolicySizeTrackingInternalBugFixEnabled()) {
24796             return -1;
24797         }
24798         CallerIdentity caller = getCallerIdentity(callerPackageName);
24799         enforcePermission(MANAGE_DEVICE_POLICY_STORAGE_LIMIT, caller.getPackageName(),
24800                 caller.getUserId());
24801 
24802         return mDevicePolicyEngine.getPolicySizeForAdmin(
24803                 EnforcingAdmin.createEnforcingAdmin(admin));
24804     }
24805 
24806     @Override
24807     public int getHeadlessDeviceOwnerMode(String callerPackageName) {
24808         final CallerIdentity caller = getCallerIdentity(callerPackageName);
24809         enforcePermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, caller.getPackageName(),
24810                 caller.getUserId());
24811 
24812         return Binder.withCleanCallingIdentity(() -> getHeadlessDeviceOwnerModeForDeviceOwner());
24813     }
24814 }
24815