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.MANAGE_CA_CERTIFICATES;
21 import static android.Manifest.permission.REQUEST_PASSWORD_COMPLEXITY;
22 import static android.accessibilityservice.AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
23 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
24 import static android.app.AppOpsManager.MODE_ALLOWED;
25 import static android.app.AppOpsManager.MODE_DEFAULT;
26 import static android.app.admin.DeviceAdminReceiver.ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED;
27 import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE;
28 import static android.app.admin.DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE;
29 import static android.app.admin.DevicePolicyManager.ACTION_MANAGED_PROFILE_PROVISIONED;
30 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE;
31 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE;
32 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
33 import static android.app.admin.DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED;
34 import static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY;
35 import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE;
36 import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED;
37 import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER;
38 import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED;
39 import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED;
40 import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS;
41 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER;
42 import static android.app.admin.DevicePolicyManager.CODE_OK;
43 import static android.app.admin.DevicePolicyManager.CODE_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
44 import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER;
45 import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER;
46 import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING;
47 import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED;
48 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
49 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
50 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
51 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_SELECTION;
52 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
53 import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE;
54 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
55 import static android.app.admin.DevicePolicyManager.DELEGATION_NETWORK_LOGGING;
56 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
57 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
58 import static android.app.admin.DevicePolicyManager.DELEGATION_SECURITY_LOGGING;
59 import static android.app.admin.DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
60 import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE;
61 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
62 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
63 import static android.app.admin.DevicePolicyManager.ID_TYPE_INDIVIDUAL_ATTESTATION;
64 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
65 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
66 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
67 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME;
68 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS;
69 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
70 import static android.app.admin.DevicePolicyManager.NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
71 import static android.app.admin.DevicePolicyManager.NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
72 import static android.app.admin.DevicePolicyManager.OPERATION_SAFETY_REASON_NONE;
73 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
74 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_LOW;
75 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
76 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
77 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
78 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
79 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK;
80 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
81 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED;
82 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
83 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
84 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
85 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
86 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_NOT_SUSPENDED;
87 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_EXPLICITLY;
88 import static android.app.admin.DevicePolicyManager.PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT;
89 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OFF;
90 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
91 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
92 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_UNKNOWN;
93 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
94 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR;
95 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
96 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED;
97 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_PRE_CONDITION_FAILED;
98 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_PROFILE_CREATION_FAILED;
99 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_REMOVE_NON_REQUIRED_APPS_FAILED;
100 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_SETTING_PROFILE_OWNER_FAILED;
101 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_SET_DEVICE_OWNER_FAILED;
102 import static android.app.admin.DevicePolicyManager.PROVISIONING_RESULT_STARTING_PROFILE_FAILED;
103 import static android.app.admin.DevicePolicyManager.STATE_USER_UNMANAGED;
104 import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
105 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
106 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
107 import static android.app.admin.DevicePolicyManager.WIPE_SILENTLY;
108 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
109 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
110 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
111 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
112 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT;
113 import static android.net.ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE;
114 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
115 import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER;
116 import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
117 import static android.provider.Telephony.Carriers.DPC_URI;
118 import static android.provider.Telephony.Carriers.ENFORCE_KEY;
119 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI;
120 import static android.security.keystore.AttestationUtils.USE_INDIVIDUAL_ATTESTATION;
121 
122 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
123 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
124 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
125 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
126 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER;
127 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER;
128 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
129 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_DEVICE_OWNER;
130 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER;
131 import static com.android.server.pm.UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE;
132 
133 import android.Manifest;
134 import android.Manifest.permission;
135 import android.accessibilityservice.AccessibilityServiceInfo;
136 import android.accounts.Account;
137 import android.accounts.AccountManager;
138 import android.accounts.AccountManagerFuture;
139 import android.accounts.AuthenticatorException;
140 import android.accounts.OperationCanceledException;
141 import android.annotation.IntDef;
142 import android.annotation.NonNull;
143 import android.annotation.Nullable;
144 import android.annotation.UserIdInt;
145 import android.app.Activity;
146 import android.app.ActivityManager;
147 import android.app.ActivityManagerInternal;
148 import android.app.ActivityTaskManager;
149 import android.app.ActivityThread;
150 import android.app.AlarmManager;
151 import android.app.AppGlobals;
152 import android.app.AppOpsManager;
153 import android.app.AppOpsManager.Mode;
154 import android.app.BroadcastOptions;
155 import android.app.IActivityManager;
156 import android.app.IActivityTaskManager;
157 import android.app.IApplicationThread;
158 import android.app.IServiceConnection;
159 import android.app.Notification;
160 import android.app.NotificationManager;
161 import android.app.PendingIntent;
162 import android.app.StatusBarManager;
163 import android.app.admin.DeviceAdminInfo;
164 import android.app.admin.DeviceAdminReceiver;
165 import android.app.admin.DevicePolicyCache;
166 import android.app.admin.DevicePolicyEventLogger;
167 import android.app.admin.DevicePolicyManager;
168 import android.app.admin.DevicePolicyManager.DeviceOwnerType;
169 import android.app.admin.DevicePolicyManager.DevicePolicyOperation;
170 import android.app.admin.DevicePolicyManager.OperationSafetyReason;
171 import android.app.admin.DevicePolicyManager.PasswordComplexity;
172 import android.app.admin.DevicePolicyManager.PersonalAppsSuspensionReason;
173 import android.app.admin.DevicePolicyManagerInternal;
174 import android.app.admin.DevicePolicyManagerLiteInternal;
175 import android.app.admin.DevicePolicySafetyChecker;
176 import android.app.admin.DeviceStateCache;
177 import android.app.admin.FactoryResetProtectionPolicy;
178 import android.app.admin.FullyManagedDeviceProvisioningParams;
179 import android.app.admin.ManagedProfileProvisioningParams;
180 import android.app.admin.NetworkEvent;
181 import android.app.admin.ParcelableGranteeMap;
182 import android.app.admin.PasswordMetrics;
183 import android.app.admin.PasswordPolicy;
184 import android.app.admin.SecurityLog;
185 import android.app.admin.SecurityLog.SecurityEvent;
186 import android.app.admin.StartInstallingUpdateCallback;
187 import android.app.admin.SystemUpdateInfo;
188 import android.app.admin.SystemUpdatePolicy;
189 import android.app.admin.UnsafeStateException;
190 import android.app.backup.IBackupManager;
191 import android.app.compat.CompatChanges;
192 import android.app.trust.TrustManager;
193 import android.app.usage.UsageStatsManagerInternal;
194 import android.compat.annotation.ChangeId;
195 import android.compat.annotation.EnabledAfter;
196 import android.compat.annotation.EnabledSince;
197 import android.content.ActivityNotFoundException;
198 import android.content.BroadcastReceiver;
199 import android.content.ComponentName;
200 import android.content.ContentValues;
201 import android.content.Context;
202 import android.content.IIntentReceiver;
203 import android.content.IIntentSender;
204 import android.content.Intent;
205 import android.content.IntentFilter;
206 import android.content.IntentSender;
207 import android.content.PermissionChecker;
208 import android.content.pm.ActivityInfo;
209 import android.content.pm.ApplicationInfo;
210 import android.content.pm.CrossProfileApps;
211 import android.content.pm.CrossProfileAppsInternal;
212 import android.content.pm.IPackageDataObserver;
213 import android.content.pm.IPackageManager;
214 import android.content.pm.PackageInfo;
215 import android.content.pm.PackageInstaller;
216 import android.content.pm.PackageManager;
217 import android.content.pm.PackageManager.NameNotFoundException;
218 import android.content.pm.PackageManagerInternal;
219 import android.content.pm.ParceledListSlice;
220 import android.content.pm.PermissionInfo;
221 import android.content.pm.ResolveInfo;
222 import android.content.pm.ServiceInfo;
223 import android.content.pm.StringParceledListSlice;
224 import android.content.pm.UserInfo;
225 import android.content.res.Resources;
226 import android.database.ContentObserver;
227 import android.database.Cursor;
228 import android.graphics.Bitmap;
229 import android.hardware.usb.UsbManager;
230 import android.location.LocationManager;
231 import android.media.AudioManager;
232 import android.media.IAudioService;
233 import android.net.ConnectivityManager;
234 import android.net.ConnectivitySettingsManager;
235 import android.net.IIpConnectivityMetrics;
236 import android.net.ProxyInfo;
237 import android.net.Uri;
238 import android.net.VpnManager;
239 import android.net.metrics.IpConnectivityLog;
240 import android.net.wifi.WifiManager;
241 import android.os.Binder;
242 import android.os.Build;
243 import android.os.Bundle;
244 import android.os.Environment;
245 import android.os.Handler;
246 import android.os.IBinder;
247 import android.os.Looper;
248 import android.os.ParcelFileDescriptor;
249 import android.os.PersistableBundle;
250 import android.os.PowerManager;
251 import android.os.PowerManagerInternal;
252 import android.os.Process;
253 import android.os.RemoteCallback;
254 import android.os.RemoteException;
255 import android.os.ResultReceiver;
256 import android.os.ServiceManager;
257 import android.os.ServiceSpecificException;
258 import android.os.ShellCallback;
259 import android.os.SystemClock;
260 import android.os.SystemProperties;
261 import android.os.UserHandle;
262 import android.os.UserManager;
263 import android.os.UserManager.UserRestrictionSource;
264 import android.os.storage.StorageManager;
265 import android.permission.AdminPermissionControlParams;
266 import android.permission.IPermissionManager;
267 import android.permission.PermissionControllerManager;
268 import android.provider.CalendarContract;
269 import android.provider.ContactsContract.QuickContact;
270 import android.provider.ContactsInternal;
271 import android.provider.Settings;
272 import android.provider.Settings.Global;
273 import android.provider.Telephony;
274 import android.security.AppUriAuthenticationPolicy;
275 import android.security.IKeyChainAliasCallback;
276 import android.security.IKeyChainService;
277 import android.security.KeyChain;
278 import android.security.KeyChain.KeyChainConnection;
279 import android.security.KeyStore;
280 import android.security.keymaster.KeymasterCertificateChain;
281 import android.security.keystore.AttestationUtils;
282 import android.security.keystore.KeyGenParameterSpec;
283 import android.security.keystore.ParcelableKeyGenParameterSpec;
284 import android.stats.devicepolicy.DevicePolicyEnums;
285 import android.telephony.TelephonyManager;
286 import android.telephony.data.ApnSetting;
287 import android.text.TextUtils;
288 import android.text.format.DateUtils;
289 import android.util.ArrayMap;
290 import android.util.ArraySet;
291 import android.util.AtomicFile;
292 import android.util.DebugUtils;
293 import android.util.IndentingPrintWriter;
294 import android.util.Log;
295 import android.util.Pair;
296 import android.util.SparseArray;
297 import android.util.TypedXmlPullParser;
298 import android.util.TypedXmlSerializer;
299 import android.util.Xml;
300 import android.view.IWindowManager;
301 import android.view.accessibility.AccessibilityManager;
302 import android.view.accessibility.IAccessibilityManager;
303 import android.view.inputmethod.InputMethodInfo;
304 
305 import com.android.internal.R;
306 import com.android.internal.annotations.GuardedBy;
307 import com.android.internal.annotations.VisibleForTesting;
308 import com.android.internal.app.LocalePicker;
309 import com.android.internal.logging.MetricsLogger;
310 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
311 import com.android.internal.net.NetworkUtilsInternal;
312 import com.android.internal.notification.SystemNotificationChannels;
313 import com.android.internal.os.BackgroundThread;
314 import com.android.internal.statusbar.IStatusBarService;
315 import com.android.internal.telephony.SmsApplication;
316 import com.android.internal.util.ArrayUtils;
317 import com.android.internal.util.DumpUtils;
318 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
319 import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
320 import com.android.internal.util.JournaledFile;
321 import com.android.internal.util.Preconditions;
322 import com.android.internal.util.StatLogger;
323 import com.android.internal.widget.LockPatternUtils;
324 import com.android.internal.widget.LockSettingsInternal;
325 import com.android.internal.widget.LockscreenCredential;
326 import com.android.internal.widget.PasswordValidationError;
327 import com.android.net.module.util.ProxyUtils;
328 import com.android.server.LocalServices;
329 import com.android.server.LockGuard;
330 import com.android.server.PersistentDataBlockManagerInternal;
331 import com.android.server.SystemServerInitThreadPool;
332 import com.android.server.SystemService;
333 import com.android.server.devicepolicy.ActiveAdmin.TrustAgentInfo;
334 import com.android.server.inputmethod.InputMethodManagerInternal;
335 import com.android.server.net.NetworkPolicyManagerInternal;
336 import com.android.server.pm.RestrictionsSet;
337 import com.android.server.pm.UserManagerInternal;
338 import com.android.server.pm.UserManagerInternal.UserRestrictionsListener;
339 import com.android.server.pm.UserRestrictionsUtils;
340 import com.android.server.pm.parsing.pkg.AndroidPackage;
341 import com.android.server.storage.DeviceStorageMonitorInternal;
342 import com.android.server.uri.NeededUriGrants;
343 import com.android.server.uri.UriGrantsManagerInternal;
344 import com.android.server.utils.Slogf;
345 import com.android.server.wm.ActivityTaskManagerInternal;
346 
347 import com.google.android.collect.Sets;
348 
349 import org.xmlpull.v1.XmlPullParserException;
350 
351 import java.io.ByteArrayInputStream;
352 import java.io.File;
353 import java.io.FileDescriptor;
354 import java.io.FileInputStream;
355 import java.io.FileOutputStream;
356 import java.io.IOException;
357 import java.io.PrintWriter;
358 import java.lang.reflect.Constructor;
359 import java.security.cert.CertificateException;
360 import java.security.cert.CertificateFactory;
361 import java.security.cert.X509Certificate;
362 import java.text.DateFormat;
363 import java.time.LocalDate;
364 import java.util.ArrayList;
365 import java.util.Arrays;
366 import java.util.Collection;
367 import java.util.Collections;
368 import java.util.Date;
369 import java.util.HashMap;
370 import java.util.HashSet;
371 import java.util.List;
372 import java.util.Locale;
373 import java.util.Map;
374 import java.util.Objects;
375 import java.util.Set;
376 import java.util.concurrent.TimeUnit;
377 import java.util.function.Function;
378 import java.util.function.Predicate;
379 import java.util.stream.Collectors;
380 
381 /**
382  * Implementation of the device policy APIs.
383  */
384 public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
385 
386     protected static final String LOG_TAG = "DevicePolicyManager";
387 
388     static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
389 
390     static final String DEVICE_POLICIES_XML = "device_policies.xml";
391 
392     static final String POLICIES_VERSION_XML = "device_policies_version";
393 
394     private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML =
395             "transfer-ownership-parameters.xml";
396 
397     private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle";
398 
399     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
400 
401     private static final int REQUEST_PROFILE_OFF_DEADLINE = 5572;
402 
403     private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
404 
405     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
406     private static final long MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD = 3 * MS_PER_DAY;
407     /** When to warn the user about the approaching work profile off deadline: 1 day before */
408     private static final long MANAGED_PROFILE_OFF_WARNING_PERIOD = 1 * MS_PER_DAY;
409 
410     private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION =
411             "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
412 
413     /** Broadcast action invoked when the user taps a notification to turn the profile on. */
414     @VisibleForTesting
415     static final String ACTION_TURN_PROFILE_ON_NOTIFICATION =
416             "com.android.server.ACTION_TURN_PROFILE_ON_NOTIFICATION";
417 
418     /** Broadcast action for tracking managed profile maximum time off. */
419     @VisibleForTesting
420     static final String ACTION_PROFILE_OFF_DEADLINE =
421             "com.android.server.ACTION_PROFILE_OFF_DEADLINE";
422 
423     private static final String CALLED_FROM_PARENT = "calledFromParent";
424     private static final String NOT_CALLED_FROM_PARENT = "notCalledFromParent";
425 
426     private static final String CREDENTIAL_MANAGEMENT_APP = "credentialManagementApp";
427     private static final String NOT_CREDENTIAL_MANAGEMENT_APP = "notCredentialManagementApp";
428 
429     private static final String NULL_STRING_ARRAY = "nullStringArray";
430 
431     private static final String ALLOW_USER_PROVISIONING_KEY = "ro.config.allowuserprovisioning";
432 
433     // Comprehensive list of delegations.
434     private static final String DELEGATIONS[] = {
435         DELEGATION_CERT_INSTALL,
436         DELEGATION_APP_RESTRICTIONS,
437         DELEGATION_BLOCK_UNINSTALL,
438         DELEGATION_ENABLE_SYSTEM_APP,
439         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
440         DELEGATION_PACKAGE_ACCESS,
441         DELEGATION_PERMISSION_GRANT,
442         DELEGATION_INSTALL_EXISTING_PACKAGE,
443         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
444         DELEGATION_NETWORK_LOGGING,
445         DELEGATION_SECURITY_LOGGING,
446         DELEGATION_CERT_SELECTION,
447     };
448 
449     // Subset of delegations that can only be delegated by Device Owner or Profile Owner of a
450     // managed profile.
451     private static final List<String> DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS =
452             Arrays.asList(new String[]{
453                     DELEGATION_NETWORK_LOGGING,
454             });
455 
456     // Subset of delegations that can only be delegated by Device Owner or Profile Owner of an
457     // organization-owned and managed profile.
458     private static final List<String>
459             DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS =
460             Arrays.asList(new String[]{
461                     DELEGATION_SECURITY_LOGGING,
462             });
463 
464     // Subset of delegations that only one single package within a given user can hold
465     private static final List<String> EXCLUSIVE_DELEGATIONS = Arrays.asList(new String[] {
466             DELEGATION_NETWORK_LOGGING,
467             DELEGATION_SECURITY_LOGGING,
468             DELEGATION_CERT_SELECTION,
469     });
470 
471     /**
472      * System property whose value indicates whether the device is fully owned by an organization:
473      * it can be either a device owner device, or a device with an organization-owned managed
474      * profile.
475      *
476      * <p>The state is stored as a Boolean string.
477      */
478     private static final String PROPERTY_ORGANIZATION_OWNED = "ro.organization_owned";
479 
480     private static final int STATUS_BAR_DISABLE_MASK =
481             StatusBarManager.DISABLE_EXPAND |
482             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
483             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
484             StatusBarManager.DISABLE_SEARCH;
485 
486     private static final int STATUS_BAR_DISABLE2_MASK =
487             StatusBarManager.DISABLE2_QUICK_SETTINGS;
488 
489     private static final Set<String> SECURE_SETTINGS_ALLOWLIST;
490     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST;
491     private static final Set<String> GLOBAL_SETTINGS_ALLOWLIST;
492     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
493     private static final Set<String> SYSTEM_SETTINGS_ALLOWLIST;
494     private static final Set<Integer> DA_DISALLOWED_POLICIES;
495     private static final String AB_DEVICE_KEY = "ro.build.ab_update";
496     // The version of the current DevicePolicyManagerService data. This version is used
497     // to decide whether an existing policy in the {@link #DEVICE_POLICIES_XML} needs to
498     // be upgraded. See {@link PolicyVersionUpgrader} on instructions how to add an upgrade
499     // step.
500     static final int DPMS_VERSION = 2;
501 
502     static {
503         SECURE_SETTINGS_ALLOWLIST = new ArraySet<>();
504         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
505         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
506         SECURE_SETTINGS_ALLOWLIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
507 
508         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST = new ArraySet<>();
509         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.addAll(SECURE_SETTINGS_ALLOWLIST);
510         SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.add(Settings.Secure.LOCATION_MODE);
511 
512         GLOBAL_SETTINGS_ALLOWLIST = new ArraySet<>();
513         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_ENABLED);
514         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.ADB_WIFI_ENABLED);
515         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME);
516         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.AUTO_TIME_ZONE);
517         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.DATA_ROAMING);
518         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
519         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_SLEEP_POLICY);
520         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
521         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
522         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_MODE);
523         GLOBAL_SETTINGS_ALLOWLIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER);
524 
525         GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
526         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
527         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
528         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
529         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
530         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
531 
532         SYSTEM_SETTINGS_ALLOWLIST = new ArraySet<>();
533         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS);
534         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_FLOAT);
535         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE);
536         SYSTEM_SETTINGS_ALLOWLIST.add(Settings.System.SCREEN_OFF_TIMEOUT);
537 
538         DA_DISALLOWED_POLICIES = new ArraySet<>();
539         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
540         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
541         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
542         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
543     }
544 
545     /**
546      * Keyguard features that when set on a profile affect the profile content or challenge only.
547      * These cannot be set on the managed profile's parent DPM instance
548      */
549     private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
550             DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
551 
552     /** Keyguard features that are allowed to be set on a managed profile */
553     private static final int PROFILE_KEYGUARD_FEATURES =
554             NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER
555                     | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
556 
557     private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
558 
559     /**
560      * Minimum timeout in milliseconds after which unlocking with weak auth times out,
561      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
562      */
563     private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
564 
565     /**
566      * The amount of ms that a managed kiosk must go without user interaction to be considered
567      * unattended.
568      */
569     private static final int UNATTENDED_MANAGED_KIOSK_MS = 30000;
570 
571     /**
572      * Strings logged with {@link
573      * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB},
574      * {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB},
575      * {@link DevicePolicyEnums#SET_NETWORK_LOGGING_ENABLED} and
576      * {@link DevicePolicyEnums#RETRIEVE_NETWORK_LOGS}.
577      */
578     private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
579     private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
580 
581     /**
582      * For admin apps targeting R+, throw when the app sets password requirement
583      * that is not taken into account at given quality. For example when quality is set
584      * to {@link android.app.admin.DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, it doesn't
585      * make sense to require certain password length. If the intent is to require a password of
586      * certain length having at least NUMERIC quality, the admin should first call
587      * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} and only then call
588      * {@link android.app.admin.DevicePolicyManager#setPasswordMinimumLength}.
589      *
590      * <p>Conversely when an admin app targeting R+ lowers password quality, those
591      * requirements that stop making sense are reset to default values.
592      */
593     @ChangeId
594     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
595     private static final long ADMIN_APP_PASSWORD_COMPLEXITY = 123562444L;
596 
597     /**
598      * Admin apps targeting Android R+ may not use
599      * {@link android.app.admin.DevicePolicyManager#setSecureSetting} to change the deprecated
600      * {@link android.provider.Settings.Secure#LOCATION_MODE} setting. Instead they should use
601      * {@link android.app.admin.DevicePolicyManager#setLocationEnabled}.
602      */
603     @ChangeId
604     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
605     private static final long USE_SET_LOCATION_ENABLED = 117835097L;
606 
607     // Only add to the end of the list. Do not change or rearrange these values, that will break
608     // historical data. Do not use negative numbers or zero, logger only handles positive
609     // integers.
610     private static final int COPY_ACCOUNT_SUCCEEDED = 1;
611     private static final int COPY_ACCOUNT_FAILED = 2;
612     private static final int COPY_ACCOUNT_TIMED_OUT = 3;
613     private static final int COPY_ACCOUNT_EXCEPTION = 4;
614 
615     @IntDef({
616             COPY_ACCOUNT_SUCCEEDED,
617             COPY_ACCOUNT_FAILED,
618             COPY_ACCOUNT_TIMED_OUT,
619             COPY_ACCOUNT_EXCEPTION})
620     private @interface CopyAccountStatus {}
621 
622     /**
623      * Admin apps targeting Android S+ may not use
624      * {@link android.app.admin.DevicePolicyManager#setPasswordQuality} to set password quality
625      * on the {@code DevicePolicyManager} instance obtained by calling
626      * {@link android.app.admin.DevicePolicyManager#getParentProfileInstance}.
627      * Instead, they should use
628      * {@link android.app.admin.DevicePolicyManager#setRequiredPasswordComplexity} to set
629      * coarse-grained password requirements device-wide.
630      */
631     @ChangeId
632     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.S)
633     private static final long PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT = 165573442L;
634 
635     private static final String CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG =
636             "The alias provided must be contained in the aliases specified in the credential "
637                     + "management app's authentication policy";
638     private static final String NOT_SYSTEM_CALLER_MSG = "Only the system can %s";
639 
640     final Context mContext;
641     final Injector mInjector;
642     final IPackageManager mIPackageManager;
643     final IPermissionManager mIPermissionManager;
644     final UserManager mUserManager;
645     final UserManagerInternal mUserManagerInternal;
646     final UsageStatsManagerInternal mUsageStatsManagerInternal;
647     final TelephonyManager mTelephonyManager;
648     private final LockPatternUtils mLockPatternUtils;
649     private final LockSettingsInternal mLockSettingsInternal;
650     private final DeviceAdminServiceController mDeviceAdminServiceController;
651     private final OverlayPackagesProvider mOverlayPackagesProvider;
652 
653     private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl();
654     private final DeviceStateCacheImpl mStateCache = new DeviceStateCacheImpl();
655 
656     /**
657      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
658      * is requested for user u.
659      */
660     private final Set<Pair<String, Integer>> mPackagesToRemove =
661             new ArraySet<Pair<String, Integer>>();
662 
663     final LocalService mLocalService;
664 
665     // Stores and loads state on device and profile owners.
666     @VisibleForTesting
667     final Owners mOwners;
668 
669     private final Binder mToken = new Binder();
670 
671     /**
672      * Whether or not device admin feature is supported. If it isn't return defaults for all
673      * public methods, unless the caller has the appropriate permission for a particular method.
674      */
675     final boolean mHasFeature;
676 
677     /**
678      * Whether or not this device is a watch.
679      */
680     final boolean mIsWatch;
681 
682     /**
683      * Whether or not this device is an automotive.
684      */
685     private final boolean mIsAutomotive;
686 
687     /**
688      * Whether this device has the telephony feature.
689      */
690     final boolean mHasTelephonyFeature;
691 
692     private final CertificateMonitor mCertificateMonitor;
693     private final SecurityLogMonitor mSecurityLogMonitor;
694     private final RemoteBugreportManager mBugreportCollectionManager;
695 
696     @GuardedBy("getLockObject()")
697     private NetworkLogger mNetworkLogger;
698 
699     private final SetupContentObserver mSetupContentObserver;
700     private final DevicePolicyConstantsObserver mConstantsObserver;
701 
702     private DevicePolicyConstants mConstants;
703 
704     /**
705      * User to be switched to on {@code logoutUser()}.
706      *
707      * <p>Only used on devices with headless system user mode
708      */
709     @GuardedBy("getLockObject()")
710     private @UserIdInt int mLogoutUserId = UserHandle.USER_NULL;
711 
712     /**
713      * User the network logging notification was sent to.
714      */
715     // Guarded by mHandler
716     private @UserIdInt int mNetworkLoggingNotificationUserId = UserHandle.USER_NULL;
717 
718     private static final boolean ENABLE_LOCK_GUARD = true;
719 
720     /**
721      * Profile off deadline is not set or more than MANAGED_PROFILE_OFF_WARNING_PERIOD away, or the
722      * user is running unlocked, no need for notification.
723      */
724     private static final int PROFILE_OFF_NOTIFICATION_NONE = 0;
725     /**
726      * Profile off deadline is closer than MANAGED_PROFILE_OFF_WARNING_PERIOD.
727      */
728     private static final int PROFILE_OFF_NOTIFICATION_WARNING = 1;
729     /**
730      * Profile off deadline reached, notify the user that personal apps blocked.
731      */
732     private static final int PROFILE_OFF_NOTIFICATION_SUSPENDED = 2;
733 
734     interface Stats {
735         int LOCK_GUARD_GUARD = 0;
736 
737         int COUNT = LOCK_GUARD_GUARD + 1;
738     }
739 
740     private final StatLogger mStatLogger = new StatLogger(new String[] {
741             "LockGuard.guard()",
742     });
743 
744     private final Object mLockDoNoUseDirectly = LockGuard.installNewLock(
745             LockGuard.INDEX_DPMS, /* doWtf=*/ true);
746 
getLockObject()747     final Object getLockObject() {
748         if (ENABLE_LOCK_GUARD) {
749             final long start = mStatLogger.getTime();
750             LockGuard.guard(LockGuard.INDEX_DPMS);
751             mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start);
752         }
753         return mLockDoNoUseDirectly;
754     }
755 
756     /**
757      * Check if the current thread holds the DPMS lock, and if not, do a WTF.
758      *
759      * (Doing this check too much may be costly, so don't call it in a hot path.)
760      */
ensureLocked()761     final void ensureLocked() {
762         if (Thread.holdsLock(mLockDoNoUseDirectly)) {
763             return;
764         }
765         Slogf.wtfStack(LOG_TAG, "Not holding DPMS lock.");
766     }
767 
768     /**
769      * Calls wtfStack() if called with the DPMS lock held.
770      */
wtfIfInLock()771     private void wtfIfInLock() {
772         if (Thread.holdsLock(mLockDoNoUseDirectly)) {
773             Slogf.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
774         }
775     }
776 
777     @VisibleForTesting
778     final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager;
779 
780     @Nullable
781     private DevicePolicySafetyChecker mSafetyChecker;
782 
783     @GuardedBy("getLockObject()")
784     private final ArrayList<Object> mPendingUserCreatedCallbackTokens = new ArrayList<>();
785 
786     public static final class Lifecycle extends SystemService {
787         private BaseIDevicePolicyManager mService;
788 
Lifecycle(Context context)789         public Lifecycle(Context context) {
790             super(context);
791             String dpmsClassName = context.getResources()
792                     .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
793             if (TextUtils.isEmpty(dpmsClassName)) {
794                 dpmsClassName = DevicePolicyManagerService.class.getName();
795             }
796             try {
797                 Class<?> serviceClass = Class.forName(dpmsClassName);
798                 Constructor<?> constructor = serviceClass.getConstructor(Context.class);
799                 mService = (BaseIDevicePolicyManager) constructor.newInstance(context);
800             } catch (Exception e) {
801                 throw new IllegalStateException(
802                     "Failed to instantiate DevicePolicyManagerService with class name: "
803                     + dpmsClassName, e);
804             }
805         }
806 
807         /** Sets the {@link DevicePolicySafetyChecker}. */
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)808         public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
809             mService.setDevicePolicySafetyChecker(safetyChecker);
810         }
811 
812         @Override
onStart()813         public void onStart() {
814             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
815         }
816 
817         @Override
onBootPhase(int phase)818         public void onBootPhase(int phase) {
819             mService.systemReady(phase);
820         }
821 
822         @Override
onUserStarting(@onNull TargetUser user)823         public void onUserStarting(@NonNull TargetUser user) {
824             if (user.isPreCreated()) return;
825             mService.handleStartUser(user.getUserIdentifier());
826         }
827 
828         @Override
onUserUnlocking(@onNull TargetUser user)829         public void onUserUnlocking(@NonNull TargetUser user) {
830             if (user.isPreCreated()) return;
831             mService.handleUnlockUser(user.getUserIdentifier());
832         }
833 
834         @Override
onUserStopping(@onNull TargetUser user)835         public void onUserStopping(@NonNull TargetUser user) {
836             if (user.isPreCreated()) return;
837             mService.handleStopUser(user.getUserIdentifier());
838         }
839 
840         @Override
onUserUnlocked(@onNull TargetUser user)841         public void onUserUnlocked(@NonNull TargetUser user) {
842             if (user.isPreCreated()) return;
843             mService.handleOnUserUnlocked(user.getUserIdentifier());
844         }
845     }
846 
847     @GuardedBy("getLockObject()")
848     final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
849 
850     @GuardedBy("getLockObject()")
851 
852     final Handler mHandler;
853     final Handler mBackgroundHandler;
854 
855     /** Listens only if mHasFeature == true. */
856     final BroadcastReceiver mReceiver = new BroadcastReceiver() {
857         @Override
858         public void onReceive(Context context, Intent intent) {
859             final String action = intent.getAction();
860             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
861                     getSendingUserId());
862 
863             /*
864              * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
865              * however it's too early in the boot process to register with IIpConnectivityMetrics
866              * to listen for events.
867              */
868             if (Intent.ACTION_USER_STARTED.equals(action) && userHandle == UserHandle.USER_SYSTEM) {
869                 synchronized (getLockObject()) {
870                     if (isNetworkLoggingEnabledInternalLocked()) {
871                         setNetworkLoggingActiveInternal(true);
872                     }
873                 }
874             }
875             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
876                     && userHandle == mOwners.getDeviceOwnerUserId()) {
877                 mBugreportCollectionManager.checkForPendingBugreportAfterBoot();
878 
879             }
880             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
881                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
882                 if (VERBOSE_LOG) {
883                     Slogf.v(LOG_TAG, "Sending password expiration notifications for action "
884                             + action + " for user " + userHandle);
885                 }
886                 mHandler.post(new Runnable() {
887                     @Override
888                     public void run() {
889                         handlePasswordExpirationNotification(userHandle);
890                     }
891                 });
892             }
893 
894             if (Intent.ACTION_USER_ADDED.equals(action)) {
895                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
896                 synchronized (getLockObject()) {
897                     // It might take a while for the user to become affiliated. Make security
898                     // and network logging unavailable in the meantime.
899                     maybePauseDeviceWideLoggingLocked();
900                 }
901             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
902                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
903                 synchronized (getLockObject()) {
904                     // Check whether the user is affiliated, *before* removing its data.
905                     boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
906                     removeUserData(userHandle);
907                     if (!isRemovedUserAffiliated) {
908                         // We discard the logs when unaffiliated users are deleted (so that the
909                         // device owner cannot retrieve data about that user after it's gone).
910                         discardDeviceWideLogsLocked();
911                         // Resume logging if all remaining users are affiliated.
912                         maybeResumeDeviceWideLoggingLocked();
913                     }
914                 }
915             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
916                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle);
917                 synchronized (getLockObject()) {
918                     maybeSendAdminEnabledBroadcastLocked(userHandle);
919                     // Reset the policy data
920                     mUserData.remove(userHandle);
921                 }
922                 handlePackagesChanged(null /* check all admins */, userHandle);
923                 updatePersonalAppsSuspensionOnUserStart(userHandle);
924             } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
925                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle);
926                 if (isManagedProfile(userHandle)) {
927                     Slogf.d(LOG_TAG, "Managed profile was stopped");
928                     updatePersonalAppsSuspension(userHandle, false /* unlocked */);
929                 }
930             } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
931                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle);
932             } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
933                 synchronized (getLockObject()) {
934                     maybeSendAdminEnabledBroadcastLocked(userHandle);
935                 }
936                 if (isManagedProfile(userHandle)) {
937                     Slogf.d(LOG_TAG, "Managed profile became unlocked");
938                     final boolean suspended =
939                             updatePersonalAppsSuspension(userHandle, true /* unlocked */);
940                     triggerPolicyComplianceCheckIfNeeded(userHandle, suspended);
941                 }
942             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
943                 handlePackagesChanged(null /* check all admins */, userHandle);
944             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
945                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
946             } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
947                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
948                     handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
949                 } else {
950                     handleNewPackageInstalled(intent.getData().getSchemeSpecificPart(), userHandle);
951                 }
952             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
953                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
954                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
955                 removeCredentialManagementApp(intent.getData().getSchemeSpecificPart());
956             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
957                 clearWipeProfileNotification();
958             } else if (Intent.ACTION_DATE_CHANGED.equals(action)
959                     || Intent.ACTION_TIME_CHANGED.equals(action)) {
960                 // Update freeze period record when clock naturally progresses to the next day
961                 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made
962                 // (ACTION_TIME_CHANGED)
963                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
964                 final int userId = getManagedUserId(UserHandle.USER_SYSTEM);
965                 if (userId >= 0) {
966                     updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked(userId));
967                 }
968             } else if (ACTION_PROFILE_OFF_DEADLINE.equals(action)) {
969                 Slogf.i(LOG_TAG, "Profile off deadline alarm was triggered");
970                 final int userId = getManagedUserId(UserHandle.USER_SYSTEM);
971                 if (userId >= 0) {
972                     updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked(userId));
973                 } else {
974                     Slogf.wtf(LOG_TAG, "Got deadline alarm for nonexistent profile");
975                 }
976             } else if (ACTION_TURN_PROFILE_ON_NOTIFICATION.equals(action)) {
977                 Slogf.i(LOG_TAG, "requesting to turn on the profile: " + userHandle);
978                 mUserManager.requestQuietModeEnabled(false, UserHandle.of(userHandle));
979             }
980         }
981 
982         private void sendDeviceOwnerUserCommand(String action, int userHandle) {
983             synchronized (getLockObject()) {
984                 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
985                 if (deviceOwner != null) {
986                     Bundle extras = new Bundle();
987                     extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
988                     sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null,
989                             /* inForeground */ true);
990                 }
991             }
992         }
993     };
994 
995     protected static class RestrictionsListener implements UserRestrictionsListener {
996         private final Context mContext;
997         private final UserManagerInternal mUserManagerInternal;
998         private final DevicePolicyManagerService mDpms;
999 
RestrictionsListener( Context context, UserManagerInternal userManagerInternal, DevicePolicyManagerService dpms)1000         public RestrictionsListener(
1001                 Context context,
1002                 UserManagerInternal userManagerInternal,
1003                 DevicePolicyManagerService dpms) {
1004             mContext = context;
1005             mUserManagerInternal = userManagerInternal;
1006             mDpms = dpms;
1007         }
1008 
1009         @Override
onUserRestrictionsChanged(int userId, Bundle newRestrictions, Bundle prevRestrictions)1010         public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
1011                 Bundle prevRestrictions) {
1012             resetCrossProfileIntentFiltersIfNeeded(userId, newRestrictions, prevRestrictions);
1013             resetUserVpnIfNeeded(userId, newRestrictions, prevRestrictions);
1014         }
1015 
resetUserVpnIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1016         private void resetUserVpnIfNeeded(
1017                 int userId, Bundle newRestrictions, Bundle prevRestrictions) {
1018             final boolean newlyEnforced =
1019                     !prevRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN)
1020                     && newRestrictions.getBoolean(UserManager.DISALLOW_CONFIG_VPN);
1021             if (newlyEnforced) {
1022                 mDpms.clearUserConfiguredVpns(userId);
1023             }
1024         }
1025 
resetCrossProfileIntentFiltersIfNeeded( int userId, Bundle newRestrictions, Bundle prevRestrictions)1026         private void resetCrossProfileIntentFiltersIfNeeded(
1027                 int userId, Bundle newRestrictions, Bundle prevRestrictions) {
1028             if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions,
1029                     UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE)) {
1030                 final int parentId = mUserManagerInternal.getProfileParentId(userId);
1031                 if (parentId == userId) {
1032                     return;
1033                 }
1034 
1035                 // Always reset filters on the parent user, which handles cross profile intent
1036                 // filters between the parent and its profiles.
1037                 Slogf.i(LOG_TAG, "Resetting cross-profile intent filters on restriction "
1038                         + "change");
1039                 mDpms.resetDefaultCrossProfileIntentFilters(parentId);
1040                 mContext.sendBroadcastAsUser(
1041                         new Intent(DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_APPLIED),
1042                         UserHandle.of(userId));
1043             }
1044         }
1045     }
1046 
clearUserConfiguredVpns(int userId)1047     private void clearUserConfiguredVpns(int userId) {
1048         final String adminConfiguredVpnPkg;
1049         synchronized (getLockObject()) {
1050             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
1051             if (owner == null) {
1052                 Slogf.wtf(LOG_TAG, "Admin not found");
1053                 return;
1054             }
1055             adminConfiguredVpnPkg = owner.mAlwaysOnVpnPackage;
1056         }
1057 
1058         // Clear always-on configuration if it wasn't set by the admin.
1059         if (adminConfiguredVpnPkg == null) {
1060             mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(userId, null, false, null);
1061         }
1062 
1063         // Clear app authorizations to establish VPNs. When DISALLOW_CONFIG_VPN is enforced apps
1064         // won't be able to get those authorizations unless it is configured by an admin.
1065         final List<AppOpsManager.PackageOps> allVpnOps = mInjector.getAppOpsManager()
1066                 .getPackagesForOps(new int[] {AppOpsManager.OP_ACTIVATE_VPN});
1067         if (allVpnOps == null) {
1068             return;
1069         }
1070         for (AppOpsManager.PackageOps pkgOps : allVpnOps) {
1071             if (UserHandle.getUserId(pkgOps.getUid()) != userId
1072                     || pkgOps.getPackageName().equals(adminConfiguredVpnPkg)) {
1073                 continue;
1074             }
1075             if (pkgOps.getOps().size() != 1) {
1076                 Slogf.wtf(LOG_TAG, "Unexpected number of ops returned");
1077                 continue;
1078             }
1079             final @Mode int mode = pkgOps.getOps().get(0).getMode();
1080             if (mode == MODE_ALLOWED) {
1081                 Slogf.i(LOG_TAG, String.format("Revoking VPN authorization for package %s uid %d",
1082                         pkgOps.getPackageName(), pkgOps.getUid()));
1083                 mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN, pkgOps.getUid(),
1084                         pkgOps.getPackageName(), MODE_DEFAULT);
1085             }
1086         }
1087     }
1088 
1089     private final class UserLifecycleListener implements UserManagerInternal.UserLifecycleListener {
1090 
1091         @Override
onUserCreated(UserInfo user, Object token)1092         public void onUserCreated(UserInfo user, Object token) {
1093             mHandler.post(() -> handleNewUserCreated(user, token));
1094         }
1095     }
1096 
handlePackagesChanged(@ullable String packageName, int userHandle)1097     private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1098         boolean removedAdmin = false;
1099         if (VERBOSE_LOG) {
1100             Slogf.d(LOG_TAG, "Handling package changes package " + packageName
1101                     + " for user " + userHandle);
1102         }
1103         DevicePolicyData policy = getUserData(userHandle);
1104         synchronized (getLockObject()) {
1105             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1106                 ActiveAdmin aa = policy.mAdminList.get(i);
1107                 try {
1108                     // If we're checking all packages or if the specific one we're checking matches,
1109                     // then check if the package and receiver still exist.
1110                     final String adminPackage = aa.info.getPackageName();
1111                     if (packageName == null || packageName.equals(adminPackage)) {
1112                         if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1113                                 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1114                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
1115                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1116                                 userHandle) == null) {
1117                             removedAdmin = true;
1118                             policy.mAdminList.remove(i);
1119                             policy.mAdminMap.remove(aa.info.getComponent());
1120                             pushActiveAdminPackagesLocked(userHandle);
1121                             pushMeteredDisabledPackagesLocked(userHandle);
1122                         }
1123                     }
1124                 } catch (RemoteException re) {
1125                     // Shouldn't happen.
1126                 }
1127             }
1128             if (removedAdmin) {
1129                 policy.validatePasswordOwner();
1130             }
1131 
1132             boolean removedDelegate = false;
1133 
1134             // Check if a delegate was removed.
1135             for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1136                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
1137                 if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1138                     policy.mDelegationMap.removeAt(i);
1139                     removedDelegate = true;
1140                 }
1141             }
1142 
1143             // If it's an owner package, we may need to refresh the bound connection.
1144             final ComponentName owner = getOwnerComponent(userHandle);
1145             if ((packageName != null) && (owner != null)
1146                     && (owner.getPackageName().equals(packageName))) {
1147                 startOwnerService(userHandle, "package-broadcast");
1148             }
1149 
1150             // Persist updates if the removed package was an admin or delegate.
1151             if (removedAdmin || removedDelegate) {
1152                 saveSettingsLocked(policy.mUserId);
1153             }
1154         }
1155         if (removedAdmin) {
1156             // The removed admin might have disabled camera, so update user restrictions.
1157             pushUserRestrictions(userHandle);
1158         }
1159     }
1160 
removeCredentialManagementApp(String packageName)1161     private void removeCredentialManagementApp(String packageName) {
1162         mBackgroundHandler.post(() -> {
1163             try (KeyChainConnection connection = mInjector.keyChainBind()) {
1164                 IKeyChainService service = connection.getService();
1165                 if (service.hasCredentialManagementApp()
1166                         && packageName.equals(service.getCredentialManagementAppPackageName())) {
1167                     service.removeCredentialManagementApp();
1168                 }
1169             } catch (RemoteException | InterruptedException | IllegalStateException e) {
1170                 Slogf.e(LOG_TAG, "Unable to remove the credential management app");
1171             }
1172         });
1173     }
1174 
isRemovedPackage(String changedPackage, String targetPackage, int userHandle)1175     private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1176         try {
1177             return targetPackage != null
1178                     && (changedPackage == null || changedPackage.equals(targetPackage))
1179                     && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1180         } catch (RemoteException e) {
1181             // Shouldn't happen
1182         }
1183 
1184         return false;
1185     }
1186 
handleNewPackageInstalled(String packageName, int userHandle)1187     private void handleNewPackageInstalled(String packageName, int userHandle) {
1188         // If personal apps were suspended by the admin, suspend the newly installed one.
1189         if (!getUserData(userHandle).mAppsSuspended) {
1190             return;
1191         }
1192         final String[] packagesToSuspend = { packageName };
1193         // Check if package is considered not suspendable?
1194         if (mInjector.getPackageManager(userHandle)
1195                 .getUnsuspendablePackages(packagesToSuspend).length != 0) {
1196             Slogf.i(LOG_TAG, "Newly installed package is unsuspendable: " + packageName);
1197             return;
1198         }
1199         try {
1200             mIPackageManager.setPackagesSuspendedAsUser(packagesToSuspend, true /*suspend*/,
1201                     null, null, null, PLATFORM_PACKAGE_NAME, userHandle);
1202         } catch (RemoteException ignored) {
1203             // shouldn't happen.
1204         }
1205     }
1206 
1207     @Override
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1208     public void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
1209         CallerIdentity callerIdentity = getCallerIdentity();
1210         Preconditions.checkCallAuthorization(mIsAutomotive || isAdb(callerIdentity), "can only set "
1211                 + "DevicePolicySafetyChecker on automotive builds or from ADB (but caller is %s)",
1212                 callerIdentity);
1213         setDevicePolicySafetyCheckerUnchecked(safetyChecker);
1214     }
1215 
1216     /**
1217      * Used by {@code setDevicePolicySafetyChecker()} above and {@link OneTimeSafetyChecker}.
1218      */
setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker)1219     void setDevicePolicySafetyCheckerUnchecked(DevicePolicySafetyChecker safetyChecker) {
1220         Slogf.i(LOG_TAG, "Setting DevicePolicySafetyChecker as %s", safetyChecker);
1221         mSafetyChecker = safetyChecker;
1222         mInjector.setDevicePolicySafetyChecker(safetyChecker);
1223     }
1224 
1225     /**
1226      * Used by {@link OneTimeSafetyChecker} only.
1227      */
getDevicePolicySafetyChecker()1228     DevicePolicySafetyChecker getDevicePolicySafetyChecker() {
1229         return mSafetyChecker;
1230     }
1231 
1232     /**
1233      * Checks if it's safe to execute the given {@code operation}.
1234      *
1235      * @throws UnsafeStateException if it's not safe to execute the operation.
1236      */
checkCanExecuteOrThrowUnsafe(@evicePolicyOperation int operation)1237     private void checkCanExecuteOrThrowUnsafe(@DevicePolicyOperation int operation) {
1238         int reason = getUnsafeOperationReason(operation);
1239         if (reason == OPERATION_SAFETY_REASON_NONE) return;
1240 
1241         if (mSafetyChecker == null) {
1242             // Happens on CTS after it's set just once (by OneTimeSafetyChecker)
1243             throw new UnsafeStateException(operation, reason);
1244         }
1245         // Let mSafetyChecker customize it (for example, by explaining how to retry)
1246         throw mSafetyChecker.newUnsafeStateException(operation, reason);
1247     }
1248 
1249     /**
1250      * Returns whether it's safe to execute the given {@code operation}, and why.
1251      */
1252     @OperationSafetyReason
getUnsafeOperationReason(@evicePolicyOperation int operation)1253     int getUnsafeOperationReason(@DevicePolicyOperation int operation) {
1254         return mSafetyChecker == null ? OPERATION_SAFETY_REASON_NONE
1255                 : mSafetyChecker.getUnsafeOperationReason(operation);
1256     }
1257 
1258     @Override
setNextOperationSafety(@evicePolicyOperation int operation, @OperationSafetyReason int reason)1259     public void setNextOperationSafety(@DevicePolicyOperation int operation,
1260             @OperationSafetyReason int reason) {
1261         Preconditions.checkCallAuthorization(
1262                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
1263         Slogf.i(LOG_TAG, "setNextOperationSafety(%s, %s)",
1264                 DevicePolicyManager.operationToString(operation),
1265                 DevicePolicyManager.operationSafetyReasonToString(reason));
1266         mSafetyChecker = new OneTimeSafetyChecker(this, operation, reason);
1267     }
1268 
1269     @Override
isSafeOperation(@perationSafetyReason int reason)1270     public boolean isSafeOperation(@OperationSafetyReason int reason) {
1271         if (VERBOSE_LOG) {
1272             Slogf.v(LOG_TAG, "checking isSafeOperation(%s) using mSafetyChecker %s",
1273                     DevicePolicyManager.operationSafetyReasonToString(reason), mSafetyChecker);
1274         }
1275         return mSafetyChecker == null ? true : mSafetyChecker.isSafeOperation(reason);
1276     }
1277 
1278     // Used by DevicePolicyManagerServiceShellCommand
listAllOwners()1279     List<OwnerShellData> listAllOwners() {
1280         Preconditions.checkCallAuthorization(
1281                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
1282         return mInjector.binderWithCleanCallingIdentity(() -> {
1283             SparseArray<DevicePolicyData> userData;
1284 
1285             // Gets the owners of "full users" first (device owner and profile owners)
1286             List<OwnerShellData> owners = mOwners.listAllOwners();
1287             synchronized (getLockObject()) {
1288                 for (int i = 0; i < owners.size(); i++) {
1289                     OwnerShellData owner = owners.get(i);
1290                     owner.isAffiliated = isUserAffiliatedWithDeviceLocked(owner.userId);
1291                 }
1292                 userData = mUserData;
1293             }
1294 
1295             // Then the owners of profile users (managed profiles)
1296             for (int i = 0; i < userData.size(); i++) {
1297                 DevicePolicyData policyData = mUserData.valueAt(i);
1298                 int userId = userData.keyAt(i);
1299                 int parentUserId = mUserManagerInternal.getProfileParentId(userId);
1300                 boolean isProfile = parentUserId != userId;
1301                 if (!isProfile) continue;
1302                 for (int j = 0; j < policyData.mAdminList.size(); j++) {
1303                     ActiveAdmin admin = policyData.mAdminList.get(j);
1304                     OwnerShellData owner = OwnerShellData.forManagedProfileOwner(userId,
1305                             parentUserId, admin.info.getComponent());
1306                     owners.add(owner);
1307                 }
1308             }
1309 
1310             return owners;
1311         });
1312     }
1313 
1314     /**
1315      * Unit test will subclass it to inject mocks.
1316      */
1317     @VisibleForTesting
1318     static class Injector {
1319 
1320         public final Context mContext;
1321 
1322         private @Nullable DevicePolicySafetyChecker mSafetyChecker;
1323 
Injector(Context context)1324         Injector(Context context) {
1325             mContext = context;
1326         }
1327 
hasFeature()1328         public boolean hasFeature() {
1329             return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1330         }
1331 
createContextAsUser(UserHandle user)1332         Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1333             final String packageName = mContext.getPackageName();
1334             return mContext.createPackageContextAsUser(packageName, 0, user);
1335         }
1336 
getResources()1337         Resources getResources() {
1338             return mContext.getResources();
1339         }
1340 
newOwners()1341         Owners newOwners() {
1342             return new Owners(getUserManager(), getUserManagerInternal(),
1343                     getPackageManagerInternal(), getActivityTaskManagerInternal(),
1344                     getActivityManagerInternal());
1345         }
1346 
getUserManager()1347         UserManager getUserManager() {
1348             return UserManager.get(mContext);
1349         }
1350 
getUserManagerInternal()1351         UserManagerInternal getUserManagerInternal() {
1352             return LocalServices.getService(UserManagerInternal.class);
1353         }
1354 
getPackageManagerInternal()1355         PackageManagerInternal getPackageManagerInternal() {
1356             return LocalServices.getService(PackageManagerInternal.class);
1357         }
1358 
getActivityTaskManagerInternal()1359         ActivityTaskManagerInternal getActivityTaskManagerInternal() {
1360             return LocalServices.getService(ActivityTaskManagerInternal.class);
1361         }
1362 
getPermissionControllerManager( @onNull UserHandle user)1363         @NonNull PermissionControllerManager getPermissionControllerManager(
1364                 @NonNull UserHandle user) {
1365             if (user.equals(mContext.getUser())) {
1366                 return mContext.getSystemService(PermissionControllerManager.class);
1367             } else {
1368                 try {
1369                     return mContext.createPackageContextAsUser(mContext.getPackageName(), 0,
1370                             user).getSystemService(PermissionControllerManager.class);
1371                 } catch (NameNotFoundException notPossible) {
1372                     // not possible
1373                     throw new IllegalStateException(notPossible);
1374                 }
1375             }
1376         }
1377 
getUsageStatsManagerInternal()1378         UsageStatsManagerInternal getUsageStatsManagerInternal() {
1379             return LocalServices.getService(UsageStatsManagerInternal.class);
1380         }
1381 
getNetworkPolicyManagerInternal()1382         NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() {
1383             return LocalServices.getService(NetworkPolicyManagerInternal.class);
1384         }
1385 
getNotificationManager()1386         NotificationManager getNotificationManager() {
1387             return mContext.getSystemService(NotificationManager.class);
1388         }
1389 
getIIpConnectivityMetrics()1390         IIpConnectivityMetrics getIIpConnectivityMetrics() {
1391             return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1392                 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1393         }
1394 
getPackageManager()1395         PackageManager getPackageManager() {
1396             return mContext.getPackageManager();
1397         }
1398 
getPackageManager(int userId)1399         PackageManager getPackageManager(int userId) {
1400             return mContext
1401                     .createContextAsUser(UserHandle.of(userId), 0 /* flags */).getPackageManager();
1402         }
1403 
getPowerManagerInternal()1404         PowerManagerInternal getPowerManagerInternal() {
1405             return LocalServices.getService(PowerManagerInternal.class);
1406         }
1407 
getTelephonyManager()1408         TelephonyManager getTelephonyManager() {
1409             return mContext.getSystemService(TelephonyManager.class);
1410         }
1411 
getTrustManager()1412         TrustManager getTrustManager() {
1413             return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1414         }
1415 
getAlarmManager()1416         AlarmManager getAlarmManager() {
1417             return mContext.getSystemService(AlarmManager.class);
1418         }
1419 
getConnectivityManager()1420         ConnectivityManager getConnectivityManager() {
1421             return mContext.getSystemService(ConnectivityManager.class);
1422         }
1423 
getVpnManager()1424         VpnManager getVpnManager() {
1425             return mContext.getSystemService(VpnManager.class);
1426         }
1427 
getLocationManager()1428         LocationManager getLocationManager() {
1429             return mContext.getSystemService(LocationManager.class);
1430         }
1431 
getIWindowManager()1432         IWindowManager getIWindowManager() {
1433             return IWindowManager.Stub
1434                     .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1435         }
1436 
getIActivityManager()1437         IActivityManager getIActivityManager() {
1438             return ActivityManager.getService();
1439         }
1440 
getIActivityTaskManager()1441         IActivityTaskManager getIActivityTaskManager() {
1442             return ActivityTaskManager.getService();
1443         }
1444 
getActivityManagerInternal()1445         ActivityManagerInternal getActivityManagerInternal() {
1446             return LocalServices.getService(ActivityManagerInternal.class);
1447         }
1448 
getIPackageManager()1449         IPackageManager getIPackageManager() {
1450             return AppGlobals.getPackageManager();
1451         }
1452 
getIPermissionManager()1453         IPermissionManager getIPermissionManager() {
1454             return AppGlobals.getPermissionManager();
1455         }
1456 
getIBackupManager()1457         IBackupManager getIBackupManager() {
1458             return IBackupManager.Stub.asInterface(
1459                     ServiceManager.getService(Context.BACKUP_SERVICE));
1460         }
1461 
getIAudioService()1462         IAudioService getIAudioService() {
1463             return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1464         }
1465 
getPersistentDataBlockManagerInternal()1466         PersistentDataBlockManagerInternal getPersistentDataBlockManagerInternal() {
1467             return LocalServices.getService(PersistentDataBlockManagerInternal.class);
1468         }
1469 
getAppOpsManager()1470         AppOpsManager getAppOpsManager() {
1471             return mContext.getSystemService(AppOpsManager.class);
1472         }
1473 
getLockSettingsInternal()1474         LockSettingsInternal getLockSettingsInternal() {
1475             return LocalServices.getService(LockSettingsInternal.class);
1476         }
1477 
getCrossProfileApps()1478         CrossProfileApps getCrossProfileApps() {
1479             return mContext.getSystemService(CrossProfileApps.class);
1480         }
1481 
hasUserSetupCompleted(DevicePolicyData userData)1482         boolean hasUserSetupCompleted(DevicePolicyData userData) {
1483             return userData.mUserSetupComplete;
1484         }
1485 
isBuildDebuggable()1486         boolean isBuildDebuggable() {
1487             return Build.IS_DEBUGGABLE;
1488         }
1489 
newLockPatternUtils()1490         LockPatternUtils newLockPatternUtils() {
1491             return new LockPatternUtils(mContext);
1492         }
1493 
storageManagerIsFileBasedEncryptionEnabled()1494         boolean storageManagerIsFileBasedEncryptionEnabled() {
1495             return StorageManager.isFileEncryptedNativeOnly();
1496         }
1497 
storageManagerIsNonDefaultBlockEncrypted()1498         boolean storageManagerIsNonDefaultBlockEncrypted() {
1499             final long identity = Binder.clearCallingIdentity();
1500             try {
1501                 return StorageManager.isNonDefaultBlockEncrypted();
1502             } finally {
1503                 Binder.restoreCallingIdentity(identity);
1504             }
1505         }
1506 
storageManagerIsEncrypted()1507         boolean storageManagerIsEncrypted() {
1508             return StorageManager.isEncrypted();
1509         }
1510 
storageManagerIsEncryptable()1511         boolean storageManagerIsEncryptable() {
1512             return StorageManager.isEncryptable();
1513         }
1514 
getMyLooper()1515         Looper getMyLooper() {
1516             return Looper.myLooper();
1517         }
1518 
getWifiManager()1519         WifiManager getWifiManager() {
1520             return mContext.getSystemService(WifiManager.class);
1521         }
1522 
getUsbManager()1523         UsbManager getUsbManager() {
1524             return mContext.getSystemService(UsbManager.class);
1525         }
1526 
1527         @SuppressWarnings("AndroidFrameworkBinderIdentity")
binderClearCallingIdentity()1528         long binderClearCallingIdentity() {
1529             return Binder.clearCallingIdentity();
1530         }
1531 
1532         @SuppressWarnings("AndroidFrameworkBinderIdentity")
binderRestoreCallingIdentity(long token)1533         void binderRestoreCallingIdentity(long token) {
1534             Binder.restoreCallingIdentity(token);
1535         }
1536 
binderGetCallingUid()1537         int binderGetCallingUid() {
1538             return Binder.getCallingUid();
1539         }
1540 
binderGetCallingPid()1541         int binderGetCallingPid() {
1542             return Binder.getCallingPid();
1543         }
1544 
binderGetCallingUserHandle()1545         UserHandle binderGetCallingUserHandle() {
1546             return Binder.getCallingUserHandle();
1547         }
1548 
binderIsCallingUidMyUid()1549         boolean binderIsCallingUidMyUid() {
1550             return getCallingUid() == Process.myUid();
1551         }
1552 
binderWithCleanCallingIdentity(@onNull ThrowingRunnable action)1553         void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
1554              Binder.withCleanCallingIdentity(action);
1555         }
1556 
binderWithCleanCallingIdentity(@onNull ThrowingSupplier<T> action)1557         final <T> T binderWithCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
1558             return Binder.withCleanCallingIdentity(action);
1559         }
1560 
userHandleGetCallingUserId()1561         final int userHandleGetCallingUserId() {
1562             return UserHandle.getUserId(binderGetCallingUid());
1563         }
1564 
environmentGetUserSystemDirectory(int userId)1565         File environmentGetUserSystemDirectory(int userId) {
1566             return Environment.getUserSystemDirectory(userId);
1567         }
1568 
powerManagerGoToSleep(long time, int reason, int flags)1569         void powerManagerGoToSleep(long time, int reason, int flags) {
1570             mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1571         }
1572 
powerManagerReboot(String reason)1573         void powerManagerReboot(String reason) {
1574             mContext.getSystemService(PowerManager.class).reboot(reason);
1575         }
1576 
recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)1577         boolean recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1578                 boolean wipeEuicc, boolean wipeExtRequested, boolean wipeResetProtectionData)
1579                         throws IOException {
1580             return FactoryResetter.newBuilder(mContext).setSafetyChecker(mSafetyChecker)
1581                     .setReason(reason).setShutdown(shutdown).setForce(force).setWipeEuicc(wipeEuicc)
1582                     .setWipeAdoptableStorage(wipeExtRequested)
1583                     .setWipeFactoryResetProtection(wipeResetProtectionData)
1584                     .build().factoryReset();
1585         }
1586 
systemPropertiesGetBoolean(String key, boolean def)1587         boolean systemPropertiesGetBoolean(String key, boolean def) {
1588             return SystemProperties.getBoolean(key, def);
1589         }
1590 
systemPropertiesGetLong(String key, long def)1591         long systemPropertiesGetLong(String key, long def) {
1592             return SystemProperties.getLong(key, def);
1593         }
1594 
systemPropertiesGet(String key, String def)1595         String systemPropertiesGet(String key, String def) {
1596             return SystemProperties.get(key, def);
1597         }
1598 
systemPropertiesGet(String key)1599         String systemPropertiesGet(String key) {
1600             return SystemProperties.get(key);
1601         }
1602 
systemPropertiesSet(String key, String value)1603         void systemPropertiesSet(String key, String value) {
1604             SystemProperties.set(key, value);
1605         }
1606 
userManagerIsHeadlessSystemUserMode()1607         boolean userManagerIsHeadlessSystemUserMode() {
1608             return UserManager.isHeadlessSystemUserMode();
1609         }
1610 
getDevicePolicyFilePathForSystemUser()1611         String getDevicePolicyFilePathForSystemUser() {
1612             return "/data/system/";
1613         }
1614 
1615         @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
pendingIntentGetActivityAsUser(Context context, int requestCode, @NonNull Intent intent, int flags, Bundle options, UserHandle user)1616         PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1617                 @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
1618             return PendingIntent.getActivityAsUser(
1619                     context, requestCode, intent, flags, options, user);
1620         }
1621 
1622         @SuppressWarnings("AndroidFrameworkPendingIntentMutability")
pendingIntentGetBroadcast( Context context, int requestCode, Intent intent, int flags)1623         PendingIntent pendingIntentGetBroadcast(
1624                 Context context, int requestCode, Intent intent, int flags) {
1625             return PendingIntent.getBroadcast(context, requestCode, intent, flags);
1626         }
1627 
registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer, int userHandle)1628         void registerContentObserver(Uri uri, boolean notifyForDescendents,
1629                 ContentObserver observer, int userHandle) {
1630             mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1631                     observer, userHandle);
1632         }
1633 
settingsSecureGetIntForUser(String name, int def, int userHandle)1634         int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1635             return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1636                     name, def, userHandle);
1637         }
1638 
settingsSecureGetStringForUser(String name, int userHandle)1639         String settingsSecureGetStringForUser(String name, int userHandle) {
1640             return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
1641                     userHandle);
1642         }
1643 
settingsSecurePutIntForUser(String name, int value, int userHandle)1644         void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1645             Settings.Secure.putIntForUser(mContext.getContentResolver(),
1646                     name, value, userHandle);
1647         }
1648 
settingsSecurePutStringForUser(String name, String value, int userHandle)1649         void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1650             Settings.Secure.putStringForUser(mContext.getContentResolver(),
1651                     name, value, userHandle);
1652         }
1653 
settingsGlobalPutStringForUser(String name, String value, int userHandle)1654         void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1655             Settings.Global.putStringForUser(mContext.getContentResolver(),
1656                     name, value, userHandle);
1657         }
1658 
settingsSecurePutInt(String name, int value)1659         void settingsSecurePutInt(String name, int value) {
1660             Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1661         }
1662 
settingsGlobalGetInt(String name, int def)1663         int settingsGlobalGetInt(String name, int def) {
1664             return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1665         }
1666 
1667         @Nullable
settingsGlobalGetString(String name)1668         String settingsGlobalGetString(String name) {
1669             return Settings.Global.getString(mContext.getContentResolver(), name);
1670         }
1671 
settingsGlobalPutInt(String name, int value)1672         void settingsGlobalPutInt(String name, int value) {
1673             Settings.Global.putInt(mContext.getContentResolver(), name, value);
1674         }
1675 
settingsSecurePutString(String name, String value)1676         void settingsSecurePutString(String name, String value) {
1677             Settings.Secure.putString(mContext.getContentResolver(), name, value);
1678         }
1679 
settingsGlobalPutString(String name, String value)1680         void settingsGlobalPutString(String name, String value) {
1681             Settings.Global.putString(mContext.getContentResolver(), name, value);
1682         }
1683 
settingsSystemPutStringForUser(String name, String value, int userId)1684         void settingsSystemPutStringForUser(String name, String value, int userId) {
1685           Settings.System.putStringForUser(
1686               mContext.getContentResolver(), name, value, userId);
1687         }
1688 
securityLogSetLoggingEnabledProperty(boolean enabled)1689         void securityLogSetLoggingEnabledProperty(boolean enabled) {
1690             SecurityLog.setLoggingEnabledProperty(enabled);
1691         }
1692 
securityLogGetLoggingEnabledProperty()1693         boolean securityLogGetLoggingEnabledProperty() {
1694             return SecurityLog.getLoggingEnabledProperty();
1695         }
1696 
securityLogIsLoggingEnabled()1697         boolean securityLogIsLoggingEnabled() {
1698             return SecurityLog.isLoggingEnabled();
1699         }
1700 
keyChainBind()1701         KeyChainConnection keyChainBind() throws InterruptedException {
1702             return KeyChain.bind(mContext);
1703         }
1704 
keyChainBindAsUser(UserHandle user)1705         KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
1706             return KeyChain.bindAsUser(mContext, user);
1707         }
1708 
postOnSystemServerInitThreadPool(Runnable runnable)1709         void postOnSystemServerInitThreadPool(Runnable runnable) {
1710             SystemServerInitThreadPool.submit(runnable, LOG_TAG);
1711         }
1712 
newTransferOwnershipMetadataManager()1713         public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() {
1714             return new TransferOwnershipMetadataManager();
1715         }
1716 
runCryptoSelfTest()1717         public void runCryptoSelfTest() {
1718             CryptoTestHelper.runAndLogSelfTest();
1719         }
1720 
getPersonalAppsForSuspension(@serIdInt int userId)1721         public String[] getPersonalAppsForSuspension(@UserIdInt int userId) {
1722             return PersonalAppsSuspensionHelper.forUser(mContext, userId)
1723                     .getPersonalAppsForSuspension();
1724         }
1725 
systemCurrentTimeMillis()1726         public long systemCurrentTimeMillis() {
1727             return System.currentTimeMillis();
1728         }
1729 
isChangeEnabled(long changeId, String packageName, int userId)1730         public boolean isChangeEnabled(long changeId, String packageName, int userId) {
1731             return CompatChanges.isChangeEnabled(changeId, packageName, UserHandle.of(userId));
1732         }
1733 
setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker)1734         void setDevicePolicySafetyChecker(DevicePolicySafetyChecker safetyChecker) {
1735             mSafetyChecker = safetyChecker;
1736         }
1737     }
1738 
1739     /**
1740      * Instantiates the service.
1741      */
DevicePolicyManagerService(Context context)1742     public DevicePolicyManagerService(Context context) {
1743         this(new Injector(context));
1744     }
1745 
1746     @VisibleForTesting
DevicePolicyManagerService(Injector injector)1747     DevicePolicyManagerService(Injector injector) {
1748         mInjector = injector;
1749         mContext = Objects.requireNonNull(injector.mContext);
1750         mHandler = new Handler(Objects.requireNonNull(injector.getMyLooper()));
1751 
1752         mConstantsObserver = new DevicePolicyConstantsObserver(mHandler);
1753         mConstantsObserver.register();
1754         mConstants = loadConstants();
1755 
1756         mOwners = Objects.requireNonNull(injector.newOwners());
1757 
1758         mUserManager = Objects.requireNonNull(injector.getUserManager());
1759         mUserManagerInternal = Objects.requireNonNull(injector.getUserManagerInternal());
1760         mUsageStatsManagerInternal = Objects.requireNonNull(
1761                 injector.getUsageStatsManagerInternal());
1762         mIPackageManager = Objects.requireNonNull(injector.getIPackageManager());
1763         mIPermissionManager = Objects.requireNonNull(injector.getIPermissionManager());
1764         mTelephonyManager = Objects.requireNonNull(injector.getTelephonyManager());
1765 
1766         mLocalService = new LocalService();
1767         mLockPatternUtils = injector.newLockPatternUtils();
1768         mLockSettingsInternal = injector.getLockSettingsInternal();
1769         // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
1770         mSecurityLogMonitor = new SecurityLogMonitor(this);
1771 
1772         mHasFeature = mInjector.hasFeature();
1773         mIsWatch = mInjector.getPackageManager()
1774                 .hasSystemFeature(PackageManager.FEATURE_WATCH);
1775         mHasTelephonyFeature = mInjector.getPackageManager()
1776                 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
1777         mIsAutomotive = mInjector.getPackageManager()
1778                 .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
1779         mBackgroundHandler = BackgroundThread.getHandler();
1780 
1781         // Needed when mHasFeature == false, because it controls the certificate warning text.
1782         mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
1783 
1784         mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
1785         mOverlayPackagesProvider = new OverlayPackagesProvider(mContext);
1786         mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager();
1787         mBugreportCollectionManager = new RemoteBugreportManager(this, mInjector);
1788 
1789         // "Lite" interface is available even when the device doesn't have the feature
1790         LocalServices.addService(DevicePolicyManagerLiteInternal.class, mLocalService);
1791         if (!mHasFeature) {
1792             // Skip the rest of the initialization
1793             mSetupContentObserver = null;
1794             return;
1795         }
1796 
1797         IntentFilter filter = new IntentFilter();
1798         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1799         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1800         filter.addAction(ACTION_TURN_PROFILE_ON_NOTIFICATION);
1801         filter.addAction(ACTION_PROFILE_OFF_DEADLINE);
1802         filter.addAction(Intent.ACTION_USER_ADDED);
1803         filter.addAction(Intent.ACTION_USER_REMOVED);
1804         filter.addAction(Intent.ACTION_USER_STARTED);
1805         filter.addAction(Intent.ACTION_USER_STOPPED);
1806         filter.addAction(Intent.ACTION_USER_SWITCHED);
1807         filter.addAction(Intent.ACTION_USER_UNLOCKED);
1808         filter.addAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
1809         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1810         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1811         filter = new IntentFilter();
1812         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1813         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1814         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1815         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1816         filter.addDataScheme("package");
1817         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1818         filter = new IntentFilter();
1819         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1820         filter.addAction(Intent.ACTION_TIME_CHANGED);
1821         filter.addAction(Intent.ACTION_DATE_CHANGED);
1822         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1823 
1824         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1825 
1826         mSetupContentObserver = new SetupContentObserver(mHandler);
1827 
1828         mUserManagerInternal.addUserRestrictionsListener(
1829                 new RestrictionsListener(mContext, mUserManagerInternal, this));
1830         mUserManagerInternal.addUserLifecycleListener(new UserLifecycleListener());
1831 
1832         loadOwners();
1833     }
1834 
1835     /**
1836      * Creates and loads the policy data from xml.
1837      * @param userHandle the user for whom to load the policy data
1838      * @return
1839      */
1840     @NonNull
getUserData(int userHandle)1841     DevicePolicyData getUserData(int userHandle) {
1842         synchronized (getLockObject()) {
1843             DevicePolicyData policy = mUserData.get(userHandle);
1844             if (policy == null) {
1845                 policy = new DevicePolicyData(userHandle);
1846                 mUserData.append(userHandle, policy);
1847                 loadSettingsLocked(policy, userHandle);
1848                 if (userHandle == UserHandle.USER_SYSTEM) {
1849                     mStateCache.setDeviceProvisioned(policy.mUserSetupComplete);
1850                 }
1851 
1852                 migrateDeviceOwnerProtectedPackagesToOwners(userHandle, policy);
1853             }
1854             return policy;
1855         }
1856     }
1857 
1858     /**
1859      * Only used by {@link #getUserData(int)} to migrate <b>existing</b> device owner protected
1860      * packages that were stored in {@link DevicePolicyData#mUserControlDisabledPackages} to
1861      * {@link Owners} because the device owner protected packages are now stored on a per device
1862      * owner basis instead of on a per user basis.
1863      *
1864      * Any calls to {@link #setUserControlDisabledPackages(ComponentName, List)} would now store
1865      * the device owner protected packages in {@link Owners} instead of {@link DevicePolicyData}.
1866      * @param userHandle The device owner user
1867      * @param policy The policy data of the device owner user
1868      */
migrateDeviceOwnerProtectedPackagesToOwners( int userHandle, DevicePolicyData policy)1869     private void migrateDeviceOwnerProtectedPackagesToOwners(
1870             int userHandle, DevicePolicyData policy) {
1871         ComponentName deviceOwnerComponent = getOwnerComponent(userHandle);
1872         if (isDeviceOwner(deviceOwnerComponent, userHandle)
1873                 && !policy.mUserControlDisabledPackages.isEmpty()) {
1874             mOwners.setDeviceOwnerProtectedPackages(
1875                     deviceOwnerComponent.getPackageName(),
1876                     policy.mUserControlDisabledPackages);
1877 
1878             policy.mUserControlDisabledPackages = new ArrayList<>();
1879             saveSettingsLocked(userHandle);
1880         }
1881     }
1882 
1883     /**
1884      * Creates and loads the policy data from xml for data that is shared between
1885      * various profiles of a user. In contrast to {@link #getUserData(int)}
1886      * it allows access to data of users other than the calling user.
1887      *
1888      * This function should only be used for shared data, e.g. everything regarding
1889      * passwords and should be removed once multiple screen locks are present.
1890      * @param userHandle the user for whom to load the policy data
1891      * @return
1892      */
getUserDataUnchecked(int userHandle)1893     DevicePolicyData getUserDataUnchecked(int userHandle) {
1894         return mInjector.binderWithCleanCallingIdentity(() -> getUserData(userHandle));
1895     }
1896 
removeUserData(int userHandle)1897     void removeUserData(int userHandle) {
1898         final boolean isOrgOwned;
1899         synchronized (getLockObject()) {
1900             if (userHandle == UserHandle.USER_SYSTEM) {
1901                 Slogf.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1902                 return;
1903             }
1904             updatePasswordQualityCacheForUserGroup(userHandle);
1905             mPolicyCache.onUserRemoved(userHandle);
1906 
1907             isOrgOwned = mOwners.isProfileOwnerOfOrganizationOwnedDevice(userHandle);
1908 
1909             mOwners.removeProfileOwner(userHandle);
1910             mOwners.writeProfileOwner(userHandle);
1911 
1912             DevicePolicyData policy = mUserData.get(userHandle);
1913             if (policy != null) {
1914                 mUserData.remove(userHandle);
1915             }
1916 
1917             File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1918                     DEVICE_POLICIES_XML);
1919             policyFile.delete();
1920             Slogf.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1921         }
1922         if (isOrgOwned) {
1923             final UserInfo primaryUser = mUserManager.getPrimaryUser();
1924             if (primaryUser != null) {
1925                 clearOrgOwnedProfileOwnerDeviceWidePolicies(primaryUser.id);
1926             } else {
1927                 Slogf.wtf(LOG_TAG, "Was unable to get primary user.");
1928             }
1929         }
1930     }
1931 
1932     /**
1933      * Load information about device and profile owners of the device, populating mOwners and
1934      * pushing owner info to other system services. This is called at a fairly early stage of
1935      * system server initialiation (via DevicePolicyManagerService's ctor), so care should to
1936      * be taken to not interact with system services that are initialiated after DPMS.
1937      * onLockSettingsReady() is a safer place to do initialization work not critical during
1938      * the first boot stage.
1939      * Note this only loads the list of owners, and not their actual policy (DevicePolicyData).
1940      * The policy is normally loaded lazily when it's first accessed. In several occasions
1941      * the list of owners is necessary for providing callers with aggregated policies across
1942      * multiple owners, hence the owner list is loaded as part of DPMS's construction here.
1943      */
loadOwners()1944     void loadOwners() {
1945         synchronized (getLockObject()) {
1946             mOwners.load();
1947             setDeviceOwnershipSystemPropertyLocked();
1948             findOwnerComponentIfNecessaryLocked();
1949 
1950             // TODO PO may not have a class name either due to b/17652534.  Address that too.
1951             updateDeviceOwnerLocked();
1952         }
1953     }
1954 
1955     /**
1956      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
1957      */
getCallerIdentity()1958     private CallerIdentity getCallerIdentity() {
1959         return getCallerIdentity(null, null);
1960     }
1961 
1962     /**
1963      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
1964      */
getCallerIdentity(@ullable String callerPackage)1965     private CallerIdentity getCallerIdentity(@Nullable String callerPackage) {
1966 
1967         return getCallerIdentity(null, callerPackage);
1968     }
1969 
1970     /**
1971      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
1972      * The component name should be an active admin for the calling user.
1973      */
1974     @VisibleForTesting
getCallerIdentity(@ullable ComponentName adminComponent)1975     CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent) {
1976         return getCallerIdentity(adminComponent, null);
1977     }
1978 
1979     /**
1980      * Creates a new {@link CallerIdentity} object to represent the caller's identity.
1981      * If {@code adminComponent} is provided, it's validated against the list of known
1982      * active admins and caller uid. If {@code callerPackage} is provided, it's validated
1983      * against the caller uid. If a valid {@code adminComponent} is provided but not
1984      * {@code callerPackage}, the package name of the {@code adminComponent} is used instead.
1985      */
1986     @VisibleForTesting
getCallerIdentity(@ullable ComponentName adminComponent, @Nullable String callerPackage)1987     CallerIdentity getCallerIdentity(@Nullable ComponentName adminComponent,
1988             @Nullable String callerPackage) {
1989         final int callerUid = mInjector.binderGetCallingUid();
1990 
1991         if (callerPackage != null) {
1992             if (!isCallingFromPackage(callerPackage, callerUid)) {
1993                 throw new SecurityException(
1994                         String.format("Caller with uid %d is not %s", callerUid, callerPackage));
1995             }
1996         }
1997 
1998         if (adminComponent != null) {
1999             final DevicePolicyData policy = getUserData(UserHandle.getUserId(callerUid));
2000             ActiveAdmin admin = policy.mAdminMap.get(adminComponent);
2001 
2002             // Throwing combined exception message for both the cases here, because from different
2003             // security exceptions it could be deduced if particular package is admin package.
2004             if (admin == null || admin.getUid() != callerUid) {
2005                 throw new SecurityException(String.format(
2006                         "Admin %s does not exist or is not owned by uid %d", adminComponent,
2007                         callerUid));
2008             }
2009             if (callerPackage != null) {
2010                 Preconditions.checkArgument(callerPackage.equals(adminComponent.getPackageName()));
2011             } else {
2012                 callerPackage = adminComponent.getPackageName();
2013             }
2014         }
2015 
2016         return new CallerIdentity(callerUid, callerPackage, adminComponent);
2017     }
2018 
2019     /**
2020      * Checks if the device is in COMP mode, and if so migrates it to managed profile on a
2021      * corporate owned device.
2022      */
2023     @GuardedBy("getLockObject()")
migrateToProfileOnOrganizationOwnedDeviceIfCompLocked()2024     private void migrateToProfileOnOrganizationOwnedDeviceIfCompLocked() {
2025         if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Checking whether we need to migrate COMP ");
2026         final int doUserId = mOwners.getDeviceOwnerUserId();
2027         if (doUserId == UserHandle.USER_NULL) {
2028             if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping migration.");
2029             return;
2030         }
2031 
2032         final List<UserInfo> profiles = mUserManager.getProfiles(doUserId);
2033         if (profiles.size() != 2) {
2034             if (profiles.size() == 1) {
2035                 if (VERBOSE_LOG) Slogf.d(LOG_TAG, "Profile not found, skipping migration.");
2036             } else {
2037                 Slogf.wtf(LOG_TAG, "Found " + profiles.size() + " profiles, skipping migration");
2038             }
2039             return;
2040         }
2041 
2042         final int poUserId = getManagedUserId(doUserId);
2043         if (poUserId < 0) {
2044             Slogf.wtf(LOG_TAG, "Found DO and a profile, but it is not managed, skipping migration");
2045             return;
2046         }
2047 
2048         final ActiveAdmin doAdmin = getDeviceOwnerAdminLocked();
2049         final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(poUserId);
2050         if (doAdmin == null || poAdmin == null) {
2051             Slogf.wtf(LOG_TAG, "Failed to get either PO or DO admin, aborting migration.");
2052             return;
2053         }
2054 
2055         final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent();
2056         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(poUserId);
2057         if (doAdminComponent == null || poAdminComponent == null) {
2058             Slogf.wtf(LOG_TAG, "Cannot find PO or DO component name, aborting migration.");
2059             return;
2060         }
2061         if (!doAdminComponent.getPackageName().equals(poAdminComponent.getPackageName())) {
2062             Slogf.e(LOG_TAG, "DO and PO are different packages, aborting migration.");
2063             return;
2064         }
2065 
2066         Slogf.i(LOG_TAG, "Migrating COMP to PO on a corp owned device; primary user: %d; "
2067                 + "profile: %d", doUserId, poUserId);
2068 
2069         Slogf.i(LOG_TAG, "Giving the PO additional power...");
2070         markProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(poAdminComponent, poUserId);
2071         Slogf.i(LOG_TAG, "Migrating DO policies to PO...");
2072         moveDoPoliciesToProfileParentAdminLocked(doAdmin, poAdmin.getParentActiveAdmin());
2073         migratePersonalAppSuspensionLocked(doUserId, poUserId, poAdmin);
2074         saveSettingsLocked(poUserId);
2075         Slogf.i(LOG_TAG, "Clearing the DO...");
2076         final ComponentName doAdminReceiver = doAdmin.info.getComponent();
2077         clearDeviceOwnerLocked(doAdmin, doUserId);
2078         Slogf.i(LOG_TAG, "Removing admin artifacts...");
2079         removeAdminArtifacts(doAdminReceiver, doUserId);
2080         Slogf.i(LOG_TAG, "Uninstalling the DO...");
2081         uninstallOrDisablePackage(doAdminComponent.getPackageName(), doUserId);
2082         Slogf.i(LOG_TAG, "Migration complete.");
2083 
2084         // Note: KeyChain keys are not removed and will remain accessible for the apps that have
2085         // been given grants to use them.
2086 
2087         DevicePolicyEventLogger
2088                 .createEvent(DevicePolicyEnums.COMP_TO_ORG_OWNED_PO_MIGRATED)
2089                 .setAdmin(poAdminComponent)
2090                 .write();
2091     }
2092 
2093     @GuardedBy("getLockObject()")
migratePersonalAppSuspensionLocked( int doUserId, int poUserId, ActiveAdmin poAdmin)2094     private void migratePersonalAppSuspensionLocked(
2095             int doUserId, int poUserId, ActiveAdmin poAdmin) {
2096         final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
2097         if (!pmi.isSuspendingAnyPackages(PLATFORM_PACKAGE_NAME, doUserId)) {
2098             Slogf.i(LOG_TAG, "DO is not suspending any apps.");
2099             return;
2100         }
2101 
2102         if (getTargetSdk(poAdmin.info.getPackageName(), poUserId) >= Build.VERSION_CODES.R) {
2103             Slogf.i(LOG_TAG, "PO is targeting R+, keeping personal apps suspended.");
2104             getUserData(doUserId).mAppsSuspended = true;
2105             poAdmin.mSuspendPersonalApps = true;
2106         } else {
2107             Slogf.i(LOG_TAG, "PO isn't targeting R+, unsuspending personal apps.");
2108             pmi.unsuspendForSuspendingPackage(PLATFORM_PACKAGE_NAME, doUserId);
2109         }
2110     }
2111 
uninstallOrDisablePackage(String packageName, @UserIdInt int userId)2112     private void uninstallOrDisablePackage(String packageName, @UserIdInt int userId) {
2113         final ApplicationInfo appInfo;
2114         try {
2115             appInfo = mIPackageManager.getApplicationInfo(
2116                     packageName, MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId);
2117         } catch (RemoteException e) {
2118             // Shouldn't happen.
2119             return;
2120         }
2121         if (appInfo == null) {
2122             Slogf.wtf(LOG_TAG, "Failed to get package info for " + packageName);
2123             return;
2124         }
2125         if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2126             Slogf.i(LOG_TAG, "Package %s is pre-installed, marking disabled until used",
2127                     packageName);
2128             mContext.getPackageManager().setApplicationEnabledSetting(packageName,
2129                     PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED, /* flags= */ 0);
2130             return;
2131         }
2132 
2133         final IIntentSender.Stub mLocalSender = new IIntentSender.Stub() {
2134             @Override
2135             public void send(int code, Intent intent, String resolvedType, IBinder allowlistToken,
2136                     IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
2137                 final int status = intent.getIntExtra(
2138                         PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
2139                 if (status == PackageInstaller.STATUS_SUCCESS) {
2140                     Slogf.i(LOG_TAG, "Package %s uninstalled for user %d", packageName, userId);
2141                 } else {
2142                     Slogf.e(LOG_TAG, "Failed to uninstall %s; status: %d", packageName, status);
2143                 }
2144             }
2145         };
2146 
2147         final PackageInstaller pi = mInjector.getPackageManager(userId).getPackageInstaller();
2148         pi.uninstall(packageName, /* flags= */ 0, new IntentSender((IIntentSender) mLocalSender));
2149     }
2150 
2151     @GuardedBy("getLockObject()")
moveDoPoliciesToProfileParentAdminLocked( ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2152     private void moveDoPoliciesToProfileParentAdminLocked(
2153             ActiveAdmin doAdmin, ActiveAdmin parentAdmin) {
2154         // The following policies can be already controlled via parent instance, skip if so.
2155         if (parentAdmin.mPasswordPolicy.quality == PASSWORD_QUALITY_UNSPECIFIED) {
2156             parentAdmin.mPasswordPolicy = doAdmin.mPasswordPolicy;
2157         }
2158         if (parentAdmin.passwordHistoryLength == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) {
2159             parentAdmin.passwordHistoryLength = doAdmin.passwordHistoryLength;
2160         }
2161         if (parentAdmin.passwordExpirationTimeout == ActiveAdmin.DEF_PASSWORD_HISTORY_LENGTH) {
2162             parentAdmin.passwordExpirationTimeout = doAdmin.passwordExpirationTimeout;
2163         }
2164         if (parentAdmin.maximumFailedPasswordsForWipe
2165                 == ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
2166             parentAdmin.maximumFailedPasswordsForWipe = doAdmin.maximumFailedPasswordsForWipe;
2167         }
2168         if (parentAdmin.maximumTimeToUnlock == ActiveAdmin.DEF_MAXIMUM_TIME_TO_UNLOCK) {
2169             parentAdmin.maximumTimeToUnlock = doAdmin.maximumTimeToUnlock;
2170         }
2171         if (parentAdmin.strongAuthUnlockTimeout
2172                 == DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
2173             parentAdmin.strongAuthUnlockTimeout = doAdmin.strongAuthUnlockTimeout;
2174         }
2175         parentAdmin.disabledKeyguardFeatures |=
2176                 doAdmin.disabledKeyguardFeatures & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
2177 
2178         parentAdmin.trustAgentInfos.putAll(doAdmin.trustAgentInfos);
2179 
2180         // The following policies weren't available to PO, but will be available after migration.
2181         parentAdmin.disableCamera = doAdmin.disableCamera;
2182         parentAdmin.disableScreenCapture = doAdmin.disableScreenCapture;
2183         parentAdmin.accountTypesWithManagementDisabled.addAll(
2184                 doAdmin.accountTypesWithManagementDisabled);
2185 
2186         moveDoUserRestrictionsToCopeParent(doAdmin, parentAdmin);
2187 
2188         // From Android 11, {@link setAutoTimeRequired} is no longer used. The user restriction
2189         // {@link UserManager#DISALLOW_CONFIG_DATE_TIME} should be used to enforce auto time
2190         // settings instead.
2191         if (doAdmin.requireAutoTime) {
2192             parentAdmin.ensureUserRestrictions().putBoolean(
2193                     UserManager.DISALLOW_CONFIG_DATE_TIME, true);
2194         }
2195     }
2196 
moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin)2197     private void moveDoUserRestrictionsToCopeParent(ActiveAdmin doAdmin, ActiveAdmin parentAdmin) {
2198         if (doAdmin.userRestrictions == null) {
2199             return;
2200         }
2201         for (final String restriction : doAdmin.userRestrictions.keySet()) {
2202             if (UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(restriction)) {
2203                 parentAdmin.ensureUserRestrictions().putBoolean(
2204                         restriction, doAdmin.userRestrictions.getBoolean(restriction));
2205             }
2206         }
2207     }
2208 
2209     /**
2210      * If the device is in Device Owner mode, apply the restriction on adding
2211      * a managed profile.
2212      */
2213     @GuardedBy("getLockObject()")
applyManagedProfileRestrictionIfDeviceOwnerLocked()2214     private void applyManagedProfileRestrictionIfDeviceOwnerLocked() {
2215         final int doUserId = mOwners.getDeviceOwnerUserId();
2216         if (doUserId == UserHandle.USER_NULL) {
2217             if (VERBOSE_LOG) Slogf.d(LOG_TAG, "No DO found, skipping application of restriction.");
2218             return;
2219         }
2220 
2221         final UserHandle doUserHandle = UserHandle.of(doUserId);
2222         // Set the restriction if not set.
2223         if (!mUserManager.hasUserRestriction(
2224                 UserManager.DISALLOW_ADD_MANAGED_PROFILE, doUserHandle)) {
2225             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
2226                     doUserHandle);
2227         }
2228     }
2229 
2230     /** Apply default restrictions that haven't been applied to profile owners yet. */
maybeSetDefaultProfileOwnerUserRestrictions()2231     private void maybeSetDefaultProfileOwnerUserRestrictions() {
2232         synchronized (getLockObject()) {
2233             for (final int userId : mOwners.getProfileOwnerKeys()) {
2234                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
2235                 // The following restrictions used to be applied to managed profiles by different
2236                 // means (via Settings or by disabling components). Now they are proper user
2237                 // restrictions so we apply them to managed profile owners. Non-managed secondary
2238                 // users didn't have those restrictions so we skip them to keep existing behavior.
2239                 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
2240                     continue;
2241                 }
2242                 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner,
2243                         UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
2244                 ensureUnknownSourcesRestrictionForProfileOwnerLocked(
2245                         userId, profileOwner, false /* newOwner */);
2246             }
2247         }
2248     }
2249 
2250     /**
2251      * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
2252      * set of restrictions for this profile owner.
2253      */
ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, ActiveAdmin profileOwner, boolean newOwner)2254     private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
2255             ActiveAdmin profileOwner, boolean newOwner) {
2256         if (newOwner || mInjector.settingsSecureGetIntForUser(
2257                 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
2258             profileOwner.ensureUserRestrictions().putBoolean(
2259                     UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
2260             saveUserRestrictionsLocked(userId);
2261             mInjector.settingsSecurePutIntForUser(
2262                     Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
2263         }
2264     }
2265 
2266     /**
2267      * Apply default restrictions that haven't been applied to a given admin yet.
2268      */
maybeSetDefaultRestrictionsForAdminLocked( int userId, ActiveAdmin admin, Set<String> defaultRestrictions)2269     private void maybeSetDefaultRestrictionsForAdminLocked(
2270             int userId, ActiveAdmin admin, Set<String> defaultRestrictions) {
2271         if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
2272             return; // The same set of default restrictions has been already applied.
2273         }
2274         Slogf.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
2275 
2276         if (VERBOSE_LOG) {
2277             Slogf.d(LOG_TAG, "Default enabled restrictions: "
2278                     + defaultRestrictions
2279                     + ". Restrictions already enabled: "
2280                     + admin.defaultEnabledRestrictionsAlreadySet);
2281         }
2282 
2283         final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
2284         restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
2285         if (!restrictionsToSet.isEmpty()) {
2286             for (final String restriction : restrictionsToSet) {
2287                 admin.ensureUserRestrictions().putBoolean(restriction, true);
2288             }
2289             admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
2290             Slogf.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
2291             saveUserRestrictionsLocked(userId);
2292         }
2293     }
2294 
setDeviceOwnershipSystemPropertyLocked()2295     private void setDeviceOwnershipSystemPropertyLocked() {
2296         // Still at the first stage of CryptKeeper double bounce, nothing can be learnt about
2297         // the real system at this point.
2298         if (StorageManager.inCryptKeeperBounce()) {
2299             return;
2300         }
2301         final boolean deviceProvisioned =
2302                 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2303         final boolean hasDeviceOwner = mOwners.hasDeviceOwner();
2304         final boolean hasOrgOwnedProfile = isOrganizationOwnedDeviceWithManagedProfile();
2305         // If the device is not provisioned and there is currently no management, do not set the
2306         // read-only system property yet, since device owner / org-owned profile may still be
2307         // provisioned.
2308         if (!hasDeviceOwner && !hasOrgOwnedProfile && !deviceProvisioned) {
2309             return;
2310         }
2311         final String value = Boolean.toString(hasDeviceOwner || hasOrgOwnedProfile);
2312         final String currentVal = mInjector.systemPropertiesGet(PROPERTY_ORGANIZATION_OWNED, null);
2313         if (TextUtils.isEmpty(currentVal)) {
2314             Slogf.i(LOG_TAG, "Set ro.organization_owned property to " + value);
2315             mInjector.systemPropertiesSet(PROPERTY_ORGANIZATION_OWNED, value);
2316         } else if (!value.equals(currentVal)) {
2317             Slogf.w(LOG_TAG, "Cannot change existing ro.organization_owned to " + value);
2318         }
2319     }
2320 
maybeStartSecurityLogMonitorOnActivityManagerReady()2321     private void maybeStartSecurityLogMonitorOnActivityManagerReady() {
2322         synchronized (getLockObject()) {
2323             if (mInjector.securityLogIsLoggingEnabled()) {
2324                 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
2325                 mInjector.runCryptoSelfTest();
2326                 maybePauseDeviceWideLoggingLocked();
2327             }
2328         }
2329     }
2330 
findOwnerComponentIfNecessaryLocked()2331     private void findOwnerComponentIfNecessaryLocked() {
2332         if (!mOwners.hasDeviceOwner()) {
2333             return;
2334         }
2335         final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
2336 
2337         if (!TextUtils.isEmpty(doComponentName.getClassName())) {
2338             return; // Already a full component name.
2339         }
2340 
2341         final ComponentName doComponent = findAdminComponentWithPackageLocked(
2342                 doComponentName.getPackageName(),
2343                 mOwners.getDeviceOwnerUserId());
2344         if (doComponent == null) {
2345             Slogf.e(LOG_TAG, "Device-owner isn't registered as device-admin");
2346         } else {
2347             mOwners.setDeviceOwnerWithRestrictionsMigrated(
2348                     doComponent,
2349                     mOwners.getDeviceOwnerName(),
2350                     mOwners.getDeviceOwnerUserId(),
2351                     !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
2352             mOwners.writeDeviceOwner();
2353             if (VERBOSE_LOG) {
2354                 Slogf.v(LOG_TAG, "Device owner component filled in");
2355             }
2356         }
2357     }
2358 
2359     /**
2360      * We didn't use to persist user restrictions for each owners but only persisted in user
2361      * manager.
2362      */
migrateUserRestrictionsIfNecessaryLocked()2363     private void migrateUserRestrictionsIfNecessaryLocked() {
2364         boolean migrated = false;
2365         // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
2366         // except for the "system controlled" ones.
2367         if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
2368             if (VERBOSE_LOG) {
2369                 Slogf.v(LOG_TAG, "Migrating DO user restrictions");
2370             }
2371             migrated = true;
2372 
2373             // Migrate user 0 restrictions to DO.
2374             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
2375 
2376             migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
2377                     /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
2378 
2379             // Push DO user restrictions to user manager.
2380             pushUserRestrictions(UserHandle.USER_SYSTEM);
2381 
2382             mOwners.setDeviceOwnerUserRestrictionsMigrated();
2383         }
2384 
2385         // Migrate for POs.
2386 
2387         // The following restrictions can be set on secondary users by the device owner, so we
2388         // assume they're not from the PO.
2389         final Set<String> secondaryUserExceptionList = Sets.newArraySet(
2390                 UserManager.DISALLOW_OUTGOING_CALLS,
2391                 UserManager.DISALLOW_SMS);
2392 
2393         for (UserInfo ui : mUserManager.getUsers()) {
2394             final int userId = ui.id;
2395             if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
2396                 if (VERBOSE_LOG) {
2397                     Slogf.v(LOG_TAG, "Migrating PO user restrictions for user %d", userId);
2398                 }
2399                 migrated = true;
2400 
2401                 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
2402 
2403                 final Set<String> exceptionList =
2404                         (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
2405 
2406                 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
2407                         exceptionList, /* isDeviceOwner =*/ false);
2408 
2409                 // Note if a secondary user has no PO but has a DA that disables camera, we
2410                 // don't get here and won't push the camera user restriction to UserManager
2411                 // here.  That's okay because we'll push user restrictions anyway when a user
2412                 // starts.  But we still do it because we want to let user manager persist
2413                 // upon migration.
2414                 pushUserRestrictions(userId);
2415 
2416                 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
2417             }
2418         }
2419         if (VERBOSE_LOG && migrated) {
2420             Slogf.v(LOG_TAG, "User restrictions migrated.");
2421         }
2422     }
2423 
migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, Set<String> exceptionList, boolean isDeviceOwner)2424     private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
2425             Set<String> exceptionList, boolean isDeviceOwner) {
2426         final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
2427                 user.getIdentifier());
2428 
2429         final Bundle newBaseRestrictions = new Bundle();
2430         final Bundle newOwnerRestrictions = new Bundle();
2431 
2432         for (String key : origRestrictions.keySet()) {
2433             if (!origRestrictions.getBoolean(key)) {
2434                 continue;
2435             }
2436             final boolean canOwnerChange = isDeviceOwner
2437                     ? UserRestrictionsUtils.canDeviceOwnerChange(key)
2438                     : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
2439 
2440             if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
2441                 newBaseRestrictions.putBoolean(key, true);
2442             } else {
2443                 newOwnerRestrictions.putBoolean(key, true);
2444             }
2445         }
2446 
2447         if (VERBOSE_LOG) {
2448             Slogf.v(LOG_TAG, "origRestrictions=%s", origRestrictions);
2449             Slogf.v(LOG_TAG, "newBaseRestrictions=%s", newBaseRestrictions);
2450             Slogf.v(LOG_TAG, "newOwnerRestrictions=%s", newOwnerRestrictions);
2451         }
2452         mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
2453                 newBaseRestrictions);
2454 
2455         if (admin != null) {
2456             admin.ensureUserRestrictions().clear();
2457             admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
2458         } else {
2459             Slogf.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
2460         }
2461         saveSettingsLocked(user.getIdentifier());
2462     }
2463 
2464     /**
2465      * Fix left-over restrictions and auto-time policy during COMP -> COPE migration.
2466      *
2467      * When a COMP device with requireAutoTime policy set was migrated to an
2468      * organization-owned profile, a DISALLOW_CONFIG_DATE_TIME restriction is set
2469      * on user 0 from the DO user, which becomes unremovable by the organization-owned
2470      * profile owner. Fix this by force removing that restriction. Also revert the
2471      * parentAdmin.requireAutoTime bit (since the COPE PO cannot unset this bit)
2472      * and replace it with DISALLOW_CONFIG_DATE_TIME on the correct
2473      * admin, in line with the deprecation recommendation of setAutoTimeRequired().
2474      */
fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration()2475     private void fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration() {
2476         for (UserInfo ui : mUserManager.getUsers()) {
2477             final int userId = ui.id;
2478             if (isProfileOwnerOfOrganizationOwnedDevice(userId)) {
2479                 final ActiveAdmin parent = getProfileOwnerAdminLocked(userId).parentAdmin;
2480                 if (parent != null && parent.requireAutoTime) {
2481                     // Remove deprecated requireAutoTime
2482                     parent.requireAutoTime = false;
2483                     saveSettingsLocked(userId);
2484 
2485                     // Remove user restrictions set by the device owner before the upgrade to
2486                     // Android 11.
2487                     mUserManagerInternal.setDevicePolicyUserRestrictions(UserHandle.USER_SYSTEM,
2488                             new Bundle(), new RestrictionsSet(), /* isDeviceOwner */ false);
2489 
2490                     // Apply user restriction to parent active admin instead
2491                     parent.ensureUserRestrictions().putBoolean(
2492                             UserManager.DISALLOW_CONFIG_DATE_TIME, true);
2493                     pushUserRestrictions(userId);
2494                 }
2495             }
2496         }
2497     }
2498 
findAdminComponentWithPackageLocked(String packageName, int userId)2499     private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
2500         final DevicePolicyData policy = getUserData(userId);
2501         final int n = policy.mAdminList.size();
2502         ComponentName found = null;
2503         int nFound = 0;
2504         for (int i = 0; i < n; i++) {
2505             final ActiveAdmin admin = policy.mAdminList.get(i);
2506             if (packageName.equals(admin.info.getPackageName())) {
2507                 // Found!
2508                 if (nFound == 0) {
2509                     found = admin.info.getComponent();
2510                 }
2511                 nFound++;
2512             }
2513         }
2514         if (nFound > 1) {
2515             Slogf.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
2516         }
2517         return found;
2518     }
2519 
2520     /**
2521      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2522      * reminders.  Clears alarm if no expirations are configured.
2523      */
setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent)2524     private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2525         final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2526         final long now = System.currentTimeMillis();
2527         final long timeToExpire = expiration - now;
2528         final long alarmTime;
2529         if (expiration == 0) {
2530             // No expirations are currently configured:  Cancel alarm.
2531             alarmTime = 0;
2532         } else if (timeToExpire <= 0) {
2533             // The password has already expired:  Repeat every 24 hours.
2534             alarmTime = now + MS_PER_DAY;
2535         } else {
2536             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2537             // the expiration time.
2538             long alarmInterval = timeToExpire % MS_PER_DAY;
2539             if (alarmInterval == 0) {
2540                 alarmInterval = MS_PER_DAY;
2541             }
2542             alarmTime = now + alarmInterval;
2543         }
2544 
2545         mInjector.binderWithCleanCallingIdentity(() -> {
2546             int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2547             AlarmManager am = mInjector.getAlarmManager();
2548             // Broadcast alarms sent by system are immutable
2549             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2550                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2551                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
2552                             | PendingIntent.FLAG_IMMUTABLE,
2553                     UserHandle.of(affectedUserHandle));
2554             am.cancel(pi);
2555             if (alarmTime != 0) {
2556                 am.set(AlarmManager.RTC, alarmTime, pi);
2557             }
2558         });
2559     }
2560 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle)2561     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2562         ensureLocked();
2563         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2564         if (admin != null
2565                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2566                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2567             return admin;
2568         }
2569         return null;
2570     }
2571 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent)2572     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2573         ensureLocked();
2574         if (parent) {
2575             Preconditions.checkCallAuthorization(isManagedProfile(userHandle),
2576                     "You can not call APIs on the parent profile outside a managed profile, "
2577                             + "userId = %d", userHandle);
2578         }
2579         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2580         if (admin != null && parent) {
2581             admin = admin.getParentActiveAdmin();
2582         }
2583         return admin;
2584     }
2585 
getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)2586     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2587             throws SecurityException {
2588         return getActiveAdminOrCheckPermissionForCallerLocked(who,
2589                 reqPolicy, /* permission= */ null);
2590     }
2591 
getDeviceOwnerLocked(final CallerIdentity caller)2592     @NonNull ActiveAdmin getDeviceOwnerLocked(final CallerIdentity caller) {
2593         ensureLocked();
2594         ComponentName doComponent = mOwners.getDeviceOwnerComponent();
2595         Preconditions.checkState(doComponent != null,
2596                 "No device owner for user %d", caller.getUid());
2597 
2598         // Use the user ID of the caller instead of mOwners.getDeviceOwnerUserId() because
2599         // secondary, affiliated users will have their own admin.
2600         ActiveAdmin doAdmin = getUserData(caller.getUserId()).mAdminMap.get(doComponent);
2601         Preconditions.checkState(doAdmin != null,
2602                 "Device owner %s for user %d not found", doComponent,
2603                         caller.getUid());
2604 
2605         Preconditions.checkCallAuthorization(doAdmin.getUid() == caller.getUid(),
2606                     "Admin %s is not owned by uid %d, but uid %d", doComponent,
2607                             caller.getUid(), doAdmin.getUid());
2608 
2609         Preconditions.checkCallAuthorization(
2610                 !caller.hasAdminComponent()
2611                 || doAdmin.info.getComponent().equals(caller.getComponentName()),
2612                 "Caller component %s is not device owner",
2613                         caller.getComponentName());
2614 
2615         return doAdmin;
2616     }
2617 
getProfileOwnerLocked(final CallerIdentity caller)2618     @NonNull ActiveAdmin getProfileOwnerLocked(final CallerIdentity caller) {
2619         ensureLocked();
2620         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(caller.getUserId());
2621 
2622         Preconditions.checkState(poAdminComponent != null,
2623                     "No profile owner for user %d", caller.getUid());
2624 
2625         ActiveAdmin poAdmin = getUserData(caller.getUserId()).mAdminMap.get(poAdminComponent);
2626         Preconditions.checkState(poAdmin != null,
2627                     "No device profile owner for caller %d", caller.getUid());
2628 
2629         Preconditions.checkCallAuthorization(poAdmin.getUid() == caller.getUid(),
2630                     "Admin %s is not owned by uid %d", poAdminComponent,
2631                             caller.getUid());
2632 
2633         Preconditions.checkCallAuthorization(
2634                 !caller.hasAdminComponent()
2635                 || poAdmin.info.getComponent().equals(caller.getComponentName()),
2636                 "Caller component %s is not profile owner",
2637                         caller.getComponentName());
2638 
2639         return poAdmin;
2640     }
2641 
getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller)2642     @NonNull ActiveAdmin getOrganizationOwnedProfileOwnerLocked(final CallerIdentity caller) {
2643         final ActiveAdmin profileOwner = getProfileOwnerLocked(caller);
2644 
2645         Preconditions.checkCallAuthorization(
2646                 mOwners.isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()),
2647                 "Admin %s is not of an org-owned device",
2648                         profileOwner.info.getComponent());
2649 
2650         return profileOwner;
2651     }
2652 
getProfileOwnerOrDeviceOwnerLocked(final CallerIdentity caller)2653     @NonNull ActiveAdmin getProfileOwnerOrDeviceOwnerLocked(final CallerIdentity caller) {
2654         ensureLocked();
2655         // Try to find an admin which can use reqPolicy
2656         final ComponentName poAdminComponent = mOwners.getProfileOwnerComponent(caller.getUserId());
2657         final ComponentName doAdminComponent = mOwners.getDeviceOwnerComponent();
2658 
2659         if (poAdminComponent == null && doAdminComponent == null) {
2660             throw new IllegalStateException(
2661                     String.format("No profile or device owner for user %d", caller.getUid()));
2662         }
2663 
2664         if (poAdminComponent != null) {
2665             return getProfileOwnerLocked(caller);
2666         }
2667 
2668         return getDeviceOwnerLocked(caller);
2669     }
2670 
getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent)2671     @NonNull ActiveAdmin getParentOfAdminIfRequired(ActiveAdmin admin, boolean parent) {
2672         Objects.requireNonNull(admin);
2673         return parent ? admin.getParentActiveAdmin() : admin;
2674     }
2675 
2676     /**
2677      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2678      *
2679      * @return an active admin or {@code null} if there is no active admin but
2680      * {@code permission} is granted
2681      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2682      */
2683     @Nullable
getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, @Nullable String permission)2684     ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
2685             ComponentName who,
2686             int reqPolicy,
2687             @Nullable String permission) throws SecurityException {
2688         ensureLocked();
2689         final CallerIdentity caller = getCallerIdentity();
2690 
2691         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, caller.getUid());
2692         if (result != null) {
2693             return result;
2694         } else if (permission != null && hasCallingPermission(permission)) {
2695             return null;
2696         }
2697 
2698         // Code for handling failure from getActiveAdminWithPolicyForUidLocked to find an admin
2699         // that satisfies the required policy.
2700         // Throws a security exception with the right error message.
2701         if (who != null) {
2702             final DevicePolicyData policy = getUserData(caller.getUserId());
2703             ActiveAdmin admin = policy.mAdminMap.get(who);
2704             final boolean isDeviceOwner = isDeviceOwner(admin.info.getComponent(),
2705                     caller.getUserId());
2706             final boolean isProfileOwner = isProfileOwner(admin.info.getComponent(),
2707                     caller.getUserId());
2708 
2709             if (DA_DISALLOWED_POLICIES.contains(reqPolicy) && !isDeviceOwner && !isProfileOwner) {
2710                 throw new SecurityException("Admin " + admin.info.getComponent()
2711                         + " is not a device owner or profile owner, so may not use policy: "
2712                         + admin.info.getTagForPolicy(reqPolicy));
2713             }
2714             throw new SecurityException("Admin " + admin.info.getComponent()
2715                     + " did not specify uses-policy for: "
2716                     + admin.info.getTagForPolicy(reqPolicy));
2717         } else {
2718             throw new SecurityException("No active admin owned by uid "
2719                     + caller.getUid() + " for policy #" + reqPolicy + (permission == null ? ""
2720                     : ", which doesn't have " + permission));
2721         }
2722     }
2723 
getActiveAdminForCallerLocked(@ullable ComponentName who, int reqPolicy, boolean parent)2724     ActiveAdmin getActiveAdminForCallerLocked(@Nullable ComponentName who, int reqPolicy,
2725             boolean parent) throws SecurityException {
2726         return getActiveAdminOrCheckPermissionForCallerLocked(
2727                 who, reqPolicy, parent, /* permission= */ null);
2728     }
2729 
2730     /**
2731      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2732      *
2733      * @return an active admin or {@code null} if there is no active admin but
2734      * {@code permission} is granted
2735      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2736      */
2737     @Nullable
getActiveAdminOrCheckPermissionForCallerLocked( @ullable ComponentName who, int reqPolicy, boolean parent, @Nullable String permission)2738     ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
2739             @Nullable ComponentName who,
2740             int reqPolicy,
2741             boolean parent,
2742             @Nullable String permission) throws SecurityException {
2743         ensureLocked();
2744         if (parent) {
2745             Preconditions.checkCallingUser(isManagedProfile(getCallerIdentity().getUserId()));
2746         }
2747         ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked(
2748                 who, reqPolicy, permission);
2749         return parent ? admin.getParentActiveAdmin() : admin;
2750     }
2751 
2752     /**
2753      * Find the admin for the component and userId bit of the uid, then check
2754      * the admin's uid matches the uid.
2755      */
getActiveAdminForUidLocked(ComponentName who, int uid)2756     private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2757         ensureLocked();
2758         final int userId = UserHandle.getUserId(uid);
2759         final DevicePolicyData policy = getUserData(userId);
2760         ActiveAdmin admin = policy.mAdminMap.get(who);
2761         if (admin == null) {
2762             throw new SecurityException("No active admin " + who + " for UID " + uid);
2763         }
2764         if (admin.getUid() != uid) {
2765             throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2766         }
2767         return admin;
2768     }
2769 
2770     /**
2771      * Returns the active admin for the user of the caller as denoted by uid, which implements
2772      * the {@code reqPolicy}.
2773      *
2774      * The {@code who} parameter is used as a hint:
2775      * If provided, it must be the component name of the active admin for that user and the caller
2776      * uid must match the uid of the admin.
2777      * If not provided, iterate over all of the active admins in the DevicePolicyData for that user
2778      * and return the one with the uid specified as parameter, and has the policy specified.
2779      */
2780     @Nullable
getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, int uid)2781     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2782             int uid) {
2783         ensureLocked();
2784         // Try to find an admin which can use reqPolicy
2785         final int userId = UserHandle.getUserId(uid);
2786         final DevicePolicyData policy = getUserData(userId);
2787         if (who != null) {
2788             ActiveAdmin admin = policy.mAdminMap.get(who);
2789             if (admin == null) {
2790                 throw new SecurityException("No active admin " + who);
2791             }
2792             if (admin.getUid() != uid) {
2793                 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2794             }
2795             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2796                 return admin;
2797             }
2798         } else {
2799             for (ActiveAdmin admin : policy.mAdminList) {
2800                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2801                         userId)) {
2802                     return admin;
2803                 }
2804             }
2805         }
2806 
2807         return null;
2808     }
2809 
2810     @VisibleForTesting
isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, int userId)2811     boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2812             int userId) {
2813         ensureLocked();
2814         final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2815         final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2816 
2817         boolean allowedToUsePolicy = ownsDevice || ownsProfile
2818                 || !DA_DISALLOWED_POLICIES.contains(reqPolicy)
2819                 || getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.Q;
2820         return allowedToUsePolicy && admin.info.usesPolicy(reqPolicy);
2821     }
2822 
2823     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2824         sendAdminCommandLocked(admin, action, null);
2825     }
2826 
2827     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2828         sendAdminCommandLocked(admin, action, null, result);
2829     }
2830 
2831     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2832             BroadcastReceiver result) {
2833         sendAdminCommandLocked(admin, action, adminExtras, result, false);
2834     }
2835 
2836     /**
2837      * Send an update to one specific admin, get notified when that admin returns a result.
2838      *
2839      * @return whether the broadcast was successfully sent
2840      */
2841     boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2842             BroadcastReceiver result, boolean inForeground) {
2843         Intent intent = new Intent(action);
2844         intent.setComponent(admin.info.getComponent());
2845         if (UserManager.isDeviceInDemoMode(mContext)) {
2846             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2847         }
2848         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2849             intent.putExtra("expiration", admin.passwordExpirationDate);
2850         }
2851         if (inForeground) {
2852             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2853         }
2854         if (adminExtras != null) {
2855             intent.putExtras(adminExtras);
2856         }
2857         if (mInjector.getPackageManager().queryBroadcastReceiversAsUser(
2858                 intent,
2859                 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2860                 admin.getUserHandle()).isEmpty()) {
2861             return false;
2862         }
2863 
2864         final BroadcastOptions options = BroadcastOptions.makeBasic();
2865         options.setBackgroundActivityStartsAllowed(true);
2866 
2867         if (result != null) {
2868             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2869                     null, AppOpsManager.OP_NONE, options.toBundle(),
2870                     result, mHandler, Activity.RESULT_OK, null, null);
2871         } else {
2872             mContext.sendBroadcastAsUser(intent, admin.getUserHandle(), null, options.toBundle());
2873         }
2874 
2875         return true;
2876     }
2877 
2878     /**
2879      * Send an update to all admins of a user that enforce a specified policy.
2880      */
2881     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
2882         final DevicePolicyData policy = getUserData(userHandle);
2883         final int count = policy.mAdminList.size();
2884         for (int i = 0; i < count; i++) {
2885             final ActiveAdmin admin = policy.mAdminList.get(i);
2886             if (admin.info.usesPolicy(reqPolicy)) {
2887                 sendAdminCommandLocked(admin, action, adminExtras, null);
2888             }
2889         }
2890     }
2891 
2892     /**
2893      * Send an update intent to all admins of a user and its profiles. Only send to admins that
2894      * enforce a specified policy.
2895      */
2896     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2897             int userHandle, Bundle adminExtras) {
2898         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2899         for (int profileId : profileIds) {
2900             sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
2901         }
2902     }
2903 
2904     /**
2905      * Sends a broadcast to each profile that share the password unlock with the given user id.
2906      */
2907     private void sendAdminCommandForLockscreenPoliciesLocked(
2908             String action, int reqPolicy, int userHandle) {
2909         final Bundle extras = new Bundle();
2910         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2911         if (isSeparateProfileChallengeEnabled(userHandle)) {
2912             sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
2913         } else {
2914             sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
2915         }
2916     }
2917 
2918     void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2919         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2920         DevicePolicyData policy = getUserData(userHandle);
2921         if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2922             policy.mRemovingAdmins.add(adminReceiver);
2923             sendAdminCommandLocked(admin,
2924                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2925                     new BroadcastReceiver() {
2926                         @Override
2927                         public void onReceive(Context context, Intent intent) {
2928                             removeAdminArtifacts(adminReceiver, userHandle);
2929                             removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2930                         }
2931                     });
2932         }
2933     }
2934 
2935     private DeviceAdminInfo findAdmin(final ComponentName adminName, final int userHandle,
2936             boolean throwForMissingPermission) {
2937         final ActivityInfo ai = mInjector.binderWithCleanCallingIdentity(() -> {
2938             try {
2939                 return mIPackageManager.getReceiverInfo(adminName,
2940                         PackageManager.GET_META_DATA
2941                         | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS
2942                         | PackageManager.MATCH_DIRECT_BOOT_AWARE
2943                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2944             } catch (RemoteException e) {
2945                 // shouldn't happen.
2946                 return null;
2947             }
2948         });
2949         if (ai == null) {
2950             throw new IllegalArgumentException("Unknown admin: " + adminName);
2951         }
2952 
2953         if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2954             final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2955                     + permission.BIND_DEVICE_ADMIN;
2956             Slogf.w(LOG_TAG, message);
2957             if (throwForMissingPermission &&
2958                     ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2959                 throw new IllegalArgumentException(message);
2960             }
2961         }
2962 
2963         try {
2964             return new DeviceAdminInfo(mContext, ai);
2965         } catch (XmlPullParserException | IOException e) {
2966             Slogf.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2967                     e);
2968             return null;
2969         }
2970     }
2971 
2972     private File getPolicyFileDirectory(@UserIdInt int userId) {
2973         return userId == UserHandle.USER_SYSTEM
2974                 ? new File(mInjector.getDevicePolicyFilePathForSystemUser())
2975                 : mInjector.environmentGetUserSystemDirectory(userId);
2976     }
2977 
2978     private JournaledFile makeJournaledFile(@UserIdInt int userId, String fileName) {
2979         final String base = new File(getPolicyFileDirectory(userId), fileName)
2980                 .getAbsolutePath();
2981         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Opening %s", base);
2982         return new JournaledFile(new File(base), new File(base + ".tmp"));
2983     }
2984 
2985     private JournaledFile makeJournaledFile(@UserIdInt int userId) {
2986         return makeJournaledFile(userId, DEVICE_POLICIES_XML);
2987     }
2988 
2989     /**
2990      * Persist modified values to disk by calling {@link #saveSettingsLocked} for each
2991      * affected user ID.
2992      */
2993     @GuardedBy("getLockObject()")
2994     private void saveSettingsForUsersLocked(Set<Integer> affectedUserIds) {
2995         for (int userId : affectedUserIds) {
2996             saveSettingsLocked(userId);
2997         }
2998     }
2999 
3000     private void saveSettingsLocked(int userHandle) {
3001         if (DevicePolicyData.store(
3002                 getUserData(userHandle),
3003                 makeJournaledFile(userHandle),
3004                 !mInjector.storageManagerIsFileBasedEncryptionEnabled())) {
3005             sendChangedNotification(userHandle);
3006         }
3007     }
3008 
3009     private void sendChangedNotification(int userHandle) {
3010         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
3011         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3012         mInjector.binderWithCleanCallingIdentity(() ->
3013                 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle)));
3014     }
3015 
3016     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
3017         DevicePolicyData.load(policy,
3018                 !mInjector.storageManagerIsFileBasedEncryptionEnabled(),
3019                 makeJournaledFile(userHandle),
3020                 component -> findAdmin(
3021                         component, userHandle, /* throwForMissingPermission= */ false),
3022                 getOwnerComponent(userHandle));
3023 
3024         policy.validatePasswordOwner();
3025         updateMaximumTimeToLockLocked(userHandle);
3026         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
3027         updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle);
3028         if (policy.mStatusBarDisabled) {
3029             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
3030         }
3031     }
3032 
3033     private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
3034         String[] packagesArray = null;
3035 
3036         if (!packages.isEmpty()) {
3037             // When adding packages, we need to include the exempt apps so they can still be
3038             // launched (ideally we should use a different AM API as these apps don't need to use
3039             // lock-task mode).
3040             // They're not added when the packages is empty though, as in that case we're disabling
3041             // lock-task mode.
3042             List<String> exemptApps = listPolicyExemptAppsUnchecked();
3043             if (!exemptApps.isEmpty()) {
3044                 // TODO(b/175377361): add unit test to verify it (cannot be CTS because the policy-
3045                 // -exempt apps are provided by OEM and the test would have no control over it) once
3046                 // tests are migrated to the new infra-structure
3047                 HashSet<String> updatedPackages = new HashSet<>(packages);
3048                 updatedPackages.addAll(exemptApps);
3049                 if (VERBOSE_LOG) {
3050                     Slogf.v(LOG_TAG, "added %d policy-exempt apps to %d lock task packages. Final "
3051                             + "list: %s", exemptApps.size(), packages.size(), updatedPackages);
3052                 }
3053                 packagesArray = updatedPackages.toArray(new String[updatedPackages.size()]);
3054             }
3055         }
3056 
3057         if (packagesArray == null) {
3058             packagesArray = packages.toArray(new String[packages.size()]);
3059         }
3060 
3061         long ident = mInjector.binderClearCallingIdentity();
3062         try {
3063             mInjector.getIActivityManager().updateLockTaskPackages(userId, packagesArray);
3064         } catch (RemoteException e) {
3065             // Not gonna happen.
3066         } finally {
3067             mInjector.binderRestoreCallingIdentity(ident);
3068         }
3069     }
3070 
3071     private void updateLockTaskFeaturesLocked(int flags, int userId) {
3072         long ident = mInjector.binderClearCallingIdentity();
3073         try {
3074             mInjector.getIActivityTaskManager().updateLockTaskFeatures(userId, flags);
3075         } catch (RemoteException e) {
3076             // Not gonna happen.
3077         } finally {
3078             mInjector.binderRestoreCallingIdentity(ident);
3079         }
3080     }
3081 
3082     private void updateDeviceOwnerLocked() {
3083         long ident = mInjector.binderClearCallingIdentity();
3084         try {
3085             // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
3086             // user id and also protect all other DAs too.
3087             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
3088             if (deviceOwnerComponent != null) {
3089                 mInjector.getIActivityManager()
3090                         .updateDeviceOwner(deviceOwnerComponent.getPackageName());
3091             }
3092         } catch (RemoteException e) {
3093             // Not gonna happen.
3094         } finally {
3095             mInjector.binderRestoreCallingIdentity(ident);
3096         }
3097     }
3098 
3099     static void validateQualityConstant(int quality) {
3100         switch (quality) {
3101             case PASSWORD_QUALITY_UNSPECIFIED:
3102             case PASSWORD_QUALITY_BIOMETRIC_WEAK:
3103             case PASSWORD_QUALITY_SOMETHING:
3104             case PASSWORD_QUALITY_NUMERIC:
3105             case PASSWORD_QUALITY_NUMERIC_COMPLEX:
3106             case PASSWORD_QUALITY_ALPHABETIC:
3107             case PASSWORD_QUALITY_ALPHANUMERIC:
3108             case PASSWORD_QUALITY_COMPLEX:
3109             case PASSWORD_QUALITY_MANAGED:
3110                 return;
3111         }
3112         throw new IllegalArgumentException("Invalid quality constant: 0x"
3113                 + Integer.toHexString(quality));
3114     }
3115 
3116     @VisibleForTesting
3117     @Override
3118     void systemReady(int phase) {
3119         if (!mHasFeature) {
3120             return;
3121         }
3122         switch (phase) {
3123             case SystemService.PHASE_LOCK_SETTINGS_READY:
3124                 onLockSettingsReady();
3125                 loadAdminDataAsync();
3126                 mOwners.systemReady();
3127                 break;
3128             case SystemService.PHASE_ACTIVITY_MANAGER_READY:
3129                 synchronized (getLockObject()) {
3130                     migrateToProfileOnOrganizationOwnedDeviceIfCompLocked();
3131                     applyManagedProfileRestrictionIfDeviceOwnerLocked();
3132                 }
3133                 maybeStartSecurityLogMonitorOnActivityManagerReady();
3134                 break;
3135             case SystemService.PHASE_BOOT_COMPLETED:
3136                 // Ideally it should be done earlier, but currently it relies on RecoverySystem,
3137                 // which would hang on earlier phases
3138                 factoryResetIfDelayedEarlier();
3139 
3140                 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
3141                 break;
3142         }
3143     }
3144 
3145     private void updatePersonalAppsSuspensionOnUserStart(int userHandle) {
3146         final int profileUserHandle = getManagedUserId(userHandle);
3147         if (profileUserHandle >= 0) {
3148             // Given that the parent user has just started, profile should be locked.
3149             updatePersonalAppsSuspension(profileUserHandle, false /* unlocked */);
3150         } else {
3151             suspendPersonalAppsInternal(userHandle, false);
3152         }
3153     }
3154 
3155     private void onLockSettingsReady() {
3156         synchronized (getLockObject()) {
3157             migrateUserRestrictionsIfNecessaryLocked();
3158             fixupAutoTimeRestrictionDuringOrganizationOwnedDeviceMigration();
3159             performPolicyVersionUpgrade();
3160         }
3161         getUserData(UserHandle.USER_SYSTEM);
3162         cleanUpOldUsers();
3163         maybeSetDefaultProfileOwnerUserRestrictions();
3164         handleStartUser(UserHandle.USER_SYSTEM);
3165         maybeLogStart();
3166 
3167         // Register an observer for watching for user setup complete and settings changes.
3168         mSetupContentObserver.register();
3169         // Initialize the user setup state, to handle the upgrade case.
3170         updateUserSetupCompleteAndPaired();
3171 
3172         List<String> packageList;
3173         synchronized (getLockObject()) {
3174             packageList = getKeepUninstalledPackagesLocked();
3175         }
3176         if (packageList != null) {
3177             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3178         }
3179 
3180         synchronized (getLockObject()) {
3181             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3182             if (deviceOwner != null) {
3183                 // Push the force-ephemeral-users policy to the user manager.
3184                 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3185 
3186                 // Update user switcher message to activity manager.
3187                 ActivityManagerInternal activityManagerInternal =
3188                         mInjector.getActivityManagerInternal();
3189                 activityManagerInternal.setSwitchingFromSystemUserMessage(
3190                         deviceOwner.startUserSessionMessage);
3191                 activityManagerInternal.setSwitchingToSystemUserMessage(
3192                         deviceOwner.endUserSessionMessage);
3193             }
3194 
3195             revertTransferOwnershipIfNecessaryLocked();
3196         }
3197         updateUsbDataSignal();
3198     }
3199 
3200     private class DpmsUpgradeDataProvider implements PolicyUpgraderDataProvider {
3201         @Override
3202         public boolean isDeviceOwner(int userId, ComponentName who) {
3203             return mOwners.isDeviceOwnerUserId(userId)
3204                     && mOwners.getDeviceOwnerComponent().equals(who);
3205         }
3206 
3207         @Override
3208         public boolean storageManagerIsFileBasedEncryptionEnabled() {
3209             return mInjector.storageManagerIsFileBasedEncryptionEnabled();
3210         }
3211 
3212         @Override
3213         public JournaledFile makeDevicePoliciesJournaledFile(int userId) {
3214             return DevicePolicyManagerService.this.makeJournaledFile(userId, DEVICE_POLICIES_XML);
3215         }
3216 
3217         @Override
3218         public JournaledFile makePoliciesVersionJournaledFile(int userId) {
3219             return DevicePolicyManagerService.this.makeJournaledFile(userId, POLICIES_VERSION_XML);
3220         }
3221 
3222         @Override
3223         public ComponentName getOwnerComponent(int userId) {
3224             return DevicePolicyManagerService.this.getOwnerComponent(userId);
3225         }
3226 
3227         @Override
3228         public Function<ComponentName, DeviceAdminInfo> getAdminInfoSupplier(int userId) {
3229             return component -> findAdmin(component, userId, /* throwForMissingPermission= */
3230                     false);
3231         }
3232 
3233         @Override
3234         public int[] getUsersForUpgrade() {
3235             List<UserInfo> allUsers = mUserManager.getUsers();
3236             return allUsers.stream().mapToInt(u -> u.id).toArray();
3237         }
3238     }
3239 
3240     private void performPolicyVersionUpgrade() {
3241         PolicyVersionUpgrader upgrader = new PolicyVersionUpgrader(
3242                 new DpmsUpgradeDataProvider());
3243 
3244         upgrader.upgradePolicy(DPMS_VERSION);
3245     }
3246 
3247     private void revertTransferOwnershipIfNecessaryLocked() {
3248         if (!mTransferOwnershipMetadataManager.metadataFileExists()) {
3249             return;
3250         }
3251         Slogf.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer.");
3252         final TransferOwnershipMetadataManager.Metadata metadata =
3253                 mTransferOwnershipMetadataManager.loadMetadataFile();
3254         // Revert transfer
3255         if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) {
3256             transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3257                     metadata.userId);
3258             deleteTransferOwnershipMetadataFileLocked();
3259             deleteTransferOwnershipBundleLocked(metadata.userId);
3260         } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) {
3261             transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3262                     metadata.userId);
3263             deleteTransferOwnershipMetadataFileLocked();
3264             deleteTransferOwnershipBundleLocked(metadata.userId);
3265         }
3266         updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
3267     }
3268 
3269     private void maybeLogStart() {
3270         if (!SecurityLog.isLoggingEnabled()) {
3271             return;
3272         }
3273         final String verifiedBootState =
3274                 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate");
3275         final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode");
3276         SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode);
3277     }
3278 
3279     private void ensureDeviceOwnerUserStarted() {
3280         final int userId;
3281         synchronized (getLockObject()) {
3282             if (!mOwners.hasDeviceOwner()) {
3283                 return;
3284             }
3285             userId = mOwners.getDeviceOwnerUserId();
3286         }
3287         if (VERBOSE_LOG) {
3288             Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
3289         }
3290         if (userId != UserHandle.USER_SYSTEM) {
3291             try {
3292                 mInjector.getIActivityManager().startUserInBackground(userId);
3293 
3294                 // STOPSHIP Prevent the DO user from being killed.
3295 
3296             } catch (RemoteException e) {
3297                 Slogf.w(LOG_TAG, "Exception starting user", e);
3298             }
3299         }
3300     }
3301 
3302     @Override
3303     void handleStartUser(int userId) {
3304         updateScreenCaptureDisabled(userId,
3305                 getScreenCaptureDisabled(null, userId, false));
3306         pushUserRestrictions(userId);
3307         // When system user is started (device boot), load cache for all users.
3308         // This is to mitigate the potential race between loading the cache and keyguard
3309         // reading the value during user switch, due to onStartUser() being asynchronous.
3310         updatePasswordQualityCacheForUserGroup(
3311                 userId == UserHandle.USER_SYSTEM ? UserHandle.USER_ALL : userId);
3312         updatePermissionPolicyCache(userId);
3313         updateAdminCanGrantSensorsPermissionCache(userId);
3314 
3315         final boolean preferentialNetworkServiceEnabled;
3316         synchronized (getLockObject()) {
3317             ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
3318             preferentialNetworkServiceEnabled = owner != null
3319                     ? owner.mPreferentialNetworkServiceEnabled
3320                              : DevicePolicyManager.PREFERENTIAL_NETWORK_SERVICE_ENABLED_DEFAULT;
3321         }
3322         updateNetworkPreferenceForUser(userId, preferentialNetworkServiceEnabled);
3323 
3324         startOwnerService(userId, "start-user");
3325     }
3326 
3327     @Override
3328     void handleUnlockUser(int userId) {
3329         startOwnerService(userId, "unlock-user");
3330     }
3331 
3332     @Override
3333     void handleOnUserUnlocked(int userId) {
3334         showNewUserDisclaimerIfNecessary(userId);
3335     }
3336 
3337     @Override
3338     void handleStopUser(int userId) {
3339         updateNetworkPreferenceForUser(userId, false);
3340         stopOwnerService(userId, "stop-user");
3341     }
3342 
3343     private void startOwnerService(int userId, String actionForLog) {
3344         final ComponentName owner = getOwnerComponent(userId);
3345         if (owner != null) {
3346             mDeviceAdminServiceController.startServiceForOwner(
3347                     owner.getPackageName(), userId, actionForLog);
3348         }
3349     }
3350 
3351     private void stopOwnerService(int userId, String actionForLog) {
3352         mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog);
3353     }
3354 
3355     private void cleanUpOldUsers() {
3356         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3357         // before reboot
3358         Set<Integer> usersWithProfileOwners;
3359         Set<Integer> usersWithData;
3360         synchronized (getLockObject()) {
3361             usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3362             usersWithData = new ArraySet<>();
3363             for (int i = 0; i < mUserData.size(); i++) {
3364                 usersWithData.add(mUserData.keyAt(i));
3365             }
3366         }
3367         List<UserInfo> allUsers = mUserManager.getUsers();
3368 
3369         Set<Integer> deletedUsers = new ArraySet<>();
3370         deletedUsers.addAll(usersWithProfileOwners);
3371         deletedUsers.addAll(usersWithData);
3372         for (UserInfo userInfo : allUsers) {
3373             deletedUsers.remove(userInfo.id);
3374         }
3375         for (Integer userId : deletedUsers) {
3376             removeUserData(userId);
3377         }
3378     }
3379 
3380     private void handlePasswordExpirationNotification(int userHandle) {
3381         final Bundle adminExtras = new Bundle();
3382         adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3383 
3384         synchronized (getLockObject()) {
3385             final long now = System.currentTimeMillis();
3386 
3387             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
3388             final int N = admins.size();
3389             for (int i = 0; i < N; i++) {
3390                 ActiveAdmin admin = admins.get(i);
3391                 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
3392                         && admin.passwordExpirationTimeout > 0L
3393                         && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3394                         && admin.passwordExpirationDate > 0L) {
3395                     sendAdminCommandLocked(admin,
3396                             DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3397                 }
3398             }
3399             setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3400         }
3401     }
3402 
3403     /**
3404      * Clean up internal state when the set of installed trusted CA certificates changes.
3405      *
3406      * @param userHandle user to check for. This must be a real user and not, for example,
3407      *        {@link UserHandle#ALL}.
3408      * @param installedCertificates the full set of certificate authorities currently installed for
3409      *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3410      *        correspond to some subset of this.
3411      */
3412     protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3413             final @NonNull Collection<String> installedCertificates) {
3414         if (!mHasFeature) {
3415             return;
3416         }
3417         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
3418 
3419         synchronized (getLockObject()) {
3420             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3421 
3422             boolean changed = false;
3423             changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3424             changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3425             if (changed) {
3426                 saveSettingsLocked(userHandle.getIdentifier());
3427             }
3428         }
3429     }
3430 
3431     /**
3432      * Internal method used by {@link CertificateMonitor}.
3433      */
3434     protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3435         if (!mHasFeature) {
3436             return Collections.<String> emptySet();
3437         }
3438         synchronized (getLockObject()) {
3439             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3440             return policy.mAcceptedCaCertificates;
3441         }
3442     }
3443 
3444     /**
3445      * @param adminReceiver The admin to add
3446      * @param refreshing true = update an active admin, no error
3447      */
3448     @Override
3449     public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
3450         if (!mHasFeature) {
3451             return;
3452         }
3453         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3454 
3455         final CallerIdentity caller = getCallerIdentity();
3456         Preconditions.checkCallAuthorization(
3457                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
3458         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3459 
3460         DevicePolicyData policy = getUserData(userHandle);
3461         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3462                 /* throwForMissingPermission= */ true);
3463         synchronized (getLockObject()) {
3464             checkActiveAdminPrecondition(adminReceiver, info, policy);
3465             mInjector.binderWithCleanCallingIdentity(() -> {
3466                 final ActiveAdmin existingAdmin
3467                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3468                 if (!refreshing && existingAdmin != null) {
3469                     throw new IllegalArgumentException("Admin is already added");
3470                 }
3471                 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3472                 newAdmin.testOnlyAdmin =
3473                         (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3474                                 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3475                 policy.mAdminMap.put(adminReceiver, newAdmin);
3476                 int replaceIndex = -1;
3477                 final int N = policy.mAdminList.size();
3478                 for (int i=0; i < N; i++) {
3479                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3480                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3481                         replaceIndex = i;
3482                         break;
3483                     }
3484                 }
3485                 if (replaceIndex == -1) {
3486                     policy.mAdminList.add(newAdmin);
3487                     enableIfNecessary(info.getPackageName(), userHandle);
3488                     mUsageStatsManagerInternal.onActiveAdminAdded(
3489                             adminReceiver.getPackageName(), userHandle);
3490                 } else {
3491                     policy.mAdminList.set(replaceIndex, newAdmin);
3492                 }
3493                 saveSettingsLocked(userHandle);
3494                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3495                         /* adminExtras= */ null, /* result= */ null);
3496             });
3497         }
3498     }
3499 
3500     private void loadAdminDataAsync() {
3501         mInjector.postOnSystemServerInitThreadPool(() -> {
3502             pushActiveAdminPackages();
3503             mUsageStatsManagerInternal.onAdminDataAvailable();
3504             pushAllMeteredRestrictedPackages();
3505             mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable();
3506         });
3507     }
3508 
3509     private void pushActiveAdminPackages() {
3510         synchronized (getLockObject()) {
3511             final List<UserInfo> users = mUserManager.getUsers();
3512             for (int i = users.size() - 1; i >= 0; --i) {
3513                 final int userId = users.get(i).id;
3514                 mUsageStatsManagerInternal.setActiveAdminApps(
3515                         getActiveAdminPackagesLocked(userId), userId);
3516             }
3517         }
3518     }
3519 
3520     private void pushAllMeteredRestrictedPackages() {
3521         synchronized (getLockObject()) {
3522             final List<UserInfo> users = mUserManager.getUsers();
3523             for (int i = users.size() - 1; i >= 0; --i) {
3524                 final int userId = users.get(i).id;
3525                 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync(
3526                         getMeteredDisabledPackagesLocked(userId), userId);
3527             }
3528         }
3529     }
3530 
3531     private void pushActiveAdminPackagesLocked(int userId) {
3532         mUsageStatsManagerInternal.setActiveAdminApps(
3533                 getActiveAdminPackagesLocked(userId), userId);
3534     }
3535 
3536     private Set<String> getActiveAdminPackagesLocked(int userId) {
3537         final DevicePolicyData policy = getUserData(userId);
3538         Set<String> adminPkgs = null;
3539         for (int i = policy.mAdminList.size() - 1; i >= 0; --i) {
3540             final String pkgName = policy.mAdminList.get(i).info.getPackageName();
3541             if (adminPkgs == null) {
3542                 adminPkgs = new ArraySet<>();
3543             }
3544             adminPkgs.add(pkgName);
3545         }
3546         return adminPkgs;
3547     }
3548 
3549     private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver,
3550             ComponentName outgoingReceiver, int userHandle) {
3551         final DevicePolicyData policy = getUserData(userHandle);
3552         if (!policy.mAdminMap.containsKey(outgoingReceiver)
3553                 && policy.mAdminMap.containsKey(incomingReceiver)) {
3554             // Nothing to transfer - the incoming receiver is already the active admin.
3555             return;
3556         }
3557         final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle,
3558             /* throwForMissingPermission= */ true);
3559         final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver);
3560         final int oldAdminUid = adminToTransfer.getUid();
3561 
3562         adminToTransfer.transfer(incomingDeviceInfo);
3563         policy.mAdminMap.remove(outgoingReceiver);
3564         policy.mAdminMap.put(incomingReceiver, adminToTransfer);
3565         if (policy.mPasswordOwner == oldAdminUid) {
3566             policy.mPasswordOwner = adminToTransfer.getUid();
3567         }
3568 
3569         saveSettingsLocked(userHandle);
3570         sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3571                 null, null);
3572     }
3573 
3574     private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info,
3575             DevicePolicyData policy) {
3576         if (info == null) {
3577             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3578         }
3579         if (!info.getActivityInfo().applicationInfo.isInternal()) {
3580             throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3581                     + adminReceiver);
3582         }
3583         if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3584             throw new IllegalArgumentException("Instant apps cannot be device admins: "
3585                     + adminReceiver);
3586         }
3587         if (policy.mRemovingAdmins.contains(adminReceiver)) {
3588             throw new IllegalArgumentException(
3589                     "Trying to set an admin which is being removed");
3590         }
3591     }
3592 
3593     private void checkAllUsersAreAffiliatedWithDevice() {
3594         Preconditions.checkCallAuthorization(areAllUsersAffiliatedWithDeviceLocked(),
3595                 "operation not allowed when device has unaffiliated users");
3596     }
3597 
3598     @Override
3599     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3600         if (!mHasFeature) {
3601             return false;
3602         }
3603         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3604 
3605         final CallerIdentity caller = getCallerIdentity();
3606         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3607 
3608         synchronized (getLockObject()) {
3609             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3610         }
3611     }
3612 
3613     @Override
3614     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3615         if (!mHasFeature) {
3616             return false;
3617         }
3618         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3619 
3620         final CallerIdentity caller = getCallerIdentity();
3621         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3622 
3623         synchronized (getLockObject()) {
3624             DevicePolicyData policyData = getUserData(userHandle);
3625             return policyData.mRemovingAdmins.contains(adminReceiver);
3626         }
3627     }
3628 
3629     @Override
3630     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3631         if (!mHasFeature) {
3632             return false;
3633         }
3634         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3635 
3636         final CallerIdentity caller = getCallerIdentity();
3637         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3638         Preconditions.checkCallAuthorization(
3639                 isCallingFromPackage(adminReceiver.getPackageName(), caller.getUid())
3640                         || isSystemUid(caller));
3641 
3642         synchronized (getLockObject()) {
3643             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3644             if (administrator == null) {
3645                 throw new SecurityException("No active admin " + adminReceiver);
3646             }
3647             return administrator.info.usesPolicy(policyId);
3648         }
3649     }
3650 
3651     @Override
3652     @SuppressWarnings("unchecked")
3653     public List<ComponentName> getActiveAdmins(int userHandle) {
3654         if (!mHasFeature) {
3655             return Collections.EMPTY_LIST;
3656         }
3657         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3658 
3659         final CallerIdentity caller = getCallerIdentity();
3660         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3661 
3662         synchronized (getLockObject()) {
3663             DevicePolicyData policy = getUserData(userHandle);
3664             final int N = policy.mAdminList.size();
3665             if (N <= 0) {
3666                 return null;
3667             }
3668             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3669             for (int i=0; i<N; i++) {
3670                 res.add(policy.mAdminList.get(i).info.getComponent());
3671             }
3672             return res;
3673         }
3674     }
3675 
3676     @Override
3677     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3678         if (!mHasFeature) {
3679             return false;
3680         }
3681         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3682 
3683         final CallerIdentity caller = getCallerIdentity();
3684         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3685 
3686         synchronized (getLockObject()) {
3687             DevicePolicyData policy = getUserData(userHandle);
3688             final int N = policy.mAdminList.size();
3689             for (int i=0; i<N; i++) {
3690                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3691                     return true;
3692                 }
3693             }
3694             return false;
3695         }
3696     }
3697 
3698     @Override
3699     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3700         if (!mHasFeature) {
3701             return;
3702         }
3703         Objects.requireNonNull(adminReceiver, "ComponentName is null");
3704         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
3705                         || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS),
3706                 "Caller must be shell or hold MANAGE_PROFILE_AND_DEVICE_OWNERS to call "
3707                         + "forceRemoveActiveAdmin");
3708         mInjector.binderWithCleanCallingIdentity(() -> {
3709             boolean isOrgOwnedProfile = false;
3710             synchronized (getLockObject()) {
3711                 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3712                     throw new SecurityException("Attempt to remove non-test admin "
3713                             + adminReceiver + " " + userHandle);
3714                 }
3715 
3716                 // If admin is a device or profile owner tidy that up first.
3717                 if (isDeviceOwner(adminReceiver, userHandle)) {
3718                     clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3719                 }
3720                 if (isProfileOwner(adminReceiver, userHandle)) {
3721                     isOrgOwnedProfile = isProfileOwnerOfOrganizationOwnedDevice(userHandle);
3722                     final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3723                             userHandle, /* parent */ false);
3724                     clearProfileOwnerLocked(admin, userHandle);
3725                 }
3726             }
3727             // Remove the admin skipping sending the broadcast.
3728             removeAdminArtifacts(adminReceiver, userHandle);
3729 
3730             // In case of PO on org owned device, clean device-wide policies and restrictions.
3731             if (isOrgOwnedProfile) {
3732                 final UserHandle parentUser = UserHandle.of(getProfileParentId(userHandle));
3733                 clearOrgOwnedProfileOwnerUserRestrictions(parentUser);
3734                 clearOrgOwnedProfileOwnerDeviceWidePolicies(parentUser.getIdentifier());
3735             }
3736 
3737             Slogf.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3738         });
3739     }
3740 
3741     private void clearOrgOwnedProfileOwnerUserRestrictions(UserHandle parentUserHandle) {
3742         mUserManager.setUserRestriction(
3743                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, false, parentUserHandle);
3744         mUserManager.setUserRestriction(
3745                 UserManager.DISALLOW_ADD_USER, false, parentUserHandle);
3746     }
3747 
3748     private void clearDeviceOwnerUserRestriction(UserHandle userHandle) {
3749         // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state
3750         if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
3751             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle);
3752         }
3753         // When a device owner is set, the system automatically restricts adding a managed profile.
3754         // Remove this restriction when the device owner is cleared.
3755         if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, userHandle)) {
3756             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, false,
3757                     userHandle);
3758         }
3759     }
3760 
3761     /**
3762      * Return if a given package has testOnly="true", in which case we'll relax certain rules
3763      * for CTS.
3764      *
3765      * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
3766      * to check wehter an active admin is test-only or not.
3767      *
3768      * The system allows this flag to be changed when an app is updated, which is not good
3769      * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3770      * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3771      */
3772     private boolean isPackageTestOnly(String packageName, int userHandle) {
3773         final ApplicationInfo ai;
3774         try {
3775             ai = mInjector.getIPackageManager().getApplicationInfo(packageName,
3776                     (PackageManager.MATCH_DIRECT_BOOT_AWARE
3777                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3778         } catch (RemoteException e) {
3779             throw new IllegalStateException(e);
3780         }
3781         if (ai == null) {
3782             throw new IllegalStateException("Couldn't find package: "
3783                     + packageName + " on user " + userHandle);
3784         }
3785         return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3786     }
3787 
3788     /**
3789      * See {@link #isPackageTestOnly}.
3790      */
3791     private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3792         final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3793         return (admin != null) && admin.testOnlyAdmin;
3794     }
3795 
3796     @Override
3797     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3798         if (!mHasFeature) {
3799             return;
3800         }
3801         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
3802 
3803         final CallerIdentity caller = hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS)
3804                 ? getCallerIdentity() : getCallerIdentity(adminReceiver);
3805         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
3806         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_ACTIVE_ADMIN);
3807         enforceUserUnlocked(userHandle);
3808 
3809         synchronized (getLockObject()) {
3810             ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3811             if (admin == null) {
3812                 return;
3813             }
3814             // Active device/profile owners must remain active admins.
3815             if (isDeviceOwner(adminReceiver, userHandle)
3816                     || isProfileOwner(adminReceiver, userHandle)) {
3817                 Slogf.e(LOG_TAG, "Device/profile owner cannot be removed: component="
3818                         + adminReceiver);
3819                 return;
3820             }
3821 
3822             mInjector.binderWithCleanCallingIdentity(() ->
3823                     removeActiveAdminLocked(adminReceiver, userHandle));
3824         }
3825     }
3826 
3827     @Override
3828     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3829         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
3830                 String.format(NOT_SYSTEM_CALLER_MSG, "query separate challenge support"));
3831 
3832         ComponentName profileOwner = getProfileOwnerAsUser(userHandle);
3833         // Profile challenge is supported on N or newer release.
3834         return profileOwner != null &&
3835                 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3836     }
3837 
3838     private boolean canSetPasswordQualityOnParent(String packageName, final CallerIdentity caller) {
3839         return !mInjector.isChangeEnabled(
3840                 PREVENT_SETTING_PASSWORD_QUALITY_ON_PARENT, packageName, caller.getUserId())
3841             || isProfileOwnerOfOrganizationOwnedDevice(caller);
3842     }
3843 
3844     private boolean isPasswordLimitingAdminTargetingP(CallerIdentity caller) {
3845         if (!caller.hasAdminComponent()) {
3846             return false;
3847         }
3848 
3849         synchronized (getLockObject()) {
3850             return getActiveAdminWithPolicyForUidLocked(
3851                     caller.getComponentName(), DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD,
3852                     caller.getUid()) != null;
3853         }
3854     }
3855 
3856     private boolean notSupportedOnAutomotive(String method) {
3857         if (mIsAutomotive) {
3858             Slogf.i(LOG_TAG, "%s is not supported on automotive builds", method);
3859             return true;
3860         }
3861         return false;
3862     }
3863 
3864     @Override
3865     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3866         if (!mHasFeature || notSupportedOnAutomotive("setPasswordQuality")) {
3867             return;
3868         }
3869         Objects.requireNonNull(who, "ComponentName is null");
3870         validateQualityConstant(quality);
3871 
3872         final CallerIdentity caller = getCallerIdentity(who);
3873         Preconditions.checkCallAuthorization(
3874                 isProfileOwner(caller) || isDeviceOwner(caller) || isSystemUid(caller)
3875                 || isPasswordLimitingAdminTargetingP(caller));
3876 
3877         if (parent) {
3878             Preconditions.checkCallAuthorization(
3879                     canSetPasswordQualityOnParent(who.getPackageName(), caller),
3880                     "Profile Owner may not apply password quality requirements device-wide");
3881         }
3882 
3883         final int userId = caller.getUserId();
3884         synchronized (getLockObject()) {
3885             ActiveAdmin ap = getActiveAdminForCallerLocked(
3886                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3887 
3888             // If setPasswordQuality is called on the parent, ensure that
3889             // the primary admin does not have password complexity state (this is an
3890             // unsupported state).
3891             if (parent) {
3892                 final ActiveAdmin primaryAdmin = getActiveAdminForCallerLocked(
3893                         who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, false);
3894                 final boolean hasComplexitySet =
3895                         primaryAdmin.mPasswordComplexity != PASSWORD_COMPLEXITY_NONE;
3896                 Preconditions.checkState(!hasComplexitySet,
3897                         "Cannot set password quality when complexity is set on the primary admin."
3898                         + " Set the primary admin's complexity to NONE first.");
3899             }
3900             mInjector.binderWithCleanCallingIdentity(() -> {
3901                 final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
3902                 if (passwordPolicy.quality != quality) {
3903                     passwordPolicy.quality = quality;
3904                     ap.mPasswordComplexity = PASSWORD_COMPLEXITY_NONE;
3905                     resetInactivePasswordRequirementsIfRPlus(userId, ap);
3906                     updatePasswordValidityCheckpointLocked(userId, parent);
3907                     updatePasswordQualityCacheForUserGroup(userId);
3908                     saveSettingsLocked(userId);
3909                 }
3910                 logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
3911             });
3912         }
3913         DevicePolicyEventLogger
3914                 .createEvent(DevicePolicyEnums.SET_PASSWORD_QUALITY)
3915                 .setAdmin(who)
3916                 .setInt(quality)
3917                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
3918                 .write();
3919     }
3920 
3921     private boolean passwordQualityInvocationOrderCheckEnabled(String packageName, int userId) {
3922         return mInjector.isChangeEnabled(ADMIN_APP_PASSWORD_COMPLEXITY, packageName, userId);
3923     }
3924 
3925     /**
3926      * For admins targeting R+ reset various password constraints to default values when quality is
3927      * set to a value that makes those constraints that have no effect.
3928      */
3929     private void resetInactivePasswordRequirementsIfRPlus(int userId, ActiveAdmin admin) {
3930         if (passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(), userId)) {
3931             final PasswordPolicy policy = admin.mPasswordPolicy;
3932             if (policy.quality < PASSWORD_QUALITY_NUMERIC) {
3933                 policy.length = PasswordPolicy.DEF_MINIMUM_LENGTH;
3934             }
3935             if (policy.quality < PASSWORD_QUALITY_COMPLEX) {
3936                 policy.letters = PasswordPolicy.DEF_MINIMUM_LETTERS;
3937                 policy.upperCase = PasswordPolicy.DEF_MINIMUM_UPPER_CASE;
3938                 policy.lowerCase = PasswordPolicy.DEF_MINIMUM_LOWER_CASE;
3939                 policy.numeric = PasswordPolicy.DEF_MINIMUM_NUMERIC;
3940                 policy.symbols = PasswordPolicy.DEF_MINIMUM_SYMBOLS;
3941                 policy.nonLetter = PasswordPolicy.DEF_MINIMUM_NON_LETTER;
3942             }
3943         }
3944     }
3945 
3946     /**
3947      * Updates a flag that tells us whether the user's password currently satisfies the
3948      * requirements set by all of the user's active admins.
3949      * This should be called whenever the password or the admin policies have changed. The caller
3950      * is responsible for calling {@link #saveSettingsLocked} to persist the change.
3951      *
3952      * @return the set of user IDs that have been affected
3953      */
3954     @GuardedBy("getLockObject()")
3955     private Set<Integer> updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) {
3956         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
3957         final int credentialOwner = getCredentialOwner(userHandle, parent);
3958         DevicePolicyData policy = getUserData(credentialOwner);
3959         PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
3960         // Update the checkpoint only if the user's password metrics is known
3961         if (metrics != null) {
3962             final int userToCheck = getProfileParentUserIfRequested(userHandle, parent);
3963             final boolean newCheckpoint = isPasswordSufficientForUserWithoutCheckpointLocked(
3964                     metrics, userToCheck);
3965             if (newCheckpoint != policy.mPasswordValidAtLastCheckpoint) {
3966                 policy.mPasswordValidAtLastCheckpoint = newCheckpoint;
3967                 affectedUserIds.add(credentialOwner);
3968             }
3969         }
3970         return affectedUserIds;
3971     }
3972 
3973     /**
3974      * Update password quality values in policy cache for all users in the same user group as
3975      * the given user. The cached password quality for user X is the aggregated quality among all
3976      * admins who have influence of user X's screenlock, i.e. it's equivalent to the return value of
3977      * getPasswordQuality(null, user X, false).
3978      *
3979      * Caches for all users in the same user group often need to be updated alltogether because a
3980      * user's admin policy can affect another's aggregated password quality in some situation.
3981      * For example a managed profile's policy will affect the parent user if the profile has unified
3982      * challenge. A profile can also explicitly set a parent password quality which will affect the
3983      * aggregated password quality of the parent user.
3984      */
3985     private void updatePasswordQualityCacheForUserGroup(@UserIdInt int userId) {
3986         final List<UserInfo> users;
3987         if (userId == UserHandle.USER_ALL) {
3988             users = mUserManager.getUsers();
3989         } else {
3990             users = mUserManager.getProfiles(userId);
3991         }
3992         for (UserInfo userInfo : users) {
3993             final int currentUserId = userInfo.id;
3994             mPolicyCache.setPasswordQuality(currentUserId,
3995                     getPasswordQuality(null, currentUserId, false));
3996         }
3997     }
3998 
3999     @Override
4000     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
4001         if (!mHasFeature) {
4002             return PASSWORD_QUALITY_UNSPECIFIED;
4003         }
4004         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4005 
4006         final CallerIdentity caller = getCallerIdentity();
4007         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4008         // System caller can query policy for a particular admin.
4009         Preconditions.checkCallAuthorization(
4010                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
4011                         || isSystemUid(caller));
4012 
4013         synchronized (getLockObject()) {
4014             int mode = PASSWORD_QUALITY_UNSPECIFIED;
4015 
4016             if (who != null) {
4017                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4018                 return admin != null ? admin.mPasswordPolicy.quality : mode;
4019             }
4020 
4021             // Return the strictest policy across all participating admins.
4022             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4023                     getProfileParentUserIfRequested(userHandle, parent));
4024             final int N = admins.size();
4025             for (int i = 0; i < N; i++) {
4026                 ActiveAdmin admin = admins.get(i);
4027                 if (mode < admin.mPasswordPolicy.quality) {
4028                     mode = admin.mPasswordPolicy.quality;
4029                 }
4030             }
4031             return mode;
4032         }
4033     }
4034 
4035     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(int userHandle) {
4036         if (isSeparateProfileChallengeEnabled(userHandle)) {
4037             // If this user has a separate challenge, only return its restrictions.
4038             return getUserDataUnchecked(userHandle).mAdminList;
4039         }
4040         // If isSeparateProfileChallengeEnabled is false and userHandle points to a managed profile
4041         // we need to query the parent user who owns the credential.
4042         return getActiveAdminsForUserAndItsManagedProfilesLocked(getProfileParentId(userHandle),
4043                 (user) -> !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
4044     }
4045 
4046     /**
4047      * Get the list of active admins for an affected user:
4048      * <ul>
4049      * <li>The active admins associated with the userHandle itself</li>
4050      * <li>The parent active admins for each managed profile associated with the userHandle</li>
4051      * </ul>
4052      *
4053      * @param userHandle the affected user for whom to get the active admins
4054      * @return the list of active admins for the affected user
4055      */
4056     @GuardedBy("getLockObject()")
4057     private List<ActiveAdmin> getActiveAdminsForAffectedUserLocked(int userHandle) {
4058         if (isManagedProfile(userHandle)) {
4059             return getUserDataUnchecked(userHandle).mAdminList;
4060         }
4061         return getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
4062                 /* shouldIncludeProfileAdmins */ (user) -> false);
4063     }
4064 
4065     /**
4066      * Returns the list of admins on the given user, as well as parent admins for each managed
4067      * profile associated with the given user. Optionally also include the admin of each managed
4068      * profile.
4069      * <p> Should not be called on a profile user.
4070      */
4071     @GuardedBy("getLockObject()")
4072     private List<ActiveAdmin> getActiveAdminsForUserAndItsManagedProfilesLocked(int userHandle,
4073             Predicate<UserInfo> shouldIncludeProfileAdmins) {
4074         ArrayList<ActiveAdmin> admins = new ArrayList<>();
4075         mInjector.binderWithCleanCallingIdentity(() -> {
4076             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4077                 DevicePolicyData policy = getUserDataUnchecked(userInfo.id);
4078                 if (userInfo.id == userHandle) {
4079                     admins.addAll(policy.mAdminList);
4080                 } else if (userInfo.isManagedProfile()) {
4081                     for (int i = 0; i < policy.mAdminList.size(); i++) {
4082                         ActiveAdmin admin = policy.mAdminList.get(i);
4083                         if (admin.hasParentActiveAdmin()) {
4084                             admins.add(admin.getParentActiveAdmin());
4085                         }
4086                         if (shouldIncludeProfileAdmins.test(userInfo)) {
4087                             admins.add(admin);
4088                         }
4089                     }
4090                 } else {
4091                     Slogf.w(LOG_TAG, "Unknown user type: " + userInfo);
4092                 }
4093             }
4094         });
4095         return admins;
4096     }
4097 
4098     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
4099         return mInjector.binderWithCleanCallingIdentity(() ->
4100                 mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle));
4101     }
4102 
4103     @Override
4104     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
4105         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLength")) {
4106             return;
4107         }
4108         Objects.requireNonNull(who, "ComponentName is null");
4109         final int userId = mInjector.userHandleGetCallingUserId();
4110         synchronized (getLockObject()) {
4111             ActiveAdmin ap = getActiveAdminForCallerLocked(
4112                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4113             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_NUMERIC, "setPasswordMinimumLength");
4114             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4115             if (passwordPolicy.length != length) {
4116                 passwordPolicy.length = length;
4117                 updatePasswordValidityCheckpointLocked(userId, parent);
4118                 saveSettingsLocked(userId);
4119             }
4120             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4121         }
4122         DevicePolicyEventLogger
4123                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LENGTH)
4124                 .setAdmin(who)
4125                 .setInt(length)
4126                 .write();
4127     }
4128 
4129     private void ensureMinimumQuality(
4130             int userId, ActiveAdmin admin, int minimumQuality, String operation) {
4131         mInjector.binderWithCleanCallingIdentity(() -> {
4132             // This check will also take care of the case where the password requirements
4133             // are specified as complexity rather than quality: When a password complexity
4134             // is set, the quality is reset to "unspecified" which will be below any value
4135             // of minimumQuality.
4136             if (admin.mPasswordPolicy.quality < minimumQuality
4137                     && passwordQualityInvocationOrderCheckEnabled(admin.info.getPackageName(),
4138                     userId)) {
4139                 throw new IllegalStateException(String.format(
4140                         "password quality should be at least %d for %s",
4141                         minimumQuality, operation));
4142             }
4143         });
4144     }
4145 
4146     @Override
4147     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
4148         return getStrictestPasswordRequirement(who, userHandle, parent,
4149                 admin -> admin.mPasswordPolicy.length, PASSWORD_QUALITY_NUMERIC);
4150     }
4151 
4152     @Override
4153     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
4154         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4155             return;
4156         }
4157         Objects.requireNonNull(who, "ComponentName is null");
4158         final int userId = mInjector.userHandleGetCallingUserId();
4159         synchronized (getLockObject()) {
4160             ActiveAdmin ap = getActiveAdminForCallerLocked(
4161                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4162             if (ap.passwordHistoryLength != length) {
4163                 ap.passwordHistoryLength = length;
4164                 updatePasswordValidityCheckpointLocked(userId, parent);
4165                 saveSettingsLocked(userId);
4166             }
4167         }
4168         if (SecurityLog.isLoggingEnabled()) {
4169             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4170             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET,
4171                     who.getPackageName(), userId, affectedUserId, length);
4172         }
4173     }
4174 
4175     @Override
4176     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
4177         if (!mLockPatternUtils.hasSecureLockScreen()) {
4178             return 0;
4179         }
4180         return getStrictestPasswordRequirement(who, userHandle, parent,
4181                 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
4182     }
4183 
4184     @Override
4185     public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
4186         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4187             return;
4188         }
4189         Objects.requireNonNull(who, "ComponentName is null");
4190         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
4191         final int userHandle = mInjector.userHandleGetCallingUserId();
4192         synchronized (getLockObject()) {
4193             ActiveAdmin ap = getActiveAdminForCallerLocked(
4194                     who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
4195             // Calling this API automatically bumps the expiration date
4196             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4197             ap.passwordExpirationDate = expiration;
4198             ap.passwordExpirationTimeout = timeout;
4199             if (timeout > 0L) {
4200                 Slogf.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
4201                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
4202                         .format(new Date(expiration)));
4203             }
4204             saveSettingsLocked(userHandle);
4205 
4206             // in case this is the first one, set the alarm on the appropriate user.
4207             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
4208         }
4209         if (SecurityLog.isLoggingEnabled()) {
4210             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
4211             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(),
4212                     userHandle, affectedUserId, timeout);
4213         }
4214     }
4215 
4216     /**
4217      * Return a single admin's expiration cycle time, or the min of all cycle times.
4218      * Returns 0 if not configured.
4219      */
4220     @Override
4221     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
4222         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4223             return 0L;
4224         }
4225         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4226 
4227         final CallerIdentity caller = getCallerIdentity(who);
4228         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4229 
4230         synchronized (getLockObject()) {
4231             long timeout = 0L;
4232 
4233             if (who != null) {
4234                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4235                 return admin != null ? admin.passwordExpirationTimeout : timeout;
4236             }
4237 
4238             // Return the strictest policy across all participating admins.
4239             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4240                     getProfileParentUserIfRequested(userHandle, parent));
4241             final int N = admins.size();
4242             for (int i = 0; i < N; i++) {
4243                 ActiveAdmin admin = admins.get(i);
4244                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
4245                         && timeout > admin.passwordExpirationTimeout)) {
4246                     timeout = admin.passwordExpirationTimeout;
4247                 }
4248             }
4249             return timeout;
4250         }
4251     }
4252 
4253     @Override
4254     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4255         Objects.requireNonNull(admin, "ComponentName is null");
4256 
4257         final CallerIdentity caller = getCallerIdentity(admin);
4258         Preconditions.checkCallAuthorization(isProfileOwner(caller));
4259         List<String> changedProviders = null;
4260 
4261         synchronized (getLockObject()) {
4262             ActiveAdmin activeAdmin = getProfileOwnerLocked(caller);
4263             if (activeAdmin.crossProfileWidgetProviders == null) {
4264                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
4265             }
4266             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4267             if (!providers.contains(packageName)) {
4268                 providers.add(packageName);
4269                 changedProviders = new ArrayList<>(providers);
4270                 saveSettingsLocked(caller.getUserId());
4271             }
4272         }
4273 
4274         DevicePolicyEventLogger
4275                 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_WIDGET_PROVIDER)
4276                 .setAdmin(admin)
4277                 .write();
4278 
4279         if (changedProviders != null) {
4280             mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(),
4281                     changedProviders);
4282             return true;
4283         }
4284 
4285         return false;
4286     }
4287 
4288     @Override
4289     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4290         Objects.requireNonNull(admin, "ComponentName is null");
4291 
4292         final CallerIdentity caller = getCallerIdentity(admin);
4293         Preconditions.checkCallAuthorization(isProfileOwner(caller));
4294         List<String> changedProviders = null;
4295 
4296         synchronized (getLockObject()) {
4297             ActiveAdmin activeAdmin = getProfileOwnerLocked(caller);
4298             if (activeAdmin.crossProfileWidgetProviders == null
4299                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4300                 return false;
4301             }
4302             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4303             if (providers.remove(packageName)) {
4304                 changedProviders = new ArrayList<>(providers);
4305                 saveSettingsLocked(caller.getUserId());
4306             }
4307         }
4308 
4309         DevicePolicyEventLogger
4310                 .createEvent(DevicePolicyEnums.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER)
4311                 .setAdmin(admin)
4312                 .write();
4313 
4314         if (changedProviders != null) {
4315             mLocalService.notifyCrossProfileProvidersChanged(caller.getUserId(),
4316                     changedProviders);
4317             return true;
4318         }
4319 
4320         return false;
4321     }
4322 
4323     @Override
4324     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
4325         Objects.requireNonNull(admin, "ComponentName is null");
4326 
4327         final CallerIdentity caller = getCallerIdentity(admin);
4328         Preconditions.checkCallAuthorization(isProfileOwner(caller));
4329 
4330         synchronized (getLockObject()) {
4331             ActiveAdmin activeAdmin = getProfileOwnerLocked(caller);
4332             if (activeAdmin.crossProfileWidgetProviders == null
4333                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4334                 return null;
4335             }
4336             if (mInjector.binderIsCallingUidMyUid()) {
4337                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
4338             } else {
4339                 return activeAdmin.crossProfileWidgetProviders;
4340             }
4341         }
4342     }
4343 
4344     /**
4345      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
4346      * Returns 0 if not configured.
4347      */
4348     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
4349         long timeout = 0L;
4350 
4351         if (who != null) {
4352             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4353             return admin != null ? admin.passwordExpirationDate : timeout;
4354         }
4355 
4356         // Return the strictest policy across all participating admins.
4357         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4358                 getProfileParentUserIfRequested(userHandle, parent));
4359         final int N = admins.size();
4360         for (int i = 0; i < N; i++) {
4361             ActiveAdmin admin = admins.get(i);
4362             if (timeout == 0L || (admin.passwordExpirationDate != 0
4363                     && timeout > admin.passwordExpirationDate)) {
4364                 timeout = admin.passwordExpirationDate;
4365             }
4366         }
4367         return timeout;
4368     }
4369 
4370     @Override
4371     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
4372         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4373             return 0L;
4374         }
4375         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4376 
4377         final CallerIdentity caller = getCallerIdentity(who);
4378         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4379 
4380         synchronized (getLockObject()) {
4381             return getPasswordExpirationLocked(who, userHandle, parent);
4382         }
4383     }
4384 
4385     @Override
4386     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
4387         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumUpperCase")) {
4388             return;
4389         }
4390         Objects.requireNonNull(who, "ComponentName is null");
4391         final int userId = mInjector.userHandleGetCallingUserId();
4392         synchronized (getLockObject()) {
4393             final ActiveAdmin ap = getActiveAdminForCallerLocked(
4394                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4395             ensureMinimumQuality(
4396                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumUpperCase");
4397             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4398             if (passwordPolicy.upperCase != length) {
4399                 passwordPolicy.upperCase = length;
4400                 updatePasswordValidityCheckpointLocked(userId, parent);
4401                 saveSettingsLocked(userId);
4402             }
4403             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4404         }
4405         DevicePolicyEventLogger
4406                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_UPPER_CASE)
4407                 .setAdmin(who)
4408                 .setInt(length)
4409                 .write();
4410     }
4411 
4412     @Override
4413     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
4414         return getStrictestPasswordRequirement(who, userHandle, parent,
4415                 admin -> admin.mPasswordPolicy.upperCase, PASSWORD_QUALITY_COMPLEX);
4416     }
4417 
4418     @Override
4419     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
4420         if (notSupportedOnAutomotive("setPasswordMinimumLowerCase")) {
4421             return;
4422         }
4423         Objects.requireNonNull(who, "ComponentName is null");
4424         final int userId = mInjector.userHandleGetCallingUserId();
4425         synchronized (getLockObject()) {
4426             ActiveAdmin ap = getActiveAdminForCallerLocked(
4427                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4428             ensureMinimumQuality(
4429                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLowerCase");
4430             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4431             if (passwordPolicy.lowerCase != length) {
4432                 passwordPolicy.lowerCase = length;
4433                 updatePasswordValidityCheckpointLocked(userId, parent);
4434                 saveSettingsLocked(userId);
4435             }
4436             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4437         }
4438         DevicePolicyEventLogger
4439                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LOWER_CASE)
4440                 .setAdmin(who)
4441                 .setInt(length)
4442                 .write();
4443     }
4444 
4445     @Override
4446     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
4447         return getStrictestPasswordRequirement(who, userHandle, parent,
4448                 admin -> admin.mPasswordPolicy.lowerCase, PASSWORD_QUALITY_COMPLEX);
4449     }
4450 
4451     @Override
4452     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
4453         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumLetters")) {
4454             return;
4455         }
4456         Objects.requireNonNull(who, "ComponentName is null");
4457         final int userId = mInjector.userHandleGetCallingUserId();
4458         synchronized (getLockObject()) {
4459             ActiveAdmin ap = getActiveAdminForCallerLocked(
4460                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4461             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumLetters");
4462             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4463             if (passwordPolicy.letters != length) {
4464                 passwordPolicy.letters = length;
4465                 updatePasswordValidityCheckpointLocked(userId, parent);
4466                 saveSettingsLocked(userId);
4467             }
4468             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4469         }
4470         DevicePolicyEventLogger
4471                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LETTERS)
4472                 .setAdmin(who)
4473                 .setInt(length)
4474                 .write();
4475     }
4476 
4477     @Override
4478     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
4479         return getStrictestPasswordRequirement(who, userHandle, parent,
4480                 admin -> admin.mPasswordPolicy.letters, PASSWORD_QUALITY_COMPLEX);
4481     }
4482 
4483     @Override
4484     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
4485         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNumeric")) {
4486             return;
4487         }
4488         Objects.requireNonNull(who, "ComponentName is null");
4489         final int userId = mInjector.userHandleGetCallingUserId();
4490         synchronized (getLockObject()) {
4491             ActiveAdmin ap = getActiveAdminForCallerLocked(
4492                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4493             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNumeric");
4494             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4495             if (passwordPolicy.numeric != length) {
4496                 passwordPolicy.numeric = length;
4497                 updatePasswordValidityCheckpointLocked(userId, parent);
4498                 saveSettingsLocked(userId);
4499             }
4500             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4501         }
4502         DevicePolicyEventLogger
4503                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NUMERIC)
4504                 .setAdmin(who)
4505                 .setInt(length)
4506                 .write();
4507     }
4508 
4509     @Override
4510     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
4511         return getStrictestPasswordRequirement(who, userHandle, parent,
4512                 admin -> admin.mPasswordPolicy.numeric, PASSWORD_QUALITY_COMPLEX);
4513     }
4514 
4515     @Override
4516     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
4517         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumSymbols")) {
4518             return;
4519         }
4520         Objects.requireNonNull(who, "ComponentName is null");
4521         final int userId = mInjector.userHandleGetCallingUserId();
4522         synchronized (getLockObject()) {
4523             ActiveAdmin ap = getActiveAdminForCallerLocked(
4524                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4525             ensureMinimumQuality(userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumSymbols");
4526             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4527             if (passwordPolicy.symbols != length) {
4528                 ap.mPasswordPolicy.symbols = length;
4529                 updatePasswordValidityCheckpointLocked(userId, parent);
4530                 saveSettingsLocked(userId);
4531             }
4532             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4533         }
4534         DevicePolicyEventLogger
4535                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_SYMBOLS)
4536                 .setAdmin(who)
4537                 .setInt(length)
4538                 .write();
4539     }
4540 
4541     @Override
4542     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
4543         return getStrictestPasswordRequirement(who, userHandle, parent,
4544                 admin -> admin.mPasswordPolicy.symbols, PASSWORD_QUALITY_COMPLEX);
4545     }
4546 
4547     @Override
4548     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
4549         if (!mHasFeature || notSupportedOnAutomotive("setPasswordMinimumNonLetter")) {
4550             return;
4551         }
4552         Objects.requireNonNull(who, "ComponentName is null");
4553         final int userId = mInjector.userHandleGetCallingUserId();
4554         synchronized (getLockObject()) {
4555             ActiveAdmin ap = getActiveAdminForCallerLocked(
4556                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4557             ensureMinimumQuality(
4558                     userId, ap, PASSWORD_QUALITY_COMPLEX, "setPasswordMinimumNonLetter");
4559             final PasswordPolicy passwordPolicy = ap.mPasswordPolicy;
4560             if (passwordPolicy.nonLetter != length) {
4561                 ap.mPasswordPolicy.nonLetter = length;
4562                 updatePasswordValidityCheckpointLocked(userId, parent);
4563                 saveSettingsLocked(userId);
4564             }
4565             logPasswordQualitySetIfSecurityLogEnabled(who, userId, parent, passwordPolicy);
4566         }
4567         DevicePolicyEventLogger
4568                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NON_LETTER)
4569                 .setAdmin(who)
4570                 .setInt(length)
4571                 .write();
4572     }
4573 
4574     @Override
4575     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
4576         return getStrictestPasswordRequirement(who, userHandle, parent,
4577                 admin -> admin.mPasswordPolicy.nonLetter, PASSWORD_QUALITY_COMPLEX);
4578     }
4579 
4580     /**
4581      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
4582      */
4583     private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
4584             boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
4585         if (!mHasFeature) {
4586             return 0;
4587         }
4588         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4589 
4590         final CallerIdentity caller = getCallerIdentity(who);
4591         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4592 
4593         synchronized (getLockObject()) {
4594             if (who != null) {
4595                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4596                 return admin != null ? getter.apply(admin) : 0;
4597             }
4598 
4599             int maxValue = 0;
4600             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4601                     getProfileParentUserIfRequested(userHandle, parent));
4602             final int N = admins.size();
4603             for (int i = 0; i < N; i++) {
4604                 final ActiveAdmin admin = admins.get(i);
4605                 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
4606                     continue;
4607                 }
4608                 final Integer adminValue = getter.apply(admin);
4609                 if (adminValue > maxValue) {
4610                     maxValue = adminValue;
4611                 }
4612             }
4613             return maxValue;
4614         }
4615     }
4616 
4617     /**
4618      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
4619      */
4620     @Override
4621     public PasswordMetrics getPasswordMinimumMetrics(@UserIdInt int userHandle,
4622             boolean deviceWideOnly) {
4623         final CallerIdentity caller = getCallerIdentity();
4624         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4625         return getPasswordMinimumMetricsUnchecked(userHandle, deviceWideOnly);
4626     }
4627 
4628     private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId) {
4629         return getPasswordMinimumMetricsUnchecked(userId, false);
4630     }
4631 
4632     private PasswordMetrics getPasswordMinimumMetricsUnchecked(@UserIdInt int userId,
4633             boolean deviceWideOnly) {
4634         if (!mHasFeature) {
4635             new PasswordMetrics(CREDENTIAL_TYPE_NONE);
4636         }
4637         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
4638         if (deviceWideOnly) {
4639             Preconditions.checkArgument(!isManagedProfile(userId));
4640         }
4641 
4642         ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>();
4643         final List<ActiveAdmin> admins;
4644         synchronized (getLockObject()) {
4645             if (deviceWideOnly) {
4646                 admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userId,
4647                         /* shouldIncludeProfileAdmins */ (user) -> false);
4648             } else {
4649                 admins = getActiveAdminsForLockscreenPoliciesLocked(userId);
4650             }
4651             for (ActiveAdmin admin : admins) {
4652                 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
4653             }
4654         }
4655         return PasswordMetrics.merge(adminMetrics);
4656     }
4657 
4658     @Override
4659     public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
4660         if (!mHasFeature) {
4661             return true;
4662         }
4663         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4664 
4665         final CallerIdentity caller = getCallerIdentity();
4666         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4667         enforceUserUnlocked(userHandle, parent);
4668 
4669         synchronized (getLockObject()) {
4670             // This API can only be called by an active device admin,
4671             // so try to retrieve it to check that the caller is one.
4672             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4673             int credentialOwner = getCredentialOwner(userHandle, parent);
4674             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
4675             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
4676             final int userToCheck = getProfileParentUserIfRequested(userHandle, parent);
4677             boolean activePasswordSufficientForUserLocked = isActivePasswordSufficientForUserLocked(
4678                     policy.mPasswordValidAtLastCheckpoint, metrics, userToCheck);
4679             return activePasswordSufficientForUserLocked;
4680         }
4681     }
4682 
4683     @Override
4684     public boolean isActivePasswordSufficientForDeviceRequirement() {
4685         if (!mHasFeature) {
4686             return true;
4687         }
4688         final CallerIdentity caller = getCallerIdentity();
4689         Preconditions.checkCallAuthorization(isProfileOwner(caller));
4690 
4691         final int profileUserId = caller.getUserId();
4692         Preconditions.checkCallingUser(isManagedProfile(profileUserId));
4693 
4694         // This method is always called on the parent DPM instance to check if its password (i.e.
4695         // the device password) is sufficient for all explicit password requirement set on it
4696         // So retrieve the parent user Id to which the device password belongs.
4697         final int parentUser = getProfileParentId(profileUserId);
4698         enforceUserUnlocked(parentUser);
4699 
4700         final boolean isSufficient;
4701         synchronized (getLockObject()) {
4702 
4703             int complexity = getAggregatedPasswordComplexityLocked(parentUser, true);
4704             PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(parentUser, true);
4705 
4706             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(parentUser);
4707             final List<PasswordValidationError> passwordValidationErrors =
4708                     PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics);
4709             isSufficient = passwordValidationErrors.isEmpty();
4710         }
4711         DevicePolicyEventLogger
4712                 .createEvent(DevicePolicyEnums.IS_ACTIVE_PASSWORD_SUFFICIENT_FOR_DEVICE)
4713                 .setStrings(mOwners.getProfileOwnerComponent(caller.getUserId()).getPackageName())
4714                 .write();
4715         return isSufficient;
4716     }
4717 
4718     @Override
4719     public boolean isUsingUnifiedPassword(ComponentName admin) {
4720         if (!mHasFeature) {
4721             return true;
4722         }
4723         Objects.requireNonNull(admin, "ComponentName is null");
4724 
4725         final CallerIdentity caller = getCallerIdentity(admin);
4726         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
4727         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
4728 
4729         return !isSeparateProfileChallengeEnabled(caller.getUserId());
4730     }
4731 
4732     @Override
4733     public boolean isPasswordSufficientAfterProfileUnification(int userHandle, int profileUser) {
4734         if (!mHasFeature) {
4735             return true;
4736         }
4737         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4738 
4739         final CallerIdentity caller = getCallerIdentity();
4740         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4741         Preconditions.checkCallAuthorization(!isManagedProfile(userHandle),
4742                 "You can not check password sufficiency for a managed profile, userId = %d",
4743                 userHandle);
4744         enforceUserUnlocked(userHandle);
4745 
4746         synchronized (getLockObject()) {
4747             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(userHandle);
4748 
4749             // Combine password policies across the user and its profiles. Profile admins are
4750             // included if the profile is to be unified or currently has unified challenge
4751             List<ActiveAdmin> admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
4752                     /* shouldIncludeProfileAdmins */ (user) -> user.id == profileUser
4753                     || !mLockPatternUtils.isSeparateProfileChallengeEnabled(user.id));
4754             ArrayList<PasswordMetrics> adminMetrics = new ArrayList<>(admins.size());
4755             int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE;
4756             for (ActiveAdmin admin : admins) {
4757                 adminMetrics.add(admin.mPasswordPolicy.getMinMetrics());
4758                 maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity);
4759             }
4760             return PasswordMetrics.validatePasswordMetrics(PasswordMetrics.merge(adminMetrics),
4761                     maxRequiredComplexity, metrics).isEmpty();
4762         }
4763     }
4764 
4765     private boolean isActivePasswordSufficientForUserLocked(
4766             boolean passwordValidAtLastCheckpoint, @Nullable PasswordMetrics metrics,
4767             int userHandle) {
4768         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) {
4769             // Before user enters their password for the first time after a reboot, return the
4770             // value of this flag, which tells us whether the password was valid the last time
4771             // settings were saved.  If DPC changes password requirements on boot so that the
4772             // current password no longer meets the requirements, this value will be stale until
4773             // the next time the password is entered.
4774             return passwordValidAtLastCheckpoint;
4775         }
4776 
4777         if (metrics == null) {
4778             // Called on a FBE device when the user password exists but its metrics is unknown.
4779             // This shouldn't happen since we enforce the user to be unlocked (which would result
4780             // in the metrics known to the framework on a FBE device) at all call sites.
4781             throw new IllegalStateException("isActivePasswordSufficient called on FBE-locked user");
4782         }
4783 
4784         return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle);
4785     }
4786 
4787     /**
4788      * Returns {@code true} if the password represented by the {@code metrics} argument
4789      * sufficiently fulfills the password requirements for the user corresponding to
4790      * {@code userId}.
4791      */
4792     private boolean isPasswordSufficientForUserWithoutCheckpointLocked(
4793             @NonNull PasswordMetrics metrics, @UserIdInt int userId) {
4794         final int complexity = getAggregatedPasswordComplexityLocked(userId);
4795         PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userId);
4796         final List<PasswordValidationError> passwordValidationErrors =
4797                 PasswordMetrics.validatePasswordMetrics(minMetrics, complexity, metrics);
4798         return passwordValidationErrors.isEmpty();
4799     }
4800 
4801     @Override
4802     @PasswordComplexity
4803     public int getPasswordComplexity(boolean parent) {
4804         final CallerIdentity caller = getCallerIdentity();
4805         DevicePolicyEventLogger
4806                 .createEvent(DevicePolicyEnums.GET_USER_PASSWORD_COMPLEXITY_LEVEL)
4807                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT,
4808                         mInjector.getPackageManager().getPackagesForUid(caller.getUid()))
4809                 .write();
4810 
4811         enforceUserUnlocked(caller.getUserId());
4812         if (parent) {
4813             Preconditions.checkCallAuthorization(
4814                     isDeviceOwner(caller) || isProfileOwner(caller) || isSystemUid(caller),
4815                     "Only profile owner, device owner and system may call this method on parent.");
4816         } else {
4817             Preconditions.checkCallAuthorization(
4818                     hasCallingOrSelfPermission(REQUEST_PASSWORD_COMPLEXITY)
4819                             || isDeviceOwner(caller) || isProfileOwner(caller),
4820                     "Must have " + REQUEST_PASSWORD_COMPLEXITY
4821                             + " permission, or be a profile owner or device owner.");
4822         }
4823 
4824         synchronized (getLockObject()) {
4825             final int credentialOwner = getCredentialOwner(caller.getUserId(), parent);
4826             PasswordMetrics metrics = mLockSettingsInternal.getUserPasswordMetrics(credentialOwner);
4827             return metrics == null ? PASSWORD_COMPLEXITY_NONE : metrics.determineComplexity();
4828         }
4829     }
4830 
4831     @Override
4832     public void setRequiredPasswordComplexity(int passwordComplexity, boolean calledOnParent) {
4833         if (!mHasFeature) {
4834             return;
4835         }
4836         final Set<Integer> allowedModes = Set.of(PASSWORD_COMPLEXITY_NONE, PASSWORD_COMPLEXITY_LOW,
4837                 PASSWORD_COMPLEXITY_MEDIUM, PASSWORD_COMPLEXITY_HIGH);
4838         Preconditions.checkArgument(allowedModes.contains(passwordComplexity),
4839                 "Provided complexity is not one of the allowed values.");
4840 
4841         final CallerIdentity caller = getCallerIdentity();
4842         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
4843         Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
4844 
4845         synchronized (getLockObject()) {
4846             final ActiveAdmin admin = getParentOfAdminIfRequired(
4847                     getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParent);
4848             if (admin.mPasswordComplexity != passwordComplexity) {
4849                 // We require the caller to explicitly clear any password quality requirements set
4850                 // on the parent DPM instance, to avoid the case where password requirements are
4851                 // specified in the form of quality on the parent but complexity on the profile
4852                 // itself.
4853                 if (!calledOnParent) {
4854                     final boolean hasQualityRequirementsOnParent = admin.hasParentActiveAdmin()
4855                             && admin.getParentActiveAdmin().mPasswordPolicy.quality
4856                             != PASSWORD_QUALITY_UNSPECIFIED;
4857                     Preconditions.checkState(!hasQualityRequirementsOnParent,
4858                             "Password quality is set on the parent when attempting to set password"
4859                             + "complexity. Clear the quality by setting the password quality "
4860                             + "on the parent to PASSWORD_QUALITY_UNSPECIFIED first");
4861                 }
4862 
4863                 mInjector.binderWithCleanCallingIdentity(() -> {
4864                     admin.mPasswordComplexity = passwordComplexity;
4865                     // Reset the password policy.
4866                     admin.mPasswordPolicy = new PasswordPolicy();
4867                     updatePasswordValidityCheckpointLocked(caller.getUserId(), calledOnParent);
4868                     updatePasswordQualityCacheForUserGroup(caller.getUserId());
4869                     saveSettingsLocked(caller.getUserId());
4870                 });
4871 
4872                 DevicePolicyEventLogger
4873                         .createEvent(DevicePolicyEnums.SET_PASSWORD_COMPLEXITY)
4874                         .setAdmin(admin.info.getPackageName())
4875                         .setInt(passwordComplexity)
4876                         .setBoolean(calledOnParent)
4877                         .write();
4878             }
4879             logPasswordComplexityRequiredIfSecurityLogEnabled(admin.info.getComponent(),
4880                     caller.getUserId(), calledOnParent, passwordComplexity);
4881         }
4882     }
4883 
4884     private void logPasswordComplexityRequiredIfSecurityLogEnabled(ComponentName who, int userId,
4885             boolean parent, int complexity) {
4886         if (SecurityLog.isLoggingEnabled()) {
4887             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4888             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_REQUIRED,
4889                     who.getPackageName(), userId, affectedUserId, complexity);
4890         }
4891     }
4892 
4893     private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle) {
4894         return getAggregatedPasswordComplexityLocked(userHandle, false);
4895     }
4896 
4897     private int getAggregatedPasswordComplexityLocked(@UserIdInt int userHandle,
4898             boolean deviceWideOnly) {
4899         ensureLocked();
4900         final List<ActiveAdmin> admins;
4901         if (deviceWideOnly) {
4902             admins = getActiveAdminsForUserAndItsManagedProfilesLocked(userHandle,
4903                     /* shouldIncludeProfileAdmins */ (user) -> false);
4904         } else {
4905             admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
4906         }
4907         int maxRequiredComplexity = PASSWORD_COMPLEXITY_NONE;
4908         for (ActiveAdmin admin : admins) {
4909             maxRequiredComplexity = Math.max(maxRequiredComplexity, admin.mPasswordComplexity);
4910         }
4911         return maxRequiredComplexity;
4912     }
4913 
4914     @Override
4915     public int getRequiredPasswordComplexity(boolean calledOnParent) {
4916         if (!mHasFeature) {
4917             return PASSWORD_COMPLEXITY_NONE;
4918         }
4919 
4920         final CallerIdentity caller = getCallerIdentity();
4921         Preconditions.checkCallAuthorization(
4922                 isDeviceOwner(caller) || isProfileOwner(caller));
4923 
4924         Preconditions.checkArgument(!calledOnParent || isProfileOwner(caller));
4925 
4926         synchronized (getLockObject()) {
4927             final ActiveAdmin requiredAdmin = getParentOfAdminIfRequired(
4928                     getDeviceOrProfileOwnerAdminLocked(caller.getUserId()), calledOnParent);
4929             return requiredAdmin.mPasswordComplexity;
4930         }
4931     }
4932 
4933     @Override
4934     public int getAggregatedPasswordComplexityForUser(int userId, boolean deviceWideOnly) {
4935         if (!mHasFeature) {
4936             return PASSWORD_COMPLEXITY_NONE;
4937         }
4938 
4939         final CallerIdentity caller = getCallerIdentity();
4940         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
4941 
4942         synchronized (getLockObject()) {
4943             return getAggregatedPasswordComplexityLocked(userId, deviceWideOnly);
4944         }
4945     }
4946 
4947 
4948     @Override
4949     public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4950         if (!mLockPatternUtils.hasSecureLockScreen()) {
4951             return 0;
4952         }
4953         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
4954 
4955         final CallerIdentity caller = getCallerIdentity();
4956         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
4957 
4958         synchronized (getLockObject()) {
4959             if (!isSystemUid(caller)) {
4960                 // This API can be called by an active device admin or by keyguard code.
4961                 if (!hasCallingPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)) {
4962                     getActiveAdminForCallerLocked(
4963                             null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4964                 }
4965             }
4966 
4967             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4968 
4969             return policy.mFailedPasswordAttempts;
4970         }
4971     }
4972 
4973     @Override
4974     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4975         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4976             return;
4977         }
4978         Objects.requireNonNull(who, "ComponentName is null");
4979         final int userId = mInjector.userHandleGetCallingUserId();
4980         synchronized (getLockObject()) {
4981             // This API can only be called by an active device admin,
4982             // so try to retrieve it to check that the caller is one.
4983             getActiveAdminForCallerLocked(
4984                     who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4985             ActiveAdmin ap = getActiveAdminForCallerLocked(
4986                     who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4987             if (ap.maximumFailedPasswordsForWipe != num) {
4988                 ap.maximumFailedPasswordsForWipe = num;
4989                 saveSettingsLocked(userId);
4990             }
4991         }
4992         if (SecurityLog.isLoggingEnabled()) {
4993             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4994             SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(),
4995                     userId, affectedUserId, num);
4996         }
4997     }
4998 
4999     @Override
5000     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
5001         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5002             return 0;
5003         }
5004         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5005 
5006         final CallerIdentity caller = getCallerIdentity();
5007         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5008         // System caller can query policy for a particular admin.
5009         Preconditions.checkCallAuthorization(
5010                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
5011                         || isSystemUid(caller));
5012 
5013         synchronized (getLockObject()) {
5014             ActiveAdmin admin = (who != null)
5015                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
5016                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
5017             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
5018         }
5019     }
5020 
5021     @Override
5022     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
5023         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5024             return UserHandle.USER_NULL;
5025         }
5026         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5027 
5028         final CallerIdentity caller = getCallerIdentity();
5029         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5030 
5031         synchronized (getLockObject()) {
5032             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5033                     userHandle, parent);
5034             return admin != null ? getUserIdToWipeForFailedPasswords(admin) : UserHandle.USER_NULL;
5035         }
5036     }
5037 
5038     /**
5039      * Returns the admin with the strictest policy on maximum failed passwords for:
5040      * <ul>
5041      *   <li>this user if it has a separate profile challenge, or
5042      *   <li>this user and all profiles that don't have their own challenge otherwise.
5043      * </ul>
5044      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
5045      * the primary profile. Policy of a PO on an organization-owned device applies to the primary
5046      * profile.
5047      * Returns {@code null} if no participating admin has that policy set.
5048      */
5049     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
5050             int userHandle, boolean parent) {
5051         int count = 0;
5052         ActiveAdmin strictestAdmin = null;
5053 
5054         // Return the strictest policy across all participating admins.
5055         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5056                 getProfileParentUserIfRequested(userHandle, parent));
5057         final int N = admins.size();
5058         for (int i = 0; i < N; i++) {
5059             ActiveAdmin admin = admins.get(i);
5060             if (admin.maximumFailedPasswordsForWipe ==
5061                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
5062                 continue;  // No max number of failed passwords policy set for this profile.
5063             }
5064 
5065             // We always favor the primary profile if several profiles have the same value set.
5066             final int userId = getUserIdToWipeForFailedPasswords(admin);
5067             if (count == 0 ||
5068                     count > admin.maximumFailedPasswordsForWipe ||
5069                     (count == admin.maximumFailedPasswordsForWipe &&
5070                             getUserInfo(userId).isPrimary())) {
5071                 count = admin.maximumFailedPasswordsForWipe;
5072                 strictestAdmin = admin;
5073             }
5074         }
5075         return strictestAdmin;
5076     }
5077 
5078     private UserInfo getUserInfo(@UserIdInt int userId) {
5079         return mInjector.binderWithCleanCallingIdentity(() -> mUserManager.getUserInfo(userId));
5080     }
5081 
5082     private boolean setPasswordPrivileged(@NonNull String password, int flags,
5083             CallerIdentity caller) {
5084         // Only allow setting password on an unsecured user
5085         if (isLockScreenSecureUnchecked(caller.getUserId())) {
5086             throw new SecurityException("Cannot change current password");
5087         }
5088         return resetPasswordInternal(password, 0, null, flags, caller);
5089     }
5090 
5091     @Override
5092     public boolean resetPassword(@Nullable String password, int flags) throws RemoteException {
5093         if (!mLockPatternUtils.hasSecureLockScreen()) {
5094             Slogf.w(LOG_TAG, "Cannot reset password when the device has no lock screen");
5095             return false;
5096         }
5097         if (password == null) password = "";
5098         final CallerIdentity caller = getCallerIdentity();
5099         final int userHandle = caller.getUserId();
5100 
5101         // As of R, only privileged caller holding RESET_PASSWORD can call resetPassword() to
5102         // set password to an unsecured user.
5103         if (hasCallingPermission(permission.RESET_PASSWORD)) {
5104             final boolean result = setPasswordPrivileged(password, flags, caller);
5105             if (result) {
5106                 DevicePolicyEventLogger
5107                         .createEvent(DevicePolicyEnums.RESET_PASSWORD)
5108                         .write();
5109             }
5110             return result;
5111         }
5112 
5113         // If caller has PO (or DO) throw or fail silently depending on its target SDK level.
5114         if (isDeviceOwner(caller) || isProfileOwner(caller)) {
5115             synchronized (getLockObject()) {
5116                 ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
5117                 if (getTargetSdk(admin.info.getPackageName(), userHandle) < Build.VERSION_CODES.O) {
5118                     Slogf.e(LOG_TAG, "DPC can no longer call resetPassword()");
5119                     return false;
5120                 }
5121                 throw new SecurityException("Device admin can no longer call resetPassword()");
5122             }
5123         }
5124 
5125         // Caller is not DO or PO, could either be unauthorized or Device Admin.
5126         synchronized (getLockObject()) {
5127             // Legacy device admin cannot call resetPassword either
5128             ActiveAdmin admin = getActiveAdminForCallerLocked(
5129                     null, DeviceAdminInfo.USES_POLICY_RESET_PASSWORD, false);
5130             Preconditions.checkCallAuthorization(admin != null,
5131                     "Unauthorized caller cannot call resetPassword.");
5132             if (getTargetSdk(admin.info.getPackageName(),
5133                     userHandle) <= android.os.Build.VERSION_CODES.M) {
5134                 Slogf.e(LOG_TAG, "Device admin can no longer call resetPassword()");
5135                 return false;
5136             }
5137             throw new SecurityException("Device admin can no longer call resetPassword()");
5138         }
5139     }
5140 
5141     private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
5142             int flags, CallerIdentity caller) {
5143         final int callingUid = caller.getUid();
5144         final int userHandle = UserHandle.getUserId(callingUid);
5145         final boolean isPin = PasswordMetrics.isNumericOnly(password);
5146         synchronized (getLockObject()) {
5147             final PasswordMetrics minMetrics = getPasswordMinimumMetricsUnchecked(userHandle);
5148             final List<PasswordValidationError> validationErrors;
5149             final int complexity = getAggregatedPasswordComplexityLocked(userHandle);
5150             // TODO: Consider changing validation API to take LockscreenCredential.
5151             if (password.isEmpty()) {
5152                 validationErrors = PasswordMetrics.validatePasswordMetrics(
5153                         minMetrics, complexity, new PasswordMetrics(CREDENTIAL_TYPE_NONE));
5154             } else {
5155                 // TODO(b/120484642): remove getBytes() below
5156                 validationErrors = PasswordMetrics.validatePassword(
5157                         minMetrics, complexity, isPin, password.getBytes());
5158             }
5159 
5160             if (!validationErrors.isEmpty()) {
5161                 Slogf.w(LOG_TAG, "Failed to reset password due to constraint violation: %s",
5162                         validationErrors.get(0));
5163                 return false;
5164             }
5165         }
5166 
5167         DevicePolicyData policy = getUserData(userHandle);
5168         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
5169             Slogf.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
5170             return false;
5171         }
5172 
5173         boolean callerIsDeviceOwnerAdmin = isDeviceOwner(caller);
5174         boolean doNotAskCredentialsOnBoot =
5175                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
5176         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
5177             setDoNotAskCredentialsOnBoot();
5178         }
5179 
5180         // Don't do this with the lock held, because it is going to call
5181         // back in to the service.
5182         final long ident = mInjector.binderClearCallingIdentity();
5183         final LockscreenCredential newCredential;
5184         if (isPin) {
5185             newCredential = LockscreenCredential.createPin(password);
5186         } else {
5187             newCredential = LockscreenCredential.createPasswordOrNone(password);
5188         }
5189         try {
5190             if (tokenHandle == 0 || token == null) {
5191                 if (!mLockPatternUtils.setLockCredential(newCredential,
5192                         LockscreenCredential.createNone(), userHandle)) {
5193                     return false;
5194                 }
5195             } else {
5196                 if (!mLockPatternUtils.setLockCredentialWithToken(newCredential, tokenHandle,
5197                         token, userHandle)) {
5198                     return false;
5199                 }
5200             }
5201             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
5202             if (requireEntry) {
5203                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
5204                         UserHandle.USER_ALL);
5205             }
5206             synchronized (getLockObject()) {
5207                 int newOwner = requireEntry ? callingUid : -1;
5208                 if (policy.mPasswordOwner != newOwner) {
5209                     policy.mPasswordOwner = newOwner;
5210                     saveSettingsLocked(userHandle);
5211                 }
5212             }
5213         } finally {
5214             mInjector.binderRestoreCallingIdentity(ident);
5215         }
5216         return true;
5217     }
5218 
5219     private boolean isLockScreenSecureUnchecked(int userId) {
5220         return mInjector.binderWithCleanCallingIdentity(() -> mLockPatternUtils.isSecure(userId));
5221     }
5222 
5223     private void setDoNotAskCredentialsOnBoot() {
5224         synchronized (getLockObject()) {
5225             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
5226             if (!policyData.mDoNotAskCredentialsOnBoot) {
5227                 policyData.mDoNotAskCredentialsOnBoot = true;
5228                 saveSettingsLocked(UserHandle.USER_SYSTEM);
5229             }
5230         }
5231     }
5232 
5233     @Override
5234     public boolean getDoNotAskCredentialsOnBoot() {
5235         Preconditions.checkCallAuthorization(
5236                 hasCallingOrSelfPermission(permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT));
5237         synchronized (getLockObject()) {
5238             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
5239             return policyData.mDoNotAskCredentialsOnBoot;
5240         }
5241     }
5242 
5243     @Override
5244     public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
5245         if (!mHasFeature) {
5246             return;
5247         }
5248         Objects.requireNonNull(who, "ComponentName is null");
5249         final int userHandle = mInjector.userHandleGetCallingUserId();
5250         synchronized (getLockObject()) {
5251             final ActiveAdmin ap = getActiveAdminForCallerLocked(
5252                     who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
5253             if (ap.maximumTimeToUnlock != timeMs) {
5254                 ap.maximumTimeToUnlock = timeMs;
5255                 saveSettingsLocked(userHandle);
5256                 updateMaximumTimeToLockLocked(userHandle);
5257             }
5258         }
5259         if (SecurityLog.isLoggingEnabled()) {
5260             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
5261             SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
5262                     who.getPackageName(), userHandle, affectedUserId, timeMs);
5263         }
5264     }
5265 
5266     private void updateMaximumTimeToLockLocked(@UserIdInt int userId) {
5267         // Update the profile's timeout
5268         if (isManagedProfile(userId)) {
5269             updateProfileLockTimeoutLocked(userId);
5270         }
5271 
5272         mInjector.binderWithCleanCallingIdentity(() -> {
5273             // Update the device timeout
5274             final int parentId = getProfileParentId(userId);
5275             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(
5276                     getActiveAdminsForLockscreenPoliciesLocked(parentId));
5277 
5278             final DevicePolicyData policy = getUserDataUnchecked(parentId);
5279             if (policy.mLastMaximumTimeToLock == timeMs) {
5280                 return;
5281             }
5282             policy.mLastMaximumTimeToLock = timeMs;
5283 
5284             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
5285                 // Make sure KEEP_SCREEN_ON is disabled, since that
5286                 // would allow bypassing of the maximum time to lock.
5287                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
5288             }
5289             getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
5290                     UserHandle.USER_SYSTEM, timeMs);
5291         });
5292     }
5293 
5294     private void updateProfileLockTimeoutLocked(@UserIdInt int userId) {
5295         final long timeMs;
5296         if (isSeparateProfileChallengeEnabled(userId)) {
5297             timeMs = getMaximumTimeToLockPolicyFromAdmins(
5298                     getActiveAdminsForLockscreenPoliciesLocked(userId));
5299         } else {
5300             timeMs = Long.MAX_VALUE;
5301         }
5302 
5303         final DevicePolicyData policy = getUserDataUnchecked(userId);
5304         if (policy.mLastMaximumTimeToLock == timeMs) {
5305             return;
5306         }
5307         policy.mLastMaximumTimeToLock = timeMs;
5308 
5309         mInjector.binderWithCleanCallingIdentity(() ->
5310                 getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
5311                         userId, policy.mLastMaximumTimeToLock));
5312     }
5313 
5314     @Override
5315     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
5316         if (!mHasFeature) {
5317             return 0;
5318         }
5319         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
5320 
5321         final CallerIdentity caller = getCallerIdentity();
5322         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
5323         // System caller can query policy for a particular admin.
5324         Preconditions.checkCallAuthorization(
5325                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
5326                         || isSystemUid(caller));
5327 
5328         synchronized (getLockObject()) {
5329             if (who != null) {
5330                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5331                 return admin != null ? admin.maximumTimeToUnlock : 0;
5332             }
5333             // Return the strictest policy across all participating admins.
5334             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5335                     getProfileParentUserIfRequested(userHandle, parent));
5336             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins);
5337             return timeMs == Long.MAX_VALUE ? 0 : timeMs;
5338         }
5339     }
5340 
5341     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
5342         long time = Long.MAX_VALUE;
5343         for (final ActiveAdmin admin : admins) {
5344             if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) {
5345                 time = admin.maximumTimeToUnlock;
5346             }
5347         }
5348         return time;
5349     }
5350 
5351     @Override
5352     public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
5353             boolean parent) {
5354         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5355             return;
5356         }
5357         Objects.requireNonNull(who, "ComponentName is null");
5358         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
5359         final CallerIdentity caller = getCallerIdentity(who);
5360         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
5361         // timeoutMs with value 0 means that the admin doesn't participate
5362         // timeoutMs is clamped to the interval in case the internal constants change in the future
5363         final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
5364         if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
5365             timeoutMs = minimumStrongAuthTimeout;
5366         }
5367         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
5368             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5369         }
5370 
5371         final int userHandle = caller.getUserId();
5372         boolean changed = false;
5373         synchronized (getLockObject()) {
5374             ActiveAdmin ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller),
5375                     parent);
5376             if (ap.strongAuthUnlockTimeout != timeoutMs) {
5377                 ap.strongAuthUnlockTimeout = timeoutMs;
5378                 saveSettingsLocked(userHandle);
5379                 changed = true;
5380             }
5381         }
5382         if (changed) {
5383             mLockSettingsInternal.refreshStrongAuthTimeout(userHandle);
5384             // Refreshes the parent if profile has unified challenge, since the timeout would
5385             // also affect the parent user in this case.
5386             if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
5387                 mLockSettingsInternal.refreshStrongAuthTimeout(getProfileParentId(userHandle));
5388             }
5389         }
5390     }
5391 
5392     /**
5393      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
5394      * admins if who is null.
5395      * Returns 0 if not configured for the provided admin.
5396      */
5397     @Override
5398     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
5399         if (!mHasFeature) {
5400             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5401         }
5402         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
5403 
5404         final CallerIdentity caller = getCallerIdentity(who);
5405         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
5406 
5407         if (!mLockPatternUtils.hasSecureLockScreen()) {
5408             // No strong auth timeout on devices not supporting the
5409             // {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature
5410             return 0;
5411         }
5412         synchronized (getLockObject()) {
5413             if (who != null) {
5414                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
5415                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
5416             }
5417 
5418             // Return the strictest policy across all participating admins.
5419             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5420                     getProfileParentUserIfRequested(userId, parent));
5421 
5422             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5423             for (int i = 0; i < admins.size(); i++) {
5424                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
5425                 if (timeout != 0) { // take only participating admins into account
5426                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
5427                 }
5428             }
5429             return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
5430         }
5431     }
5432 
5433     private long getMinimumStrongAuthTimeoutMs() {
5434         if (!mInjector.isBuildDebuggable()) {
5435             return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
5436         }
5437         // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
5438         // name cannot be longer than 31 characters
5439         return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
5440                 MINIMUM_STRONG_AUTH_TIMEOUT_MS),
5441                 MINIMUM_STRONG_AUTH_TIMEOUT_MS);
5442     }
5443 
5444     @Override
5445     public void lockNow(int flags, boolean parent) {
5446         final CallerIdentity caller = getCallerIdentity();
5447 
5448         final int callingUserId = caller.getUserId();
5449         ComponentName adminComponent = null;
5450         synchronized (getLockObject()) {
5451             // Make sure the caller has any active admin with the right policy or
5452             // the required permission.
5453             final ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked(
5454                     null,
5455                     DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
5456                     parent,
5457                     android.Manifest.permission.LOCK_DEVICE);
5458             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOCK_NOW);
5459             final long ident = mInjector.binderClearCallingIdentity();
5460             try {
5461                 adminComponent = admin == null ? null : admin.info.getComponent();
5462                 if (adminComponent != null) {
5463                     // For Profile Owners only, callers with only permission not allowed.
5464                     if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
5465                         // Evict key
5466                         Preconditions.checkCallingUser(isManagedProfile(callingUserId));
5467                         Preconditions.checkArgument(!parent,
5468                                 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
5469                         if (!isProfileOwner(adminComponent, callingUserId)) {
5470                             throw new SecurityException("Only profile owner admins can set "
5471                                     + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5472                         }
5473                         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5474                             throw new UnsupportedOperationException(
5475                                     "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices");
5476                         }
5477                         mUserManager.evictCredentialEncryptionKey(callingUserId);
5478                     }
5479                 }
5480 
5481                 // Lock all users unless this is a managed profile with a separate challenge
5482                 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
5483                         ? UserHandle.USER_ALL : callingUserId);
5484                 mLockPatternUtils.requireStrongAuth(
5485                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
5486 
5487                 // Require authentication for the device or profile
5488                 if (userToLock == UserHandle.USER_ALL) {
5489                     if (mIsAutomotive) {
5490                         if (VERBOSE_LOG) {
5491                             Slogf.v(LOG_TAG, "lockNow(): not powering off display on automotive"
5492                                     + " build");
5493                         }
5494                     } else {
5495                         // Power off the display
5496                         mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
5497                                 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
5498                     }
5499                     mInjector.getIWindowManager().lockNow(null);
5500                 } else {
5501                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
5502                 }
5503 
5504                 if (SecurityLog.isLoggingEnabled() && adminComponent != null) {
5505                     final int affectedUserId =
5506                             parent ? getProfileParentId(callingUserId) : callingUserId;
5507                     SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK,
5508                             adminComponent.getPackageName(), callingUserId, affectedUserId);
5509                 }
5510             } catch (RemoteException e) {
5511             } finally {
5512                 mInjector.binderRestoreCallingIdentity(ident);
5513             }
5514         }
5515         DevicePolicyEventLogger
5516                 .createEvent(DevicePolicyEnums.LOCK_NOW)
5517                 .setAdmin(adminComponent)
5518                 .setInt(flags)
5519                 .write();
5520     }
5521 
5522     @Override
5523     public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
5524         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
5525         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
5526     }
5527 
5528     private boolean canManageCaCerts(CallerIdentity caller) {
5529         return (caller.hasAdminComponent() && (isDeviceOwner(caller) || isProfileOwner(caller)))
5530                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_INSTALL))
5531                 || hasCallingOrSelfPermission(MANAGE_CA_CERTIFICATES);
5532     }
5533 
5534     @Override
5535     public boolean approveCaCert(String alias, int userId, boolean approval) {
5536         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
5537 
5538         synchronized (getLockObject()) {
5539             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
5540             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
5541             if (!changed) {
5542                 return false;
5543             }
5544             saveSettingsLocked(userId);
5545         }
5546         mCertificateMonitor.onCertificateApprovalsChanged(userId);
5547         return true;
5548     }
5549 
5550     @Override
5551     public boolean isCaCertApproved(String alias, int userId) {
5552         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
5553 
5554         synchronized (getLockObject()) {
5555             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
5556         }
5557     }
5558 
5559     private Set<Integer> removeCaApprovalsIfNeeded(int userId) {
5560         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
5561         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
5562             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
5563             if (userInfo.isManagedProfile()){
5564                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
5565             }
5566             if (!isSecure) {
5567                 synchronized (getLockObject()) {
5568                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
5569                     affectedUserIds.add(userInfo.id);
5570                 }
5571                 mCertificateMonitor.onCertificateApprovalsChanged(userId);
5572             }
5573         }
5574         return affectedUserIds;
5575     }
5576 
5577     @Override
5578     public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) {
5579         if (!mHasFeature) {
5580             return false;
5581         }
5582         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
5583         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
5584         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_CA_CERT);
5585 
5586         final String alias = mInjector.binderWithCleanCallingIdentity(() -> {
5587             String installedAlias = mCertificateMonitor.installCaCert(
5588                     caller.getUserHandle(), certBuffer);
5589             DevicePolicyEventLogger
5590                     .createEvent(DevicePolicyEnums.INSTALL_CA_CERT)
5591                     .setAdmin(caller.getPackageName())
5592                     .setBoolean(/* isDelegate */ admin == null)
5593                     .write();
5594             return installedAlias;
5595         });
5596 
5597         if (alias == null) {
5598             Slogf.w(LOG_TAG, "Problem installing cert");
5599             return false;
5600         }
5601 
5602         synchronized (getLockObject()) {
5603             getUserData(caller.getUserId()).mOwnerInstalledCaCerts.add(alias);
5604             saveSettingsLocked(caller.getUserId());
5605         }
5606         return true;
5607     }
5608 
5609     @Override
5610     public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
5611         if (!mHasFeature) {
5612             return;
5613         }
5614         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
5615         Preconditions.checkCallAuthorization(canManageCaCerts(caller));
5616         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_UNINSTALL_CA_CERT);
5617 
5618         mInjector.binderWithCleanCallingIdentity(() -> {
5619             mCertificateMonitor.uninstallCaCerts(caller.getUserHandle(), aliases);
5620             DevicePolicyEventLogger
5621                     .createEvent(DevicePolicyEnums.UNINSTALL_CA_CERTS)
5622                     .setAdmin(caller.getPackageName())
5623                     .setBoolean(/* isDelegate */ admin == null)
5624                     .write();
5625         });
5626 
5627         synchronized (getLockObject()) {
5628             if (getUserData(caller.getUserId()).mOwnerInstalledCaCerts.removeAll(
5629                     Arrays.asList(aliases))) {
5630                 saveSettingsLocked(caller.getUserId());
5631             }
5632         }
5633     }
5634 
5635     @Override
5636     public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
5637             byte[] cert, byte[] chain, String alias, boolean requestAccess,
5638             boolean isUserSelectable) {
5639         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
5640         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
5641         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
5642         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
5643                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
5644                 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
5645         if (isCredentialManagementApp) {
5646             Preconditions.checkCallAuthorization(!isUserSelectable, "The credential "
5647                     + "management app is not allowed to install a user selectable key pair");
5648             Preconditions.checkCallAuthorization(
5649                     isAliasInCredentialManagementAppPolicy(caller, alias),
5650                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
5651         }
5652         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_KEY_PAIR);
5653 
5654         final long id = mInjector.binderClearCallingIdentity();
5655         try {
5656             final KeyChainConnection keyChainConnection =
5657                     KeyChain.bindAsUser(mContext, caller.getUserHandle());
5658             try {
5659                 IKeyChainService keyChain = keyChainConnection.getService();
5660                 if (!keyChain.installKeyPair(privKey, cert, chain, alias, KeyStore.UID_SELF)) {
5661                     logInstallKeyPairFailure(caller, isCredentialManagementApp);
5662                     return false;
5663                 }
5664                 if (requestAccess) {
5665                     keyChain.setGrant(caller.getUid(), alias, true);
5666                 }
5667                 keyChain.setUserSelectable(alias, isUserSelectable);
5668                 DevicePolicyEventLogger
5669                         .createEvent(DevicePolicyEnums.INSTALL_KEY_PAIR)
5670                         .setAdmin(caller.getPackageName())
5671                         .setBoolean(/* isDelegate */ isCallerDelegate)
5672                         .setStrings(isCredentialManagementApp
5673                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
5674                         .write();
5675                 return true;
5676             } catch (RemoteException e) {
5677                 Slogf.e(LOG_TAG, "Installing certificate", e);
5678             } finally {
5679                 keyChainConnection.close();
5680             }
5681         } catch (InterruptedException e) {
5682             Slogf.w(LOG_TAG, "Interrupted while installing certificate", e);
5683             Thread.currentThread().interrupt();
5684         } finally {
5685             mInjector.binderRestoreCallingIdentity(id);
5686         }
5687         logInstallKeyPairFailure(caller, isCredentialManagementApp);
5688         return false;
5689     }
5690 
5691     private void logInstallKeyPairFailure(CallerIdentity caller,
5692             boolean isCredentialManagementApp) {
5693         if (!isCredentialManagementApp) {
5694             return;
5695         }
5696         DevicePolicyEventLogger
5697                 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_INSTALL_KEY_PAIR_FAILED)
5698                 .setStrings(caller.getPackageName())
5699                 .write();
5700     }
5701 
5702     @Override
5703     public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
5704         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
5705         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
5706         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
5707         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
5708                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
5709                 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
5710         if (isCredentialManagementApp) {
5711             Preconditions.checkCallAuthorization(
5712                     isAliasInCredentialManagementAppPolicy(caller, alias),
5713                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
5714         }
5715         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_KEY_PAIR);
5716 
5717         final long id = Binder.clearCallingIdentity();
5718         try {
5719             final KeyChainConnection keyChainConnection =
5720                     KeyChain.bindAsUser(mContext, caller.getUserHandle());
5721             try {
5722                 IKeyChainService keyChain = keyChainConnection.getService();
5723                 DevicePolicyEventLogger
5724                         .createEvent(DevicePolicyEnums.REMOVE_KEY_PAIR)
5725                         .setAdmin(caller.getPackageName())
5726                         .setBoolean(/* isDelegate */ isCallerDelegate)
5727                         .setStrings(isCredentialManagementApp
5728                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
5729                         .write();
5730                 return keyChain.removeKeyPair(alias);
5731             } catch (RemoteException e) {
5732                 Slogf.e(LOG_TAG, "Removing keypair", e);
5733             } finally {
5734                 keyChainConnection.close();
5735             }
5736         } catch (InterruptedException e) {
5737             Slogf.w(LOG_TAG, "Interrupted while removing keypair", e);
5738             Thread.currentThread().interrupt();
5739         } finally {
5740             Binder.restoreCallingIdentity(id);
5741         }
5742         return false;
5743     }
5744 
5745     @Override
5746     public boolean hasKeyPair(String callerPackage, String alias) {
5747         final CallerIdentity caller = getCallerIdentity(callerPackage);
5748         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
5749         Preconditions.checkCallAuthorization(canInstallCertificates(caller)
5750                 || isCredentialManagementApp);
5751         if (isCredentialManagementApp) {
5752             Preconditions.checkCallAuthorization(
5753                     isAliasInCredentialManagementAppPolicy(caller, alias),
5754                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
5755         }
5756 
5757         return mInjector.binderWithCleanCallingIdentity(() -> {
5758             try (KeyChainConnection keyChainConnection =
5759                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
5760                 return keyChainConnection.getService().containsKeyPair(alias);
5761             } catch (RemoteException e) {
5762                 Slogf.e(LOG_TAG, "Querying keypair", e);
5763             } catch (InterruptedException e) {
5764                 Slogf.w(LOG_TAG, "Interrupted while querying keypair", e);
5765                 Thread.currentThread().interrupt();
5766             }
5767             return false;
5768         });
5769     }
5770 
5771     private boolean canInstallCertificates(CallerIdentity caller) {
5772         return isProfileOwner(caller) || isDeviceOwner(caller)
5773                 || isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
5774     }
5775 
5776     private boolean canChooseCertificates(CallerIdentity caller) {
5777         return isProfileOwner(caller) || isDeviceOwner(caller)
5778                 || isCallerDelegate(caller, DELEGATION_CERT_SELECTION);
5779     }
5780 
5781     @Override
5782     public boolean setKeyGrantToWifiAuth(String callerPackage, String alias, boolean hasGrant) {
5783         Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty");
5784 
5785         final CallerIdentity caller = getCallerIdentity(callerPackage);
5786         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
5787 
5788         return setKeyChainGrantInternal(alias, hasGrant, Process.WIFI_UID, caller.getUserHandle());
5789     }
5790 
5791     @Override
5792     public boolean isKeyPairGrantedToWifiAuth(String callerPackage, String alias) {
5793         Preconditions.checkStringNotEmpty(alias, "Alias to check cannot be empty");
5794 
5795         final CallerIdentity caller = getCallerIdentity(callerPackage);
5796         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
5797 
5798         return mInjector.binderWithCleanCallingIdentity(() -> {
5799             try (KeyChainConnection keyChainConnection =
5800                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
5801                 final List<String> result = new ArrayList<>();
5802                 final int[] granteeUids = keyChainConnection.getService().getGrants(alias);
5803 
5804                 for (final int uid : granteeUids) {
5805                     if (uid == Process.WIFI_UID) {
5806                         return true;
5807                     }
5808                 }
5809                 return false;
5810             } catch (RemoteException e) {
5811                 Slogf.e(LOG_TAG, "Querying grant to wifi auth.", e);
5812                 return false;
5813             }
5814         });
5815     }
5816 
5817     @Override
5818     public boolean setKeyGrantForApp(ComponentName who, String callerPackage, String alias,
5819             String packageName, boolean hasGrant) {
5820         Preconditions.checkStringNotEmpty(alias, "Alias to grant cannot be empty");
5821         Preconditions.checkStringNotEmpty(packageName, "Package to grant to cannot be empty");
5822 
5823         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
5824         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
5825                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
5826                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_CERT_SELECTION)));
5827 
5828         final int granteeUid;
5829         try {
5830             ApplicationInfo ai = mInjector.getIPackageManager().getApplicationInfo(
5831                     packageName, 0, caller.getUserId());
5832             Preconditions.checkArgument(ai != null,
5833                     "Provided package %s is not installed", packageName);
5834             granteeUid = ai.uid;
5835         } catch (RemoteException e) {
5836             throw new IllegalStateException("Failure getting grantee uid", e);
5837         }
5838 
5839         return setKeyChainGrantInternal(alias, hasGrant, granteeUid, caller.getUserHandle());
5840     }
5841 
5842     private boolean setKeyChainGrantInternal(String alias, boolean hasGrant, int granteeUid,
5843             UserHandle userHandle) {
5844         final long id = mInjector.binderClearCallingIdentity();
5845         try {
5846             try (KeyChainConnection keyChainConnection =
5847                          KeyChain.bindAsUser(mContext, userHandle)) {
5848                 IKeyChainService keyChain = keyChainConnection.getService();
5849                 return keyChain.setGrant(granteeUid, alias, hasGrant);
5850             } catch (RemoteException e) {
5851                 Slogf.e(LOG_TAG, "Setting grant for package.", e);
5852                 return false;
5853             }
5854         } catch (InterruptedException e) {
5855             Slogf.w(LOG_TAG, "Interrupted while setting key grant", e);
5856             Thread.currentThread().interrupt();
5857         } finally {
5858             mInjector.binderRestoreCallingIdentity(id);
5859         }
5860         return false;
5861     }
5862 
5863     @Override
5864     public ParcelableGranteeMap getKeyPairGrants(String callerPackage, String alias) {
5865         final CallerIdentity caller = getCallerIdentity(callerPackage);
5866         Preconditions.checkCallAuthorization(canChooseCertificates(caller));
5867 
5868         final ArrayMap<Integer, Set<String>> result = new ArrayMap<>();
5869         mInjector.binderWithCleanCallingIdentity(() -> {
5870             try (KeyChainConnection keyChainConnection =
5871                          KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
5872                 final int[] granteeUids = keyChainConnection.getService().getGrants(alias);
5873                 final PackageManager pm = mInjector.getPackageManager(caller.getUserId());
5874 
5875                 for (final int uid : granteeUids) {
5876                     final String[] packages = pm.getPackagesForUid(uid);
5877                     if (packages == null) {
5878                         Slogf.wtf(LOG_TAG, "No packages found for uid " + uid);
5879                         continue;
5880                     }
5881                     result.put(uid, new ArraySet<String>(packages));
5882                 }
5883             } catch (RemoteException e) {
5884                 Slogf.e(LOG_TAG, "Querying keypair grants", e);
5885             } catch (InterruptedException e) {
5886                 Slogf.w(LOG_TAG, "Interrupted while querying keypair grants", e);
5887                 Thread.currentThread().interrupt();
5888             }
5889         });
5890         return new ParcelableGranteeMap(result);
5891     }
5892 
5893     /**
5894      * Enforce one the following conditions are met:
5895      * (1) The device has a Device Owner, and one of the following holds:
5896      *   (1.1) The caller is the Device Owner
5897      *   (1.2) The caller is another app in the same user as the device owner, AND
5898      *         The caller is the delegated certificate installer.
5899      * (2) The user has a profile owner, AND:
5900      *   (2.1) The profile owner has been granted access to Device IDs and one of the following
5901      *         holds:
5902      *     (2.1.1) The caller is the profile owner.
5903      *     (2.1.2) The caller is from another app in the same user as the profile owner, AND
5904      *       (2.1.2.1) The caller is the delegated cert installer.
5905      *
5906      *  For the device owner case, simply check that the caller is the device owner or the
5907      *  delegated certificate installer.
5908      *
5909      *  For the profile owner case, first check that the caller is the profile owner or can
5910      *  manage the DELEGATION_CERT_INSTALL scope.
5911      *  If that check succeeds, ensure the profile owner was granted access to device
5912      *  identifiers. The grant is transitive: The delegated cert installer is implicitly allowed
5913      *  access to device identifiers in this case as part of the delegation.
5914      */
5915     @VisibleForTesting
5916     public void enforceCallerCanRequestDeviceIdAttestation(CallerIdentity caller)
5917             throws SecurityException {
5918         /**
5919          *  First check if there's a profile owner because the device could be in COMP mode (where
5920          *  there's a device owner and profile owner on the same device).
5921          *  If the caller is from the work profile, then it must be the PO or the delegate, and
5922          *  it must have the right permission to access device identifiers.
5923          */
5924         if (hasProfileOwner(caller.getUserId())) {
5925             // Make sure that the caller is the profile owner or delegate.
5926             Preconditions.checkCallAuthorization(canInstallCertificates(caller));
5927             // Verify that the managed profile is on an organization-owned device and as such
5928             // the profile owner can access Device IDs.
5929             if (isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId())) {
5930                 return;
5931             }
5932             throw new SecurityException(
5933                     "Profile Owner is not allowed to access Device IDs.");
5934         }
5935 
5936         // If not, fall back to the device owner check.
5937         Preconditions.checkCallAuthorization(
5938                 isDeviceOwner(caller) || isCallerDelegate(caller, DELEGATION_CERT_INSTALL));
5939     }
5940 
5941     @VisibleForTesting
5942     public static int[] translateIdAttestationFlags(
5943             int idAttestationFlags) {
5944         Map<Integer, Integer> idTypeToAttestationFlag = new HashMap();
5945         idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
5946         idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
5947         idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
5948         idTypeToAttestationFlag.put(
5949                 ID_TYPE_INDIVIDUAL_ATTESTATION, USE_INDIVIDUAL_ATTESTATION);
5950 
5951         int numFlagsSet = Integer.bitCount(idAttestationFlags);
5952         // No flags are set - return null to indicate no device ID attestation information should
5953         // be included in the attestation record.
5954         if (numFlagsSet == 0) {
5955             return null;
5956         }
5957 
5958         // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if
5959         // no other flag is set. That will lead to inclusion of general device make data in the
5960         // attestation record, but no specific device identifiers.
5961         if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) {
5962             numFlagsSet -= 1;
5963             idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO);
5964         }
5965 
5966         int[] attestationUtilsFlags = new int[numFlagsSet];
5967         int i = 0;
5968         for (Integer idType: idTypeToAttestationFlag.keySet()) {
5969             if ((idType & idAttestationFlags) != 0) {
5970                 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType);
5971             }
5972         }
5973 
5974         return attestationUtilsFlags;
5975     }
5976 
5977     @Override
5978     public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
5979             ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags,
5980             KeymasterCertificateChain attestationChain) {
5981         // Get attestation flags, if any.
5982         final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags);
5983         final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
5984         KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
5985         final String alias = keySpec.getKeystoreAlias();
5986 
5987         Preconditions.checkStringNotEmpty(alias, "Empty alias provided");
5988         Preconditions.checkArgument(
5989                 !deviceIdAttestationRequired || keySpec.getAttestationChallenge() != null,
5990                 "Requested Device ID attestation but challenge is empty");
5991 
5992         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
5993         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
5994         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
5995         if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) {
5996             // TODO: replace enforce methods
5997             enforceCallerCanRequestDeviceIdAttestation(caller);
5998             enforceIndividualAttestationSupportedIfRequested(attestationUtilsFlags);
5999         } else {
6000             Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6001                     && (isProfileOwner(caller) || isDeviceOwner(caller)))
6002                     || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
6003             if (isCredentialManagementApp) {
6004                 Preconditions.checkCallAuthorization(
6005                         isAliasInCredentialManagementAppPolicy(caller, alias),
6006                         CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6007             }
6008         }
6009 
6010         if (TextUtils.isEmpty(alias)) {
6011             throw new IllegalArgumentException("Empty alias provided.");
6012         }
6013         // As the caller will be granted access to the key, ensure no UID was specified, as
6014         // it will not have the desired effect.
6015         if (keySpec.getUid() != KeyStore.UID_SELF) {
6016             Slogf.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
6017             logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6018             return false;
6019         }
6020 
6021         if (deviceIdAttestationRequired) {
6022             if (keySpec.getAttestationChallenge() == null) {
6023                 throw new IllegalArgumentException(
6024                         "Requested Device ID attestation but challenge is empty.");
6025             }
6026             KeyGenParameterSpec.Builder specBuilder = new KeyGenParameterSpec.Builder(keySpec);
6027             specBuilder.setAttestationIds(attestationUtilsFlags);
6028             specBuilder.setDevicePropertiesAttestationIncluded(true);
6029             keySpec = specBuilder.build();
6030         }
6031 
6032         final long id = mInjector.binderClearCallingIdentity();
6033         try {
6034             try (KeyChainConnection keyChainConnection =
6035                     KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6036                 IKeyChainService keyChain = keyChainConnection.getService();
6037 
6038                 final int generationResult = keyChain.generateKeyPair(algorithm,
6039                         new ParcelableKeyGenParameterSpec(keySpec));
6040                 if (generationResult != KeyChain.KEY_GEN_SUCCESS) {
6041                     Slogf.e(LOG_TAG, "KeyChain failed to generate a keypair, error %d.",
6042                             generationResult);
6043                     logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6044                     switch (generationResult) {
6045                         case KeyChain.KEY_GEN_STRONGBOX_UNAVAILABLE:
6046                             throw new ServiceSpecificException(
6047                                     DevicePolicyManager.KEY_GEN_STRONGBOX_UNAVAILABLE,
6048                                     String.format("KeyChain error: %d", generationResult));
6049                         case KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS:
6050                             throw new UnsupportedOperationException(
6051                                 "Device does not support Device ID attestation.");
6052                         default:
6053                             return false;
6054                     }
6055                 }
6056 
6057                 // Set a grant for the caller here so that when the client calls
6058                 // requestPrivateKey, it will be able to get the key from Keystore.
6059                 // Note the use of the calling  UID, since the request for the private
6060                 // key will come from the client's process, so the grant has to be for
6061                 // that UID.
6062                 keyChain.setGrant(caller.getUid(), alias, true);
6063 
6064                 try {
6065                     final List<byte[]> encodedCerts = new ArrayList();
6066                     final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
6067                     final byte[] certChainBytes = keyChain.getCaCertificates(alias);
6068                     encodedCerts.add(keyChain.getCertificate(alias));
6069                     if (certChainBytes != null) {
6070                         final Collection<X509Certificate> certs =
6071                                 (Collection<X509Certificate>) certFactory.generateCertificates(
6072                                     new ByteArrayInputStream(certChainBytes));
6073                         for (X509Certificate cert : certs) {
6074                             encodedCerts.add(cert.getEncoded());
6075                         }
6076                     }
6077 
6078                     attestationChain.shallowCopyFrom(new KeymasterCertificateChain(encodedCerts));
6079                 } catch (CertificateException e) {
6080                     logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6081                     Slogf.e(LOG_TAG, "While retrieving certificate chain.", e);
6082                     return false;
6083                 }
6084 
6085                 DevicePolicyEventLogger
6086                         .createEvent(DevicePolicyEnums.GENERATE_KEY_PAIR)
6087                         .setAdmin(caller.getPackageName())
6088                         .setBoolean(/* isDelegate */ isCallerDelegate)
6089                         .setInt(idAttestationFlags)
6090                         .setStrings(algorithm, isCredentialManagementApp
6091                                 ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6092                         .write();
6093                 return true;
6094             }
6095         } catch (RemoteException e) {
6096             Slogf.e(LOG_TAG, "KeyChain error while generating a keypair", e);
6097         } catch (InterruptedException e) {
6098             Slogf.w(LOG_TAG, "Interrupted while generating keypair", e);
6099             Thread.currentThread().interrupt();
6100         } finally {
6101             mInjector.binderRestoreCallingIdentity(id);
6102         }
6103         logGenerateKeyPairFailure(caller, isCredentialManagementApp);
6104         return false;
6105     }
6106 
6107     private void logGenerateKeyPairFailure(CallerIdentity caller,
6108             boolean isCredentialManagementApp) {
6109         if (!isCredentialManagementApp) {
6110             return;
6111         }
6112         DevicePolicyEventLogger
6113                 .createEvent(DevicePolicyEnums.CREDENTIAL_MANAGEMENT_APP_GENERATE_KEY_PAIR_FAILED)
6114                 .setStrings(caller.getPackageName())
6115                 .write();
6116     }
6117 
6118     private void enforceIndividualAttestationSupportedIfRequested(int[] attestationUtilsFlags) {
6119         for (int attestationFlag : attestationUtilsFlags) {
6120             if (attestationFlag == USE_INDIVIDUAL_ATTESTATION
6121                     && !mInjector.getPackageManager().hasSystemFeature(
6122                     PackageManager.FEATURE_DEVICE_UNIQUE_ATTESTATION)) {
6123                 throw new UnsupportedOperationException("Device Individual attestation is not "
6124                         + "supported on this device.");
6125             }
6126         }
6127     }
6128 
6129     @Override
6130     public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias,
6131             byte[] cert, byte[] chain, boolean isUserSelectable) {
6132         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
6133         final boolean isCallerDelegate = isCallerDelegate(caller, DELEGATION_CERT_INSTALL);
6134         final boolean isCredentialManagementApp = isCredentialManagementApp(caller);
6135         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
6136                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
6137                 || (caller.hasPackage() && (isCallerDelegate || isCredentialManagementApp)));
6138         if (isCredentialManagementApp) {
6139             Preconditions.checkCallAuthorization(
6140                     isAliasInCredentialManagementAppPolicy(caller, alias),
6141                     CREDENTIAL_MANAGEMENT_APP_INVALID_ALIAS_MSG);
6142         }
6143 
6144         final long id = mInjector.binderClearCallingIdentity();
6145         try (final KeyChainConnection keyChainConnection =
6146                 KeyChain.bindAsUser(mContext, caller.getUserHandle())) {
6147             IKeyChainService keyChain = keyChainConnection.getService();
6148             if (!keyChain.setKeyPairCertificate(alias, cert, chain)) {
6149                 return false;
6150             }
6151             keyChain.setUserSelectable(alias, isUserSelectable);
6152             DevicePolicyEventLogger
6153                     .createEvent(DevicePolicyEnums.SET_KEY_PAIR_CERTIFICATE)
6154                     .setAdmin(caller.getPackageName())
6155                     .setBoolean(/* isDelegate */ isCallerDelegate)
6156                     .setStrings(isCredentialManagementApp
6157                             ? CREDENTIAL_MANAGEMENT_APP : NOT_CREDENTIAL_MANAGEMENT_APP)
6158                     .write();
6159             return true;
6160         } catch (InterruptedException e) {
6161             Slogf.w(LOG_TAG, "Interrupted while setting keypair certificate", e);
6162             Thread.currentThread().interrupt();
6163         } catch (RemoteException e) {
6164             Slogf.e(LOG_TAG, "Failed setting keypair certificate", e);
6165         } finally {
6166             mInjector.binderRestoreCallingIdentity(id);
6167         }
6168         return false;
6169     }
6170 
6171     @Override
6172     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
6173             final IBinder response) {
6174         final CallerIdentity caller = getCallerIdentity();
6175         Preconditions.checkCallAuthorization(isSystemUid(caller),
6176                 String.format(NOT_SYSTEM_CALLER_MSG, "choose private key alias"));
6177 
6178         // If there is a profile owner, redirect to that; otherwise query the device owner.
6179         ComponentName aliasChooser = getProfileOwnerAsUser(caller.getUserId());
6180         if (aliasChooser == null && caller.getUserHandle().isSystem()) {
6181             synchronized (getLockObject()) {
6182                 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
6183                 if (deviceOwnerAdmin != null) {
6184                     aliasChooser = deviceOwnerAdmin.info.getComponent();
6185                 }
6186             }
6187         }
6188         if (aliasChooser == null) {
6189             sendPrivateKeyAliasResponse(null, response);
6190             return;
6191         }
6192 
6193         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
6194         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
6195         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
6196         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
6197         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
6198         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
6199 
6200         final ComponentName delegateReceiver;
6201         delegateReceiver = resolveDelegateReceiver(DELEGATION_CERT_SELECTION,
6202                 DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS, caller.getUserId());
6203 
6204         final boolean isDelegate;
6205         if (delegateReceiver != null) {
6206             intent.setComponent(delegateReceiver);
6207             isDelegate = true;
6208         } else {
6209             intent.setComponent(aliasChooser);
6210             isDelegate = false;
6211         }
6212 
6213         mInjector.binderWithCleanCallingIdentity(() -> {
6214             mContext.sendOrderedBroadcastAsUser(intent, caller.getUserHandle(), null,
6215                     new BroadcastReceiver() {
6216                 @Override
6217                 public void onReceive(Context context, Intent intent) {
6218                     final String chosenAlias = getResultData();
6219                     sendPrivateKeyAliasResponse(chosenAlias, response);
6220                 }
6221             }, null, Activity.RESULT_OK, null, null);
6222             DevicePolicyEventLogger
6223                     .createEvent(DevicePolicyEnums.CHOOSE_PRIVATE_KEY_ALIAS)
6224                     .setAdmin(intent.getComponent())
6225                     .setBoolean(isDelegate)
6226                     .write();
6227         });
6228     }
6229 
6230     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
6231         final IKeyChainAliasCallback keyChainAliasResponse =
6232                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
6233         // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
6234         // is oneway, which means it won't block if the recipient lives in another process.
6235         try {
6236             keyChainAliasResponse.alias(alias);
6237         } catch (Exception e) {
6238             // Caller could throw RuntimeException or RemoteException back across processes. Catch
6239             // everything just to be sure.
6240             Slogf.e(LOG_TAG, "error while responding to callback", e);
6241         }
6242     }
6243 
6244     /**
6245      * Determine whether DPMS should check if a delegate package is already installed before
6246      * granting it new delegations via {@link #setDelegatedScopes}.
6247      */
6248     private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
6249             int targetSdk, List<String> scopes) {
6250         // 1) Never skip is installed check from N.
6251         if (targetSdk >= Build.VERSION_CODES.N) {
6252             return true;
6253         }
6254         // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
6255         if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
6256             return false;
6257         }
6258         // 3) Skip if all previously granted scopes are being cleared.
6259         if (scopes.isEmpty()) {
6260             return false;
6261         }
6262         // Otherwise it should check that delegatePackage is installed.
6263         return true;
6264     }
6265 
6266     /**
6267      * Set the scopes of a device owner or profile owner delegate.
6268      *
6269      * @param who the device owner or profile owner.
6270      * @param delegatePackage the name of the delegate package.
6271      * @param scopeList the list of delegation scopes to be given to the delegate package.
6272      */
6273     @Override
6274     public void setDelegatedScopes(ComponentName who, String delegatePackage,
6275             List<String> scopeList) throws SecurityException {
6276         Objects.requireNonNull(who, "ComponentName is null");
6277         Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
6278         Preconditions.checkCollectionElementsNotNull(scopeList, "Scopes");
6279         final CallerIdentity caller = getCallerIdentity(who);
6280 
6281         // Remove possible duplicates.
6282         final ArrayList<String> scopes = new ArrayList(new ArraySet(scopeList));
6283         // Ensure given scopes are valid.
6284         if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
6285             throw new IllegalArgumentException("Unexpected delegation scopes");
6286         }
6287         // Retrieve the user ID of the calling process.
6288         final int userId = caller.getUserId();
6289         // Ensure calling process is device/profile owner.
6290         if (!Collections.disjoint(scopes, DEVICE_OWNER_OR_MANAGED_PROFILE_OWNER_DELEGATIONS)) {
6291             Preconditions.checkCallAuthorization(isDeviceOwner(caller)
6292                     || (isProfileOwner(caller) && isManagedProfile(caller.getUserId())));
6293         } else if (!Collections.disjoint(
6294                 scopes, DEVICE_OWNER_OR_ORGANIZATION_OWNED_MANAGED_PROFILE_OWNER_DELEGATIONS)) {
6295             Preconditions.checkCallAuthorization(isDeviceOwner(caller)
6296                     || isProfileOwnerOfOrganizationOwnedDevice(caller));
6297         } else {
6298             Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
6299         }
6300 
6301         synchronized (getLockObject()) {
6302             // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
6303             if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
6304                         getTargetSdk(who.getPackageName(), userId), scopes)) {
6305                 // Throw when the delegate package is not installed.
6306                 if (!isPackageInstalledForUser(delegatePackage, userId)) {
6307                     throw new IllegalArgumentException("Package " + delegatePackage
6308                             + " is not installed on the current user");
6309                 }
6310             }
6311 
6312             // Set the new delegate in user policies.
6313             final DevicePolicyData policy = getUserData(userId);
6314             List<String> exclusiveScopes = null;
6315             if (!scopes.isEmpty()) {
6316                 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
6317                 exclusiveScopes = new ArrayList<>(scopes);
6318                 exclusiveScopes.retainAll(EXCLUSIVE_DELEGATIONS);
6319             } else {
6320                 // Remove any delegation info if the given scopes list is empty.
6321                 policy.mDelegationMap.remove(delegatePackage);
6322             }
6323             sendDelegationChangedBroadcast(delegatePackage, scopes, userId);
6324 
6325             // If set, remove exclusive scopes from all other delegates
6326             if (exclusiveScopes != null && !exclusiveScopes.isEmpty()) {
6327                 for (int i = policy.mDelegationMap.size() - 1; i >= 0; --i) {
6328                     final String currentPackage = policy.mDelegationMap.keyAt(i);
6329                     final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
6330 
6331                     if (!currentPackage.equals(delegatePackage)) {
6332                         // Iterate through all other delegates
6333                         if (currentScopes.removeAll(exclusiveScopes)) {
6334                             // And if this delegate had some exclusive scopes which are now moved
6335                             // to the new delegate, notify about its delegation changes.
6336                             if (currentScopes.isEmpty()) {
6337                                 policy.mDelegationMap.removeAt(i);
6338                             }
6339                             sendDelegationChangedBroadcast(currentPackage,
6340                                     new ArrayList<>(currentScopes), userId);
6341                         }
6342                     }
6343                 }
6344             }
6345             // Persist updates.
6346             saveSettingsLocked(userId);
6347         }
6348     }
6349 
6350     private void sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes,
6351             int userId) {
6352         // Notify delegate package of updates.
6353         final Intent intent = new Intent(
6354                 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
6355         // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
6356         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
6357         // Limit components this intent resolves to to the delegate package.
6358         intent.setPackage(delegatePackage);
6359         // Include the list of delegated scopes as an extra.
6360         intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes);
6361         // Send the broadcast.
6362         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
6363     }
6364 
6365     /**
6366      * Get the delegation scopes given to a delegate package by a device owner or profile owner.
6367      *
6368      * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
6369      * passing in {@code null} as the {@code who} parameter and its own name as the
6370      * {@code delegatepackage}.
6371      *
6372      * @param who the device owner or profile owner, or {@code null} if the caller is
6373      *            {@code delegatePackage}.
6374      * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
6375      * @return a list of the delegation scopes currently given to {@code delegatePackage}.
6376      */
6377     @Override
6378     @NonNull
6379     public List<String> getDelegatedScopes(ComponentName who,
6380             String delegatePackage) throws SecurityException {
6381         Objects.requireNonNull(delegatePackage, "Delegate package is null");
6382         final CallerIdentity caller = getCallerIdentity(who);
6383 
6384         // Ensure the caller may call this method:
6385         // * Either it's a profile owner / device owner, if componentName is provided
6386         // * Or it's an app querying its own delegation scopes
6387         if (caller.hasAdminComponent()) {
6388             Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
6389         } else {
6390             Preconditions.checkCallAuthorization(isPackage(caller, delegatePackage),
6391                     String.format("Caller with uid %d is not %s", caller.getUid(),
6392                             delegatePackage));
6393         }
6394         synchronized (getLockObject()) {
6395             final DevicePolicyData policy = getUserData(caller.getUserId());
6396             // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
6397             final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
6398             return scopes == null ? Collections.EMPTY_LIST : scopes;
6399         }
6400     }
6401 
6402     /**
6403      * Get a list of  packages that were given a specific delegation scopes by a device owner or
6404      * profile owner.
6405      *
6406      * @param who the device owner or profile owner.
6407      * @param scope the scope whose delegates are to be retrieved.
6408      * @return a list of the delegate packages currently given the {@code scope} delegation.
6409      */
6410     @NonNull
6411     public List<String> getDelegatePackages(ComponentName who, String scope)
6412             throws SecurityException {
6413         Objects.requireNonNull(who, "ComponentName is null");
6414         Objects.requireNonNull(scope, "Scope is null");
6415         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
6416             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
6417         }
6418 
6419         // Retrieve the user ID of the calling process.
6420         final CallerIdentity caller = getCallerIdentity(who);
6421         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
6422         synchronized (getLockObject()) {
6423             return getDelegatePackagesInternalLocked(scope, caller.getUserId());
6424         }
6425     }
6426 
6427     private List<String> getDelegatePackagesInternalLocked(String scope, int userId) {
6428         final DevicePolicyData policy = getUserData(userId);
6429 
6430         // Create a list to hold the resulting delegate packages.
6431         final List<String> delegatePackagesWithScope = new ArrayList<>();
6432         // Add all delegations containing scope to the result list.
6433         for (int i = 0; i < policy.mDelegationMap.size(); i++) {
6434             if (policy.mDelegationMap.valueAt(i).contains(scope)) {
6435                 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
6436             }
6437         }
6438         return delegatePackagesWithScope;
6439     }
6440 
6441     /**
6442      * Return the ComponentName of the receiver that handles the given broadcast action, from
6443      * the app that holds the given delegation capability. If the app defines multiple receivers
6444      * with the same intent action filter, will return any one of them nondeterministically.
6445      *
6446      * @return ComponentName of the receiver or {@null} if none exists.
6447      */
6448     private ComponentName resolveDelegateReceiver(String scope, String action, int userId) {
6449 
6450         final List<String> delegates;
6451         synchronized (getLockObject()) {
6452             delegates = getDelegatePackagesInternalLocked(scope, userId);
6453         }
6454         if (delegates.size() == 0) {
6455             return null;
6456         } else if (delegates.size() > 1) {
6457             Slogf.wtf(LOG_TAG, "More than one delegate holds " + scope);
6458             return null;
6459         }
6460         final String pkg = delegates.get(0);
6461         Intent intent = new Intent(action);
6462         intent.setPackage(pkg);
6463         final List<ResolveInfo> receivers;
6464         try {
6465             receivers = mIPackageManager.queryIntentReceivers(
6466                     intent, null, 0, userId).getList();
6467         } catch (RemoteException e) {
6468             return null;
6469         }
6470         final int count = receivers.size();
6471         if (count >= 1) {
6472             if (count > 1) {
6473                 Slogf.w(LOG_TAG, pkg + " defines more than one delegate receiver for " + action);
6474             }
6475             return receivers.get(0).activityInfo.getComponentName();
6476         } else {
6477             return null;
6478         }
6479     }
6480 
6481     /**
6482      * Check whether a caller application has been delegated a given scope via
6483      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
6484      * device owner.
6485      * <p>
6486      * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
6487      * then comparing the calling UID with the UID of {@code callerPackage} as reported by
6488      * {@link PackageManager#getPackageUidAsUser}.
6489      *
6490      * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
6491      * @param scope the delegation scope to be checked.
6492      * @return {@code true} if the calling process is a delegate of {@code scope}.
6493      */
6494     private boolean isCallerDelegate(String callerPackage, int callerUid, String scope) {
6495         Objects.requireNonNull(callerPackage, "callerPackage is null");
6496         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
6497             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
6498         }
6499 
6500         // Retrieve the UID and user ID of the calling process.
6501         final int userId = UserHandle.getUserId(callerUid);
6502         synchronized (getLockObject()) {
6503             // Retrieve user policy data.
6504             final DevicePolicyData policy = getUserData(userId);
6505             // Retrieve the list of delegation scopes granted to callerPackage.
6506             final List<String> scopes = policy.mDelegationMap.get(callerPackage);
6507             // Check callingUid only if callerPackage has the required scope delegation.
6508             if (scopes != null && scopes.contains(scope)) {
6509                 // Return true if the caller is actually callerPackage.
6510                 return isCallingFromPackage(callerPackage, callerUid);
6511             }
6512             return false;
6513         }
6514     }
6515 
6516     /**
6517      * Check whether a caller application has been delegated a given scope via
6518      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
6519      * device owner.
6520      * <p>
6521      * This is done by checking that the calling package was granted {@code scope} delegation and
6522      * then comparing the calling UID with the UID of the calling package as reported by
6523      * {@link PackageManager#getPackageUidAsUser}.
6524      *
6525      * @param caller the calling identity
6526      * @param scope the delegation scope to be checked.
6527      * @return {@code true} if the calling process is a delegate of {@code scope}.
6528      */
6529     private boolean isCallerDelegate(CallerIdentity caller, String scope) {
6530         Objects.requireNonNull(caller.getPackageName(), "callerPackage is null");
6531         Preconditions.checkArgument(Arrays.asList(DELEGATIONS).contains(scope),
6532                 "Unexpected delegation scope: %s", scope);
6533 
6534         synchronized (getLockObject()) {
6535             // Retrieve user policy data.
6536             final DevicePolicyData policy = getUserData(caller.getUserId());
6537             // Retrieve the list of delegation scopes granted to callerPackage.
6538             final List<String> scopes = policy.mDelegationMap.get(caller.getPackageName());
6539             // Check callingUid only if callerPackage has the required scope delegation.
6540             return scopes != null && scopes.contains(scope);
6541         }
6542     }
6543 
6544     /**
6545      * Helper function to preserve delegation behavior pre-O when using the deprecated functions
6546      * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
6547      */
6548     private void setDelegatedScopePreO(ComponentName who,
6549             String delegatePackage, String scope) {
6550         Objects.requireNonNull(who, "ComponentName is null");
6551 
6552         final CallerIdentity caller = getCallerIdentity(who);
6553         // Ensure calling process is device/profile owner.
6554         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
6555 
6556         synchronized (getLockObject()) {
6557             final DevicePolicyData policy = getUserData(caller.getUserId());
6558 
6559             if (delegatePackage != null) {
6560                 // Set package as a delegate for scope if it is not already one.
6561                 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
6562                 if (scopes == null) {
6563                     scopes = new ArrayList<>();
6564                 }
6565                 if (!scopes.contains(scope)) {
6566                     scopes.add(scope);
6567                     setDelegatedScopes(who, delegatePackage, scopes);
6568                 }
6569             }
6570 
6571             // Clear any existing scope delegates.
6572             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
6573                 final String currentPackage = policy.mDelegationMap.keyAt(i);
6574                 final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
6575 
6576                 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
6577                     final List<String> newScopes = new ArrayList(currentScopes);
6578                     newScopes.remove(scope);
6579                     setDelegatedScopes(who, currentPackage, newScopes);
6580                 }
6581             }
6582         }
6583     }
6584 
6585     /**
6586      * Check whether a caller application is the credential management app, which can access
6587      * privileged APIs.
6588      * <p>
6589      * This is done by checking that the calling package is authorized to perform the app operation
6590      * {@link android.app.AppOpsManager#OP_MANAGE_CREDENTIALS}.
6591      *
6592      * @param caller the calling identity
6593      * @return {@code true} if the calling process is the credential management app.
6594      */
6595     private boolean isCredentialManagementApp(CallerIdentity caller) {
6596         return mInjector.binderWithCleanCallingIdentity(() -> {
6597             AppOpsManager appOpsManager = mInjector.getAppOpsManager();
6598             if (appOpsManager == null) return false;
6599             return appOpsManager.noteOpNoThrow(AppOpsManager.OP_MANAGE_CREDENTIALS, caller.getUid(),
6600                     caller.getPackageName(), null, null) == AppOpsManager.MODE_ALLOWED;
6601         });
6602     }
6603 
6604     /**
6605      * If the caller is the credential management app, the alias provided must be contained
6606      * in the aliases specified in the credential management app's authentication policy.
6607      */
6608     private boolean isAliasInCredentialManagementAppPolicy(CallerIdentity caller, String alias) {
6609         return mInjector.binderWithCleanCallingIdentity(() -> {
6610             try (KeyChainConnection connection = KeyChain.bindAsUser(mContext,
6611                     caller.getUserHandle())) {
6612                 // The policy will be null if there is no credential management app
6613                 AppUriAuthenticationPolicy policy =
6614                         connection.getService().getCredentialManagementAppPolicy();
6615                 return policy != null && !policy.getAppAndUriMappings().isEmpty()
6616                         && containsAlias(policy, alias);
6617             } catch (RemoteException | InterruptedException e) {
6618                 return false;
6619             }
6620         });
6621     }
6622 
6623     private static boolean containsAlias(AppUriAuthenticationPolicy policy, String alias) {
6624         for (Map.Entry<String, Map<Uri, String>> appsToUris :
6625                 policy.getAppAndUriMappings().entrySet()) {
6626             for (Map.Entry<Uri, String> urisToAliases : appsToUris.getValue().entrySet()) {
6627                 if (urisToAliases.getValue().equals(alias)) {
6628                     return true;
6629                 }
6630             }
6631         }
6632         return false;
6633     }
6634 
6635     @Override
6636     public void setCertInstallerPackage(ComponentName who, String installerPackage)
6637             throws SecurityException {
6638         setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
6639         DevicePolicyEventLogger
6640                 .createEvent(DevicePolicyEnums.SET_CERT_INSTALLER_PACKAGE)
6641                 .setAdmin(who)
6642                 .setStrings(installerPackage)
6643                 .write();
6644     }
6645 
6646     @Override
6647     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
6648         final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
6649         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
6650     }
6651 
6652     /**
6653      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
6654      * not installed and therefore not available.
6655      *
6656      * @throws SecurityException if the caller is not a profile or device owner.
6657      * @throws UnsupportedOperationException if the package does not support being set as always-on.
6658      */
6659     @Override
6660     public boolean setAlwaysOnVpnPackage(ComponentName who, String vpnPackage, boolean lockdown,
6661             List<String> lockdownAllowlist)
6662             throws SecurityException {
6663         Objects.requireNonNull(who, "ComponentName is null");
6664 
6665         final CallerIdentity caller = getCallerIdentity(who);
6666         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
6667         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_ALWAYS_ON_VPN_PACKAGE);
6668 
6669         if (vpnPackage == null) {
6670             final String prevVpnPackage;
6671             synchronized (getLockObject()) {
6672                 prevVpnPackage = getProfileOwnerOrDeviceOwnerLocked(caller).mAlwaysOnVpnPackage;
6673                 // If the admin is clearing VPN package but hasn't configure any VPN previously,
6674                 // ignore it so that it doesn't interfere with user-configured VPNs.
6675                 if (TextUtils.isEmpty(prevVpnPackage)) {
6676                     return true;
6677                 }
6678             }
6679             revokeVpnAuthorizationForPackage(prevVpnPackage, caller.getUserId());
6680         }
6681 
6682         final int userId = caller.getUserId();
6683         mInjector.binderWithCleanCallingIdentity(() -> {
6684             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
6685                 Slogf.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage);
6686                 throw new ServiceSpecificException(
6687                         DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage);
6688             }
6689 
6690             if (vpnPackage != null && lockdown && lockdownAllowlist != null) {
6691                 for (String packageName : lockdownAllowlist) {
6692                     if (!isPackageInstalledForUser(packageName, userId)) {
6693                         Slogf.w(LOG_TAG, "Non-existent package in VPN allowlist: " + packageName);
6694                         throw new ServiceSpecificException(
6695                                 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName);
6696                     }
6697                 }
6698             }
6699             // If some package is uninstalled after the check above, it will be ignored by CM.
6700             if (!mInjector.getVpnManager().setAlwaysOnVpnPackageForUser(
6701                     userId, vpnPackage, lockdown, lockdownAllowlist)) {
6702                 throw new UnsupportedOperationException();
6703             }
6704         });
6705         DevicePolicyEventLogger
6706                 .createEvent(DevicePolicyEnums.SET_ALWAYS_ON_VPN_PACKAGE)
6707                 .setAdmin(caller.getComponentName())
6708                 .setStrings(vpnPackage)
6709                 .setBoolean(lockdown)
6710                 .setInt(lockdownAllowlist != null ? lockdownAllowlist.size() : 0)
6711                 .write();
6712         synchronized (getLockObject()) {
6713             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
6714             if (!TextUtils.equals(vpnPackage, admin.mAlwaysOnVpnPackage)
6715                     || lockdown != admin.mAlwaysOnVpnLockdown) {
6716                 admin.mAlwaysOnVpnPackage = vpnPackage;
6717                 admin.mAlwaysOnVpnLockdown = lockdown;
6718                 saveSettingsLocked(userId);
6719             }
6720         }
6721         return true;
6722     }
6723 
6724     private void revokeVpnAuthorizationForPackage(String vpnPackage, int userId) {
6725         mInjector.binderWithCleanCallingIdentity(() -> {
6726             try {
6727                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6728                         vpnPackage, /* flags= */ 0, userId);
6729                 if (ai == null) {
6730                     Slogf.w(LOG_TAG, "Non-existent VPN package: " + vpnPackage);
6731                 } else {
6732                     mInjector.getAppOpsManager().setMode(AppOpsManager.OP_ACTIVATE_VPN,
6733                             ai.uid, vpnPackage, MODE_DEFAULT);
6734                 }
6735             } catch (RemoteException e) {
6736                 Slogf.e(LOG_TAG, "Can't talk to package managed", e);
6737             }
6738         });
6739     }
6740 
6741     @Override
6742     public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException {
6743         Objects.requireNonNull(admin, "ComponentName is null");
6744 
6745         final CallerIdentity caller = getCallerIdentity(admin);
6746         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
6747 
6748         return mInjector.binderWithCleanCallingIdentity(
6749                 () -> mInjector.getVpnManager().getAlwaysOnVpnPackageForUser(caller.getUserId()));
6750     }
6751 
6752     @Override
6753     public String getAlwaysOnVpnPackageForUser(int userHandle) {
6754         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
6755                 String.format(NOT_SYSTEM_CALLER_MSG, "call getAlwaysOnVpnPackageForUser"));
6756         synchronized (getLockObject()) {
6757             ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle);
6758             return admin != null ? admin.mAlwaysOnVpnPackage : null;
6759         }
6760     }
6761 
6762     @Override
6763     public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException {
6764         final CallerIdentity caller;
6765         if (hasCallingPermission(PERMISSION_MAINLINE_NETWORK_STACK)) {
6766             // TODO: CaptivePortalLoginActivity erroneously calls this method with a non-admin
6767             // ComponentName, so we have to use a separate code path for it:
6768             // getCallerIdentity(admin) will throw if the admin is not in the known admin list.
6769             caller = getCallerIdentity();
6770         } else {
6771             caller = getCallerIdentity(admin);
6772             Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
6773         }
6774 
6775         return mInjector.binderWithCleanCallingIdentity(
6776                 () -> mInjector.getVpnManager().isVpnLockdownEnabled(caller.getUserId()));
6777     }
6778 
6779     @Override
6780     public boolean isAlwaysOnVpnLockdownEnabledForUser(int userHandle) {
6781         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
6782                 String.format(NOT_SYSTEM_CALLER_MSG, "call isAlwaysOnVpnLockdownEnabledForUser"));
6783         synchronized (getLockObject()) {
6784             ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userHandle);
6785             return admin != null ? admin.mAlwaysOnVpnLockdown : null;
6786         }
6787     }
6788 
6789     @Override
6790     public List<String> getAlwaysOnVpnLockdownAllowlist(ComponentName admin)
6791             throws SecurityException {
6792         Objects.requireNonNull(admin, "ComponentName is null");
6793 
6794         final CallerIdentity caller = getCallerIdentity(admin);
6795         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
6796 
6797         return mInjector.binderWithCleanCallingIdentity(
6798                 () -> mInjector.getVpnManager().getVpnLockdownAllowlist(caller.getUserId()));
6799     }
6800 
6801     private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc,
6802             boolean wipeResetProtectionData) {
6803         wtfIfInLock();
6804         boolean success = false;
6805 
6806         try {
6807             boolean delayed = !mInjector.recoverySystemRebootWipeUserData(
6808                     /* shutdown= */ false, reason, /* force= */ true, /* wipeEuicc= */ wipeEuicc,
6809                     wipeExtRequested, wipeResetProtectionData);
6810             if (delayed) {
6811                 // Persist the request so the device is automatically factory-reset on next start if
6812                 // the system crashes or reboots before the {@code DevicePolicySafetyChecker} calls
6813                 // its callback.
6814                 Slogf.i(LOG_TAG, "Persisting factory reset request as it could be delayed by %s",
6815                         mSafetyChecker);
6816                 synchronized (getLockObject()) {
6817                     DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6818                     policy.setDelayedFactoryReset(reason, wipeExtRequested, wipeEuicc,
6819                             wipeResetProtectionData);
6820                     saveSettingsLocked(UserHandle.USER_SYSTEM);
6821                 }
6822             }
6823             success = true;
6824         } catch (IOException | SecurityException e) {
6825             Slogf.w(LOG_TAG, "Failed requesting data wipe", e);
6826         } finally {
6827             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
6828         }
6829     }
6830 
6831     private void factoryResetIfDelayedEarlier() {
6832         synchronized (getLockObject()) {
6833             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6834 
6835             if (policy.mFactoryResetFlags == 0) return;
6836 
6837             if (policy.mFactoryResetReason == null) {
6838                 // Shouldn't happen.
6839                 Slogf.e(LOG_TAG, "no persisted reason for factory resetting");
6840                 policy.mFactoryResetReason = "requested before boot";
6841             }
6842             FactoryResetter factoryResetter = FactoryResetter.newBuilder(mContext)
6843                     .setReason(policy.mFactoryResetReason).setForce(true)
6844                     .setWipeEuicc((policy.mFactoryResetFlags & DevicePolicyData
6845                             .FACTORY_RESET_FLAG_WIPE_EUICC) != 0)
6846                     .setWipeAdoptableStorage((policy.mFactoryResetFlags & DevicePolicyData
6847                             .FACTORY_RESET_FLAG_WIPE_EXTERNAL_STORAGE) != 0)
6848                     .setWipeFactoryResetProtection((policy.mFactoryResetFlags & DevicePolicyData
6849                             .FACTORY_RESET_FLAG_WIPE_FACTORY_RESET_PROTECTION) != 0)
6850                     .build();
6851             Slogf.i(LOG_TAG, "Factory resetting on boot using " + factoryResetter);
6852             try {
6853                 if (!factoryResetter.factoryReset()) {
6854                     // Shouldn't happen because FactoryResetter was created without a
6855                     // DevicePolicySafetyChecker.
6856                     Slogf.wtf(LOG_TAG, "Factory reset using " + factoryResetter + " failed.");
6857                 }
6858             } catch (IOException e) {
6859                 // Shouldn't happen.
6860                 Slogf.wtf(LOG_TAG, "Could not factory reset using " + factoryResetter, e);
6861             }
6862         }
6863     }
6864 
6865     private void forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently) {
6866         boolean success = false;
6867         try {
6868             if (getCurrentForegroundUserId() == userId) {
6869                 mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM);
6870             }
6871 
6872             success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
6873             if (!success) {
6874                 Slogf.w(LOG_TAG, "Couldn't remove user " + userId);
6875             } else if (isManagedProfile(userId) && !wipeSilently) {
6876                 sendWipeProfileNotification(wipeReasonForUser);
6877             }
6878         } catch (RemoteException re) {
6879             // Shouldn't happen
6880         } finally {
6881             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
6882         }
6883     }
6884 
6885     @Override
6886     public void wipeDataWithReason(int flags, String wipeReasonForUser,
6887             boolean calledOnParentInstance) {
6888         if (!mHasFeature && !hasCallingOrSelfPermission(permission.MASTER_CLEAR)) {
6889             return;
6890         }
6891         final CallerIdentity caller = getCallerIdentity();
6892         boolean calledByProfileOwnerOnOrgOwnedDevice =
6893                 isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId());
6894         if (calledOnParentInstance) {
6895             Preconditions.checkCallAuthorization(calledByProfileOwnerOnOrgOwnedDevice,
6896                     "Wiping the entire device can only be done by a profile owner on "
6897                             + "organization-owned device.");
6898         }
6899         if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
6900             Preconditions.checkCallAuthorization(isDeviceOwner(caller)
6901                             || calledByProfileOwnerOnOrgOwnedDevice,
6902                     "Only device owners or profile owners of organization-owned device can set "
6903                             + "WIPE_RESET_PROTECTION_DATA");
6904         }
6905 
6906         final ActiveAdmin admin;
6907         synchronized (getLockObject()) {
6908             admin = getActiveAdminWithPolicyForUidLocked(/* who= */ null,
6909                     DeviceAdminInfo.USES_POLICY_WIPE_DATA, caller.getUid());
6910         }
6911 
6912         Preconditions.checkCallAuthorization(
6913                 (admin != null) || hasCallingOrSelfPermission(permission.MASTER_CLEAR),
6914                 "No active admin for user %d and caller %d does not hold MASTER_CLEAR permission",
6915                 caller.getUserId(), caller.getUid());
6916         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_WIPE_DATA);
6917 
6918         if (TextUtils.isEmpty(wipeReasonForUser)) {
6919             if (calledByProfileOwnerOnOrgOwnedDevice && !calledOnParentInstance) {
6920                 wipeReasonForUser = mContext.getString(R.string.device_ownership_relinquished);
6921             } else {
6922                 wipeReasonForUser = mContext.getString(
6923                         R.string.work_profile_deleted_description_dpm_wipe);
6924             }
6925         }
6926 
6927         int userId = admin != null ? admin.getUserHandle().getIdentifier()
6928                 : caller.getUserId();
6929         Slogf.i(LOG_TAG, "wipeDataWithReason(%s): admin=%s, user=%d", wipeReasonForUser, admin,
6930                 userId);
6931         if (calledByProfileOwnerOnOrgOwnedDevice) {
6932             // When wipeData is called on the parent instance, it implies wiping the entire device.
6933             if (calledOnParentInstance) {
6934                 userId = UserHandle.USER_SYSTEM;
6935             } else {
6936                 // when wipeData is _not_ called on the parent instance, it implies relinquishing
6937                 // control over the device, wiping only the work profile. So the user restriction
6938                 // on profile removal needs to be removed first.
6939                 final UserHandle parentUser = UserHandle.of(getProfileParentId(userId));
6940                 mInjector.binderWithCleanCallingIdentity(
6941                         () -> clearOrgOwnedProfileOwnerUserRestrictions(parentUser));
6942             }
6943         }
6944         DevicePolicyEventLogger event = DevicePolicyEventLogger
6945                 .createEvent(DevicePolicyEnums.WIPE_DATA_WITH_REASON)
6946                 .setInt(flags)
6947                 .setStrings(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT);
6948 
6949         final String adminName;
6950         final ComponentName adminComp;
6951         if (admin != null) {
6952             adminComp = admin.info.getComponent();
6953             adminName = adminComp.flattenToShortString();
6954             event.setAdmin(adminComp);
6955         } else {
6956             adminComp = null;
6957             adminName = mInjector.getPackageManager().getPackagesForUid(caller.getUid())[0];
6958             Slogf.i(LOG_TAG, "Logging wipeData() event admin as " + adminName);
6959             event.setAdmin(adminName);
6960             if (mInjector.userManagerIsHeadlessSystemUserMode()) {
6961                 // On headless system user mode, the call is meant to factory reset the whole
6962                 // device, otherwise the caller could simply remove the current user.
6963                 userId = UserHandle.USER_SYSTEM;
6964             }
6965         }
6966         event.write();
6967 
6968         String internalReason = String.format(
6969                 "DevicePolicyManager.wipeDataWithReason() from %s, organization-owned? %s",
6970                 adminName, calledByProfileOwnerOnOrgOwnedDevice);
6971 
6972         wipeDataNoLock(adminComp, flags, internalReason, wipeReasonForUser, userId);
6973     }
6974 
6975     /**
6976      * Clears device wide policies enforced by COPE PO when relinquishing the device. This method
6977      * should be invoked once the admin is gone, so that all methods that rely on calculating
6978      * aggregate policy (e.g. strong auth timeout) from all admins aren't affected by its policies.
6979      * This method assumes that there is no other device or profile owners left on the device.
6980      * Shouldn't be called from binder thread without clearing identity.
6981      */
6982     private void clearOrgOwnedProfileOwnerDeviceWidePolicies(@UserIdInt int parentId) {
6983         Slogf.i(LOG_TAG, "Cleaning up device-wide policies left over from org-owned profile...");
6984         // Lockscreen message
6985         mLockPatternUtils.setDeviceOwnerInfo(null);
6986         // Wifi config lockdown
6987         mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
6988         // Security logging
6989         if (mInjector.securityLogGetLoggingEnabledProperty()) {
6990             mSecurityLogMonitor.stop();
6991             mInjector.securityLogSetLoggingEnabledProperty(false);
6992         }
6993         // Network logging
6994         setNetworkLoggingActiveInternal(false);
6995 
6996         // System update policy.
6997         final boolean hasSystemUpdatePolicy;
6998         synchronized (getLockObject()) {
6999             hasSystemUpdatePolicy = mOwners.getSystemUpdatePolicy() != null;
7000             if (hasSystemUpdatePolicy) {
7001                 mOwners.clearSystemUpdatePolicy();
7002                 mOwners.writeDeviceOwner();
7003             }
7004         }
7005         if (hasSystemUpdatePolicy) {
7006             mContext.sendBroadcastAsUser(
7007                     new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM);
7008         }
7009 
7010         // Unsuspend personal apps if needed.
7011         suspendPersonalAppsInternal(parentId, false);
7012 
7013         // Notify FRP agent, LSS and WindowManager to ensure they don't hold on to stale policies.
7014         final int frpAgentUid = getFrpManagementAgentUid();
7015         if (frpAgentUid > 0) {
7016             notifyResetProtectionPolicyChanged(frpAgentUid);
7017         }
7018         mLockSettingsInternal.refreshStrongAuthTimeout(parentId);
7019         updateScreenCaptureDisabled(parentId, getScreenCaptureDisabled(null, parentId, false));
7020 
7021         Slogf.i(LOG_TAG, "Cleaning up device-wide policies done.");
7022     }
7023 
7024     private void wipeDataNoLock(ComponentName admin, int flags, String internalReason,
7025                                 String wipeReasonForUser, int userId) {
7026         wtfIfInLock();
7027 
7028         mInjector.binderWithCleanCallingIdentity(() -> {
7029             // First check whether the admin is allowed to wipe the device/user/profile.
7030             final String restriction;
7031             if (userId == UserHandle.USER_SYSTEM) {
7032                 restriction = UserManager.DISALLOW_FACTORY_RESET;
7033             } else if (isManagedProfile(userId)) {
7034                 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
7035             } else {
7036                 restriction = UserManager.DISALLOW_REMOVE_USER;
7037             }
7038             if (isAdminAffectedByRestriction(admin, restriction, userId)) {
7039                 throw new SecurityException("Cannot wipe data. " + restriction
7040                         + " restriction is set for user " + userId);
7041             }
7042 
7043             if (userId == UserHandle.USER_SYSTEM) {
7044                 forceWipeDeviceNoLock(
7045                         (flags & WIPE_EXTERNAL_STORAGE) != 0,
7046                         internalReason,
7047                         (flags & WIPE_EUICC) != 0,
7048                         (flags & WIPE_RESET_PROTECTION_DATA) != 0);
7049             } else {
7050                 forceWipeUser(userId, wipeReasonForUser, (flags & WIPE_SILENTLY) != 0);
7051             }
7052         });
7053     }
7054 
7055     private void sendWipeProfileNotification(String wipeReasonForUser) {
7056         Notification notification =
7057                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
7058                         .setSmallIcon(android.R.drawable.stat_sys_warning)
7059                         .setContentTitle(mContext.getString(R.string.work_profile_deleted))
7060                         .setContentText(wipeReasonForUser)
7061                         .setColor(mContext.getColor(R.color.system_notification_accent_color))
7062                         .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
7063                         .build();
7064         mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification);
7065     }
7066 
7067     private void clearWipeProfileNotification() {
7068         mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
7069     }
7070 
7071     @Override
7072     public void setFactoryResetProtectionPolicy(ComponentName who,
7073             @Nullable FactoryResetProtectionPolicy policy) {
7074         if (!mHasFeature) {
7075             return;
7076         }
7077         Preconditions.checkNotNull(who, "ComponentName is null");
7078         CallerIdentity caller = getCallerIdentity(who);
7079         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
7080                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
7081         checkCanExecuteOrThrowUnsafe(DevicePolicyManager
7082                 .OPERATION_SET_FACTORY_RESET_PROTECTION_POLICY);
7083 
7084         final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow();
7085         synchronized (getLockObject()) {
7086             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
7087             admin.mFactoryResetProtectionPolicy = policy;
7088             saveSettingsLocked(caller.getUserId());
7089         }
7090 
7091         mInjector.binderWithCleanCallingIdentity(
7092                 () -> notifyResetProtectionPolicyChanged(frpManagementAgentUid));
7093 
7094         DevicePolicyEventLogger
7095                 .createEvent(DevicePolicyEnums.SET_FACTORY_RESET_PROTECTION)
7096                 .setAdmin(who)
7097                 .write();
7098     }
7099 
7100     // Shouldn't be called from binder thread without clearing identity.
7101     private void notifyResetProtectionPolicyChanged(int frpManagementAgentUid) {
7102         final Intent intent = new Intent(
7103                 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED).addFlags(
7104                 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND | Intent.FLAG_RECEIVER_FOREGROUND);
7105         mContext.sendBroadcastAsUser(intent,
7106                 UserHandle.getUserHandleForUid(frpManagementAgentUid),
7107                 permission.MANAGE_FACTORY_RESET_PROTECTION);
7108     }
7109 
7110     @Override
7111     public FactoryResetProtectionPolicy getFactoryResetProtectionPolicy(
7112             @Nullable ComponentName who) {
7113         if (!mHasFeature) {
7114             return null;
7115         }
7116 
7117         final CallerIdentity caller = getCallerIdentity(who);
7118         final int frpManagementAgentUid = getFrpManagementAgentUidOrThrow();
7119         final ActiveAdmin admin;
7120         synchronized (getLockObject()) {
7121             if (who == null) {
7122                 Preconditions.checkCallAuthorization(frpManagementAgentUid == caller.getUid()
7123                                 || hasCallingPermission(permission.MASTER_CLEAR),
7124                         "Must be called by the FRP management agent on device");
7125                 admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
7126                         UserHandle.getUserId(frpManagementAgentUid));
7127             } else {
7128                 Preconditions.checkCallAuthorization(
7129                         isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller));
7130                 admin = getProfileOwnerOrDeviceOwnerLocked(caller);
7131             }
7132         }
7133 
7134         return admin != null ? admin.mFactoryResetProtectionPolicy : null;
7135     }
7136 
7137     private int getFrpManagementAgentUid() {
7138         PersistentDataBlockManagerInternal pdb = mInjector.getPersistentDataBlockManagerInternal();
7139         return pdb != null ? pdb.getAllowedUid() : -1;
7140     }
7141 
7142     private int getFrpManagementAgentUidOrThrow() {
7143         int uid = getFrpManagementAgentUid();
7144         if (uid == -1) {
7145             throw new UnsupportedOperationException(
7146                     "The persistent data block service is not supported on this device");
7147         }
7148         return uid;
7149     }
7150 
7151     @Override
7152     public boolean isFactoryResetProtectionPolicySupported() {
7153         return getFrpManagementAgentUid() != -1;
7154     }
7155 
7156     /**
7157      * Called by a privileged caller holding {@code BIND_DEVICE_ADMIN} permission to retrieve
7158      * the remove warning for the given device admin.
7159      */
7160     @Override
7161     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
7162         if (!mHasFeature) {
7163             return;
7164         }
7165         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7166 
7167         final CallerIdentity caller = getCallerIdentity();
7168         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7169         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
7170 
7171         synchronized (getLockObject()) {
7172             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
7173             if (admin == null) {
7174                 result.sendResult(null);
7175                 return;
7176             }
7177             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
7178             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
7179             intent.setComponent(admin.info.getComponent());
7180             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
7181                     null, new BroadcastReceiver() {
7182                 @Override
7183                 public void onReceive(Context context, Intent intent) {
7184                     result.sendResult(getResultExtras(false));
7185                 }
7186             }, null, Activity.RESULT_OK, null, null);
7187         }
7188     }
7189 
7190     @Override
7191     public void reportPasswordChanged(@UserIdInt int userId) {
7192         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
7193             return;
7194         }
7195 
7196         final CallerIdentity caller = getCallerIdentity();
7197         Preconditions.checkCallAuthorization(isSystemUid(caller));
7198         // Managed Profile password can only be changed when it has a separate challenge.
7199         if (!isSeparateProfileChallengeEnabled(userId)) {
7200             Preconditions.checkCallAuthorization(!isManagedProfile(userId), "You can "
7201                     + "not set the active password for a managed profile, userId = %d", userId);
7202         }
7203 
7204         DevicePolicyData policy = getUserData(userId);
7205         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
7206 
7207         synchronized (getLockObject()) {
7208             policy.mFailedPasswordAttempts = 0;
7209             affectedUserIds.add(userId);
7210             affectedUserIds.addAll(updatePasswordValidityCheckpointLocked(
7211                     userId, /* parent */ false));
7212             affectedUserIds.addAll(updatePasswordExpirationsLocked(userId));
7213             setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
7214 
7215             // Send a broadcast to each profile using this password as its primary unlock.
7216             sendAdminCommandForLockscreenPoliciesLocked(
7217                     DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
7218                     DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
7219 
7220             affectedUserIds.addAll(removeCaApprovalsIfNeeded(userId));
7221             saveSettingsForUsersLocked(affectedUserIds);
7222         }
7223     }
7224 
7225     /**
7226      * Called any time the device password is updated. Resets all password expiration clocks.
7227      *
7228      * @return the set of user IDs that have been affected
7229      */
7230     private Set<Integer> updatePasswordExpirationsLocked(int userHandle) {
7231         final ArraySet<Integer> affectedUserIds = new ArraySet<>();
7232         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle);
7233         for (int i = 0; i < admins.size(); i++) {
7234             ActiveAdmin admin = admins.get(i);
7235             if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
7236                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
7237                 long timeout = admin.passwordExpirationTimeout;
7238                 admin.passwordExpirationDate =
7239                         timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
7240             }
7241         }
7242         return affectedUserIds;
7243     }
7244 
7245     @Override
7246     public void reportFailedPasswordAttempt(int userHandle) {
7247         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7248 
7249         final CallerIdentity caller = getCallerIdentity();
7250         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7251         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
7252         if (!isSeparateProfileChallengeEnabled(userHandle)) {
7253             Preconditions.checkCallAuthorization(!isManagedProfile(userHandle),
7254                     "You can not report failed password attempt if separate profile challenge is "
7255                             + "not in place for a managed profile, userId = %d", userHandle);
7256         }
7257 
7258         boolean wipeData = false;
7259         ActiveAdmin strictestAdmin = null;
7260         final long ident = mInjector.binderClearCallingIdentity();
7261         try {
7262             synchronized (getLockObject()) {
7263                 DevicePolicyData policy = getUserData(userHandle);
7264                 policy.mFailedPasswordAttempts++;
7265                 saveSettingsLocked(userHandle);
7266                 if (mHasFeature) {
7267                     strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
7268                             userHandle, /* parent */ false);
7269                     int max = strictestAdmin != null
7270                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
7271                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
7272                         wipeData = true;
7273                     }
7274 
7275                     sendAdminCommandForLockscreenPoliciesLocked(
7276                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
7277                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
7278                 }
7279             }
7280         } finally {
7281             mInjector.binderRestoreCallingIdentity(ident);
7282         }
7283 
7284         if (wipeData && strictestAdmin != null) {
7285             final int userId = getUserIdToWipeForFailedPasswords(strictestAdmin);
7286             Slogf.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
7287                     + strictestAdmin.info.getComponent().flattenToShortString()
7288                     + ". Calling wipeData for user " + userId);
7289 
7290             // Attempt to wipe the device/user/profile associated with the admin, as if the
7291             // admin had called wipeData(). That way we can check whether the admin is actually
7292             // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
7293             // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
7294             // able to do so).
7295             // IMPORTANT: Call without holding the lock to prevent deadlock.
7296             try {
7297                 String wipeReasonForUser = mContext.getString(
7298                         R.string.work_profile_deleted_reason_maximum_password_failure);
7299                 wipeDataNoLock(strictestAdmin.info.getComponent(),
7300                         /*flags=*/ 0,
7301                         /*reason=*/ "reportFailedPasswordAttempt()",
7302                         wipeReasonForUser,
7303                         userId);
7304             } catch (SecurityException e) {
7305                 Slogf.w(LOG_TAG, "Failed to wipe user " + userId
7306                         + " after max failed password attempts reached.", e);
7307             }
7308         }
7309 
7310         if (mInjector.securityLogIsLoggingEnabled()) {
7311             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
7312                     /*result*/ 0, /*method strength*/ 1);
7313         }
7314     }
7315 
7316     /**
7317      * Returns which user should be wiped if this admin's maximum filed password attempts policy is
7318      * violated.
7319      */
7320     private int getUserIdToWipeForFailedPasswords(ActiveAdmin admin) {
7321         final int userId = admin.getUserHandle().getIdentifier();
7322         final ComponentName component = admin.info.getComponent();
7323         return isProfileOwnerOfOrganizationOwnedDevice(component, userId)
7324                 ? getProfileParentId(userId) : userId;
7325     }
7326 
7327     @Override
7328     public void reportSuccessfulPasswordAttempt(int userHandle) {
7329         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7330 
7331         final CallerIdentity caller = getCallerIdentity();
7332         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7333         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
7334 
7335         synchronized (getLockObject()) {
7336             DevicePolicyData policy = getUserData(userHandle);
7337             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
7338                 mInjector.binderWithCleanCallingIdentity(() -> {
7339                     policy.mFailedPasswordAttempts = 0;
7340                     policy.mPasswordOwner = -1;
7341                     saveSettingsLocked(userHandle);
7342                     if (mHasFeature) {
7343                         sendAdminCommandForLockscreenPoliciesLocked(
7344                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
7345                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
7346                     }
7347                 });
7348             }
7349         }
7350 
7351         if (mInjector.securityLogIsLoggingEnabled()) {
7352             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
7353                     /*method strength*/ 1);
7354         }
7355     }
7356 
7357     @Override
7358     public void reportFailedBiometricAttempt(int userHandle) {
7359         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7360 
7361         final CallerIdentity caller = getCallerIdentity();
7362         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7363         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
7364 
7365         if (mInjector.securityLogIsLoggingEnabled()) {
7366             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
7367                     /*method strength*/ 0);
7368         }
7369     }
7370 
7371     @Override
7372     public void reportSuccessfulBiometricAttempt(int userHandle) {
7373         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7374 
7375         final CallerIdentity caller = getCallerIdentity();
7376         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7377         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
7378 
7379         if (mInjector.securityLogIsLoggingEnabled()) {
7380             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
7381                     /*method strength*/ 0);
7382         }
7383     }
7384 
7385     @Override
7386     public void reportKeyguardDismissed(int userHandle) {
7387         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7388 
7389         final CallerIdentity caller = getCallerIdentity();
7390         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7391         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
7392 
7393         if (mInjector.securityLogIsLoggingEnabled()) {
7394             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
7395         }
7396     }
7397 
7398     @Override
7399     public void reportKeyguardSecured(int userHandle) {
7400         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7401 
7402         final CallerIdentity caller = getCallerIdentity();
7403         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7404         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(BIND_DEVICE_ADMIN));
7405 
7406         if (mInjector.securityLogIsLoggingEnabled()) {
7407             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
7408         }
7409     }
7410 
7411     @Override
7412     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
7413             String exclusionList) {
7414         if (!mHasFeature) {
7415             return null;
7416         }
7417         synchronized (getLockObject()) {
7418             Objects.requireNonNull(who, "ComponentName is null");
7419 
7420             // Only check if system user has set global proxy. We don't allow other users to set it.
7421             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
7422             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7423                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
7424 
7425             // Scan through active admins and find if anyone has already
7426             // set the global proxy.
7427             Set<ComponentName> compSet = policy.mAdminMap.keySet();
7428             for (ComponentName component : compSet) {
7429                 ActiveAdmin ap = policy.mAdminMap.get(component);
7430                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
7431                     // Another admin already sets the global proxy
7432                     // Return it to the caller.
7433                     return component;
7434                 }
7435             }
7436 
7437             // If the user is not system, don't set the global proxy. Fail silently.
7438             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
7439                 Slogf.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
7440                         + UserHandle.getCallingUserId() + " is not permitted.");
7441                 return null;
7442             }
7443             if (proxySpec == null) {
7444                 admin.specifiesGlobalProxy = false;
7445                 admin.globalProxySpec = null;
7446                 admin.globalProxyExclusionList = null;
7447             } else {
7448 
7449                 admin.specifiesGlobalProxy = true;
7450                 admin.globalProxySpec = proxySpec;
7451                 admin.globalProxyExclusionList = exclusionList;
7452             }
7453 
7454             // Reset the global proxy accordingly
7455             // Do this using system permissions, as apps cannot write to secure settings
7456             mInjector.binderWithCleanCallingIdentity(() -> resetGlobalProxyLocked(policy));
7457             return null;
7458         }
7459     }
7460 
7461     @Override
7462     public ComponentName getGlobalProxyAdmin(int userHandle) {
7463         if (!mHasFeature) {
7464             return null;
7465         }
7466         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7467 
7468         final CallerIdentity caller = getCallerIdentity();
7469         Preconditions.checkCallAuthorization(
7470                 hasFullCrossUsersPermission(caller, userHandle) && isSystemUid(caller));
7471 
7472         synchronized (getLockObject()) {
7473             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
7474             // Scan through active admins and find if anyone has already
7475             // set the global proxy.
7476             final int N = policy.mAdminList.size();
7477             for (int i = 0; i < N; i++) {
7478                 ActiveAdmin ap = policy.mAdminList.get(i);
7479                 if (ap.specifiesGlobalProxy) {
7480                     // Device admin sets the global proxy
7481                     // Return it to the caller.
7482                     return ap.info.getComponent();
7483                 }
7484             }
7485         }
7486         // No device admin sets the global proxy.
7487         return null;
7488     }
7489 
7490     @Override
7491     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
7492         Objects.requireNonNull(who, "ComponentName is null");
7493         final CallerIdentity caller = getCallerIdentity(who);
7494         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
7495         checkAllUsersAreAffiliatedWithDevice();
7496         mInjector.binderWithCleanCallingIdentity(
7497                 () -> mInjector.getConnectivityManager().setGlobalProxy(proxyInfo));
7498     }
7499 
7500     private void resetGlobalProxyLocked(DevicePolicyData policy) {
7501         final int N = policy.mAdminList.size();
7502         for (int i = 0; i < N; i++) {
7503             ActiveAdmin ap = policy.mAdminList.get(i);
7504             if (ap.specifiesGlobalProxy) {
7505                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
7506                 return;
7507             }
7508         }
7509         // No device admins defining global proxies - reset global proxy settings to none
7510         saveGlobalProxyLocked(null, null);
7511     }
7512 
7513     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
7514         if (exclusionList == null) {
7515             exclusionList = "";
7516         }
7517         if (proxySpec == null) {
7518             proxySpec = "";
7519         }
7520         // Remove white spaces
7521         proxySpec = proxySpec.trim();
7522         String data[] = proxySpec.split(":");
7523         int proxyPort = 8080;
7524         if (data.length > 1) {
7525             try {
7526                 proxyPort = Integer.parseInt(data[1]);
7527             } catch (NumberFormatException e) {}
7528         }
7529         exclusionList = exclusionList.trim();
7530 
7531         ProxyInfo proxyProperties = ProxyInfo.buildDirectProxy(data[0], proxyPort,
7532                 ProxyUtils.exclusionStringAsList(exclusionList));
7533         if (!proxyProperties.isValid()) {
7534             Slogf.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
7535             return;
7536         }
7537         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
7538         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
7539         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
7540                 exclusionList);
7541     }
7542 
7543     /**
7544      * Called by an application that is administering the device to request that the storage system
7545      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
7546      *
7547      * @return the new total request status (for all admins), or {@link
7548      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user
7549      */
7550     @Override
7551     public int setStorageEncryption(ComponentName who, boolean encrypt) {
7552         if (!mHasFeature) {
7553             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7554         }
7555         Objects.requireNonNull(who, "ComponentName is null");
7556         final int userHandle = UserHandle.getCallingUserId();
7557         synchronized (getLockObject()) {
7558             // Check for permissions
7559             // Only system user can set storage encryption
7560             if (userHandle != UserHandle.USER_SYSTEM) {
7561                 Slogf.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. "
7562                         + "User " + UserHandle.getCallingUserId() + " is not permitted.");
7563                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7564             }
7565 
7566             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7567                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
7568 
7569             // Quick exit:  If the filesystem does not support encryption, we can exit early.
7570             if (!isEncryptionSupported()) {
7571                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7572             }
7573 
7574             // (1) Record the value for the admin so it's sticky
7575             if (ap.encryptionRequested != encrypt) {
7576                 ap.encryptionRequested = encrypt;
7577                 saveSettingsLocked(userHandle);
7578             }
7579 
7580             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
7581             // (2) Compute "max" for all admins
7582             boolean newRequested = false;
7583             final int N = policy.mAdminList.size();
7584             for (int i = 0; i < N; i++) {
7585                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
7586             }
7587 
7588             // Notify OS of new request
7589             setEncryptionRequested(newRequested);
7590 
7591             // Return the new global request status
7592             return newRequested
7593                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
7594                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
7595         }
7596     }
7597 
7598     /**
7599      * Get the current storage encryption request status for a given admin, or aggregate of all
7600      * active admins.
7601      */
7602     @Override
7603     public boolean getStorageEncryption(@Nullable ComponentName who, int userHandle) {
7604         if (!mHasFeature) {
7605             return false;
7606         }
7607         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7608 
7609         final CallerIdentity caller = getCallerIdentity(who);
7610         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7611 
7612         synchronized (getLockObject()) {
7613             // Check for permissions if a particular caller is specified
7614             if (caller.hasAdminComponent()) {
7615                 // When checking for a single caller, status is based on caller's request
7616                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
7617                 return ap != null ? ap.encryptionRequested : false;
7618             }
7619 
7620             // If no particular caller is specified, return the aggregate set of requests.
7621             // This is short circuited by returning true on the first hit.
7622             DevicePolicyData policy = getUserData(userHandle);
7623             final int N = policy.mAdminList.size();
7624             for (int i = 0; i < N; i++) {
7625                 if (policy.mAdminList.get(i).encryptionRequested) {
7626                     return true;
7627                 }
7628             }
7629             return false;
7630         }
7631     }
7632 
7633     /**
7634      * Get the current encryption status of the device.
7635      */
7636     @Override
7637     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
7638         if (!mHasFeature) {
7639             // Ok to return current status.
7640         }
7641         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
7642 
7643         final CallerIdentity caller = getCallerIdentity(callerPackage);
7644         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7645 
7646 
7647         final ApplicationInfo ai;
7648         try {
7649             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
7650         } catch (RemoteException e) {
7651             throw new SecurityException(e);
7652         }
7653 
7654         boolean legacyApp = false;
7655         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
7656             legacyApp = true;
7657         }
7658 
7659         final int rawStatus = getEncryptionStatus();
7660         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
7661             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
7662         }
7663         return rawStatus;
7664     }
7665 
7666     /**
7667      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
7668      */
7669     private boolean isEncryptionSupported() {
7670         // Note, this can be implemented as
7671         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7672         // But is provided as a separate internal method if there's a faster way to do a
7673         // simple check for supported-or-not.
7674         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7675     }
7676 
7677     /**
7678      * Hook to low-levels:  Reporting the current status of encryption.
7679      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
7680      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
7681      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
7682      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
7683      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
7684      */
7685     private int getEncryptionStatus() {
7686         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
7687             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
7688         } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
7689             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
7690         } else if (mInjector.storageManagerIsEncrypted()) {
7691             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
7692         } else if (mInjector.storageManagerIsEncryptable()) {
7693             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
7694         } else {
7695             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7696         }
7697     }
7698 
7699     /**
7700      * Hook to low-levels:  If needed, record the new admin setting for encryption.
7701      */
7702     private void setEncryptionRequested(boolean encrypt) {
7703     }
7704 
7705     /**
7706      * Set whether the screen capture is disabled for the user managed by the specified admin.
7707      */
7708     @Override
7709     public void setScreenCaptureDisabled(ComponentName who, boolean disabled, boolean parent) {
7710         if (!mHasFeature) {
7711             return;
7712         }
7713         Objects.requireNonNull(who, "ComponentName is null");
7714 
7715         final CallerIdentity caller = getCallerIdentity(who);
7716         if (parent) {
7717             Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
7718         }
7719 
7720         synchronized (getLockObject()) {
7721             ActiveAdmin ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller),
7722                     parent);
7723             if (ap.disableScreenCapture != disabled) {
7724                 ap.disableScreenCapture = disabled;
7725                 saveSettingsLocked(caller.getUserId());
7726                 final int affectedUserId = parent
7727                         ? getProfileParentId(caller.getUserId())
7728                         : caller.getUserId();
7729                 updateScreenCaptureDisabled(affectedUserId, disabled);
7730             }
7731         }
7732         DevicePolicyEventLogger
7733                 .createEvent(DevicePolicyEnums.SET_SCREEN_CAPTURE_DISABLED)
7734                 .setAdmin(caller.getComponentName())
7735                 .setBoolean(disabled)
7736                 .write();
7737     }
7738 
7739     /**
7740      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
7741      * active admin (if given admin is null).
7742      */
7743     @Override
7744     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle, boolean parent) {
7745         if (!mHasFeature) {
7746             return false;
7747         }
7748 
7749         final CallerIdentity caller = getCallerIdentity(who);
7750         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
7751 
7752         if (parent) {
7753             Preconditions.checkCallAuthorization(
7754                     isProfileOwnerOfOrganizationOwnedDevice(getCallerIdentity().getUserId()));
7755         }
7756 
7757         synchronized (getLockObject()) {
7758             if (who != null) {
7759                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
7760                 return (admin != null) && admin.disableScreenCapture;
7761             }
7762 
7763             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
7764             List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(affectedUserId);
7765             for (ActiveAdmin admin: admins) {
7766                 if (admin.disableScreenCapture) {
7767                     return true;
7768                 }
7769             }
7770             return false;
7771         }
7772     }
7773 
7774     private void updateScreenCaptureDisabled(int userHandle, boolean disabled) {
7775         mPolicyCache.setScreenCaptureAllowed(userHandle, !disabled);
7776         mHandler.post(() -> {
7777             try {
7778                 mInjector.getIWindowManager().refreshScreenCaptureDisabled(userHandle);
7779             } catch (RemoteException e) {
7780                 Slogf.w(LOG_TAG, "Unable to notify WindowManager.", e);
7781             }
7782         });
7783     }
7784 
7785     @Override
7786     public void setNearbyNotificationStreamingPolicy(int policy) {
7787         if (!mHasFeature) {
7788             return;
7789         }
7790 
7791         final CallerIdentity caller = getCallerIdentity();
7792         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
7793 
7794         synchronized (getLockObject()) {
7795             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
7796             if (admin.mNearbyNotificationStreamingPolicy != policy) {
7797                 admin.mNearbyNotificationStreamingPolicy = policy;
7798                 saveSettingsLocked(caller.getUserId());
7799             }
7800         }
7801     }
7802 
7803     @Override
7804     public int getNearbyNotificationStreamingPolicy(final int userId) {
7805         if (!mHasFeature) {
7806             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
7807         }
7808 
7809         final CallerIdentity caller = getCallerIdentity();
7810         Preconditions.checkCallAuthorization(
7811                 isProfileOwner(caller)
7812                         || isDeviceOwner(caller)
7813                         || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY));
7814 
7815         synchronized (getLockObject()) {
7816             if (mOwners.hasProfileOwner(userId) || mOwners.hasDeviceOwner()) {
7817                 final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
7818                 return admin.mNearbyNotificationStreamingPolicy;
7819             }
7820         }
7821 
7822         return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
7823     }
7824 
7825     @Override
7826     public void setNearbyAppStreamingPolicy(int policy) {
7827         if (!mHasFeature) {
7828             return;
7829         }
7830 
7831         final CallerIdentity caller = getCallerIdentity();
7832         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
7833 
7834         synchronized (getLockObject()) {
7835             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
7836             if (admin.mNearbyAppStreamingPolicy != policy) {
7837                 admin.mNearbyAppStreamingPolicy = policy;
7838                 saveSettingsLocked(caller.getUserId());
7839             }
7840         }
7841     }
7842 
7843     @Override
7844     public int getNearbyAppStreamingPolicy(final int userId) {
7845         if (!mHasFeature) {
7846             return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
7847         }
7848 
7849         final CallerIdentity caller = getCallerIdentity();
7850         Preconditions.checkCallAuthorization(
7851                 isProfileOwner(caller)
7852                         || isDeviceOwner(caller)
7853                         || hasCallingOrSelfPermission(permission.READ_NEARBY_STREAMING_POLICY));
7854 
7855         synchronized (getLockObject()) {
7856             if (mOwners.hasProfileOwner(userId) || mOwners.hasDeviceOwner()) {
7857                 final ActiveAdmin admin = getDeviceOrProfileOwnerAdminLocked(userId);
7858                 return admin.mNearbyAppStreamingPolicy;
7859             }
7860         }
7861 
7862         return NEARBY_STREAMING_NOT_CONTROLLED_BY_POLICY;
7863     }
7864 
7865     /**
7866      * Set whether auto time is required by the specified admin (must be device or profile owner).
7867      */
7868     @Override
7869     public void setAutoTimeRequired(ComponentName who, boolean required) {
7870         if (!mHasFeature) {
7871             return;
7872         }
7873         Objects.requireNonNull(who, "ComponentName is null");
7874         final CallerIdentity caller = getCallerIdentity(who);
7875 
7876         boolean requireAutoTimeChanged = false;
7877         synchronized (getLockObject()) {
7878             Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
7879                     "Managed profile cannot set auto time required");
7880             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
7881             if (admin.requireAutoTime != required) {
7882                 admin.requireAutoTime = required;
7883                 saveSettingsLocked(caller.getUserId());
7884                 requireAutoTimeChanged = true;
7885             }
7886         }
7887         // requireAutoTime is now backed by DISALLOW_CONFIG_DATE_TIME restriction, so propagate
7888         // updated restrictions to the framework.
7889         if (requireAutoTimeChanged) {
7890             pushUserRestrictions(caller.getUserId());
7891         }
7892         // Turn AUTO_TIME on in settings if it is required
7893         if (required) {
7894             mInjector.binderWithCleanCallingIdentity(
7895                     () -> mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME,
7896                             1 /* AUTO_TIME on */));
7897         }
7898         DevicePolicyEventLogger
7899                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_REQUIRED)
7900                 .setAdmin(who)
7901                 .setBoolean(required)
7902                 .write();
7903     }
7904 
7905     /**
7906      * Returns whether or not auto time is required by the device owner or any profile owner.
7907      */
7908     @Override
7909     public boolean getAutoTimeRequired() {
7910         if (!mHasFeature) {
7911             return false;
7912         }
7913         synchronized (getLockObject()) {
7914             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7915             if (deviceOwner != null && deviceOwner.requireAutoTime) {
7916                 // If the device owner enforces auto time, we don't need to check the PO's
7917                 return true;
7918             }
7919 
7920             // Now check to see if any profile owner on any user enforces auto time
7921             for (Integer userId : mOwners.getProfileOwnerKeys()) {
7922                 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7923                 if (profileOwner != null && profileOwner.requireAutoTime) {
7924                     return true;
7925                 }
7926             }
7927 
7928             return false;
7929         }
7930     }
7931 
7932     /**
7933      * Set whether auto time is enabled on the device.
7934      */
7935     @Override
7936     public void setAutoTimeEnabled(ComponentName who, boolean enabled) {
7937         if (!mHasFeature) {
7938             return;
7939         }
7940         Objects.requireNonNull(who, "ComponentName is null");
7941 
7942         final CallerIdentity caller = getCallerIdentity(who);
7943         Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
7944                 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDeviceOwner(caller));
7945 
7946         mInjector.binderWithCleanCallingIdentity(() ->
7947                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, enabled ? 1 : 0));
7948 
7949         DevicePolicyEventLogger
7950                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME)
7951                 .setAdmin(caller.getComponentName())
7952                 .setBoolean(enabled)
7953                 .write();
7954     }
7955 
7956     /**
7957      * Returns whether auto time is used on the device or not.
7958      */
7959     @Override
7960     public boolean getAutoTimeEnabled(ComponentName who) {
7961         if (!mHasFeature) {
7962             return false;
7963         }
7964         Objects.requireNonNull(who, "ComponentName is null");
7965 
7966         final CallerIdentity caller = getCallerIdentity(who);
7967         Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
7968                 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDeviceOwner(caller));
7969 
7970         return mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) > 0;
7971     }
7972 
7973     /**
7974      * Set whether auto time zone is enabled on the device.
7975      */
7976     @Override
7977     public void setAutoTimeZoneEnabled(ComponentName who, boolean enabled) {
7978         if (!mHasFeature) {
7979             return;
7980         }
7981         Objects.requireNonNull(who, "ComponentName is null");
7982 
7983         final CallerIdentity caller = getCallerIdentity(who);
7984         Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
7985                 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDeviceOwner(caller));
7986 
7987         mInjector.binderWithCleanCallingIdentity(() ->
7988                 mInjector.settingsGlobalPutInt(Global.AUTO_TIME_ZONE, enabled ? 1 : 0));
7989 
7990         DevicePolicyEventLogger
7991                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_ZONE)
7992                 .setAdmin(caller.getComponentName())
7993                 .setBoolean(enabled)
7994                 .write();
7995     }
7996 
7997     /**
7998      * Returns whether auto time zone is used on the device or not.
7999      */
8000     @Override
8001     public boolean getAutoTimeZoneEnabled(ComponentName who) {
8002         if (!mHasFeature) {
8003             return false;
8004         }
8005         Objects.requireNonNull(who, "ComponentName is null");
8006 
8007         final CallerIdentity caller = getCallerIdentity(who);
8008         Preconditions.checkCallAuthorization(isProfileOwnerOnUser0(caller)
8009                 || isProfileOwnerOfOrganizationOwnedDevice(caller) || isDeviceOwner(caller));
8010 
8011         return mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) > 0;
8012     }
8013 
8014     // TODO (b/137101239): remove this method in follow-up CL
8015     // since it's only used for split system user.
8016     @Override
8017     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
8018         throw new UnsupportedOperationException("This method was used by split system user only.");
8019     }
8020 
8021     // TODO (b/137101239): remove this method in follow-up CL
8022     // since it's only used for split system user.
8023     @Override
8024     public boolean getForceEphemeralUsers(ComponentName who) {
8025         throw new UnsupportedOperationException("This method was used by split system user only.");
8026     }
8027 
8028     @Override
8029     public boolean requestBugreport(ComponentName who) {
8030         if (!mHasFeature) {
8031             return false;
8032         }
8033         Objects.requireNonNull(who, "ComponentName is null");
8034         // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
8035         // which could still contain data related to that user. Should we disallow that, e.g. until
8036         // next boot? Might not be needed given that this still requires user consent.
8037         final CallerIdentity caller = getCallerIdentity(who);
8038         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
8039         checkAllUsersAreAffiliatedWithDevice();
8040         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REQUEST_BUGREPORT);
8041 
8042         if (mBugreportCollectionManager.requestBugreport()) {
8043             DevicePolicyEventLogger
8044                     .createEvent(DevicePolicyEnums.REQUEST_BUGREPORT)
8045                     .setAdmin(who)
8046                     .write();
8047 
8048             final long currentTime = System.currentTimeMillis();
8049             synchronized (getLockObject()) {
8050                 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
8051                 if (currentTime > policyData.mLastBugReportRequestTime) {
8052                     policyData.mLastBugReportRequestTime = currentTime;
8053                     saveSettingsLocked(UserHandle.USER_SYSTEM);
8054                 }
8055             }
8056 
8057             return true;
8058         } else {
8059             return false;
8060         }
8061     }
8062 
8063     void sendDeviceOwnerCommand(String action, Bundle extras) {
8064         final int deviceOwnerUserId;
8065         final ComponentName receiverComponent;
8066         synchronized (getLockObject()) {
8067             deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
8068             receiverComponent = mOwners.getDeviceOwnerComponent();
8069         }
8070         sendActiveAdminCommand(action, extras, deviceOwnerUserId, receiverComponent,
8071                 /* inForeground */ false);
8072     }
8073 
8074     void sendDeviceOwnerOrProfileOwnerCommand(String action, Bundle extras, int userId) {
8075         if (userId == UserHandle.USER_ALL) {
8076             userId = UserHandle.USER_SYSTEM;
8077         }
8078         boolean inForeground = false;
8079         ComponentName receiverComponent = null;
8080         if (action.equals(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE)) {
8081             inForeground = true;
8082             receiverComponent = resolveDelegateReceiver(DELEGATION_NETWORK_LOGGING, action, userId);
8083         }
8084         if (action.equals(DeviceAdminReceiver.ACTION_SECURITY_LOGS_AVAILABLE)) {
8085             inForeground = true;
8086             receiverComponent = resolveDelegateReceiver(
8087                 DELEGATION_SECURITY_LOGGING, action, userId);
8088         }
8089         if (receiverComponent == null) {
8090             receiverComponent = getOwnerComponent(userId);
8091         }
8092         sendActiveAdminCommand(action, extras, userId, receiverComponent, inForeground);
8093     }
8094 
8095     private void sendProfileOwnerCommand(String action, Bundle extras, @UserIdInt int userId) {
8096         sendActiveAdminCommand(action, extras, userId, mOwners.getProfileOwnerComponent(userId),
8097                 /* inForeground */ false);
8098     }
8099 
8100     private void sendActiveAdminCommand(String action, Bundle extras,
8101             @UserIdInt int userId, ComponentName receiverComponent, boolean inForeground) {
8102         final Intent intent = new Intent(action);
8103         intent.setComponent(receiverComponent);
8104         if (extras != null) {
8105             intent.putExtras(extras);
8106         }
8107         if (inForeground) {
8108             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8109         }
8110 
8111         if (VERBOSE_LOG) {
8112             Slogf.v(LOG_TAG, "sendActiveAdminCommand(): broadcasting " + action + " to "
8113                     + receiverComponent.flattenToShortString() + " on user " + userId);
8114         }
8115         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
8116     }
8117 
8118     private void sendOwnerChangedBroadcast(String broadcast, int userId) {
8119         final Intent intent = new Intent(broadcast)
8120                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
8121         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
8122     }
8123 
8124     void sendBugreportToDeviceOwner(Uri bugreportUri, String bugreportHash) {
8125         synchronized (getLockObject()) {
8126             final Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
8127             intent.setComponent(mOwners.getDeviceOwnerComponent());
8128             intent.setDataAndType(bugreportUri, RemoteBugreportManager.BUGREPORT_MIMETYPE);
8129             intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
8130             intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8131 
8132             final UriGrantsManagerInternal ugm = LocalServices
8133                     .getService(UriGrantsManagerInternal.class);
8134             final NeededUriGrants needed = ugm.checkGrantUriPermissionFromIntent(intent,
8135                     Process.SHELL_UID, mOwners.getDeviceOwnerComponent().getPackageName(),
8136                     mOwners.getDeviceOwnerUserId());
8137             ugm.grantUriPermissionUncheckedFromIntent(needed, null);
8138 
8139             mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
8140         }
8141     }
8142 
8143     void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash) {
8144         synchronized (getLockObject()) {
8145             mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
8146         }
8147     }
8148 
8149     Pair<String, String> getDeviceOwnerRemoteBugreportUriAndHash() {
8150         synchronized (getLockObject()) {
8151             final String uri = mOwners.getDeviceOwnerRemoteBugreportUri();
8152             return uri == null ? null
8153                     : new Pair<>(uri, mOwners.getDeviceOwnerRemoteBugreportHash());
8154         }
8155     }
8156 
8157     /**
8158      * Disables all device cameras according to the specified admin.
8159      */
8160     @Override
8161     public void setCameraDisabled(ComponentName who, boolean disabled, boolean parent) {
8162         if (!mHasFeature) {
8163             return;
8164         }
8165         Objects.requireNonNull(who, "ComponentName is null");
8166 
8167         final CallerIdentity caller = getCallerIdentity(who);
8168         if (parent) {
8169             Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
8170         }
8171         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_CAMERA_DISABLED);
8172 
8173         final int userHandle = caller.getUserId();
8174         synchronized (getLockObject()) {
8175             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
8176                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA, parent);
8177             if (ap.disableCamera != disabled) {
8178                 ap.disableCamera = disabled;
8179                 saveSettingsLocked(userHandle);
8180             }
8181         }
8182         // Tell the user manager that the restrictions have changed.
8183         pushUserRestrictions(userHandle);
8184 
8185         final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
8186         if (SecurityLog.isLoggingEnabled()) {
8187             SecurityLog.writeEvent(SecurityLog.TAG_CAMERA_POLICY_SET,
8188                     who.getPackageName(), userHandle, affectedUserId, disabled ? 1 : 0);
8189         }
8190         DevicePolicyEventLogger
8191                 .createEvent(DevicePolicyEnums.SET_CAMERA_DISABLED)
8192                 .setAdmin(caller.getComponentName())
8193                 .setBoolean(disabled)
8194                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
8195                 .write();
8196     }
8197 
8198     /**
8199      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
8200      * active admins.
8201      */
8202     @Override
8203     public boolean getCameraDisabled(ComponentName who, int userHandle, boolean parent) {
8204         if (!mHasFeature) {
8205             return false;
8206         }
8207 
8208         final CallerIdentity caller = getCallerIdentity(who);
8209         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8210 
8211         if (parent) {
8212             Preconditions.checkCallAuthorization(
8213                     isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId()));
8214         }
8215 
8216         synchronized (getLockObject()) {
8217             if (who != null) {
8218                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
8219                 return (admin != null) && admin.disableCamera;
8220             }
8221             // First, see if DO has set it.  If so, it's device-wide.
8222             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
8223             if (deviceOwner != null && deviceOwner.disableCamera) {
8224                 return true;
8225             }
8226             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
8227             // Return the strictest policy across all participating admins.
8228             List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(affectedUserId);
8229             // Determine whether or not the device camera is disabled for any active admins.
8230             for (ActiveAdmin admin : admins) {
8231                 if (admin.disableCamera) {
8232                     return true;
8233                 }
8234             }
8235             return false;
8236         }
8237     }
8238 
8239     @Override
8240     public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
8241         if (!mHasFeature) {
8242             return;
8243         }
8244         Objects.requireNonNull(who, "ComponentName is null");
8245 
8246         final CallerIdentity caller = getCallerIdentity(who);
8247 
8248         final int userHandle = caller.getUserId();
8249         synchronized (getLockObject()) {
8250             ActiveAdmin ap = getActiveAdminForCallerLocked(
8251                     who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
8252             if (isManagedProfile(userHandle)) {
8253                 if (parent) {
8254                     if (isProfileOwnerOfOrganizationOwnedDevice(caller)) {
8255                         which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
8256                     } else {
8257                         which = which & NON_ORG_OWNED_PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
8258                     }
8259                 } else {
8260                     which = which & PROFILE_KEYGUARD_FEATURES;
8261                 }
8262             }
8263             if (ap.disabledKeyguardFeatures != which) {
8264                 ap.disabledKeyguardFeatures = which;
8265                 saveSettingsLocked(userHandle);
8266             }
8267         }
8268         if (SecurityLog.isLoggingEnabled()) {
8269             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
8270             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET,
8271                     who.getPackageName(), userHandle, affectedUserId, which);
8272         }
8273         DevicePolicyEventLogger
8274                 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED_FEATURES)
8275                 .setAdmin(caller.getComponentName())
8276                 .setInt(which)
8277                 .setStrings(parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
8278                 .write();
8279     }
8280 
8281     /**
8282      * Gets the disabled state for features in keyguard for the given admin,
8283      * or the aggregate of all active admins if who is null.
8284      */
8285     @Override
8286     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
8287         if (!mHasFeature) {
8288             return 0;
8289         }
8290         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
8291 
8292         final CallerIdentity caller = getCallerIdentity();
8293         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
8294         Preconditions.checkCallAuthorization(
8295                 who == null || isCallingFromPackage(who.getPackageName(), caller.getUid())
8296                         || isSystemUid(caller));
8297 
8298         final long ident = mInjector.binderClearCallingIdentity();
8299         try {
8300             synchronized (getLockObject()) {
8301                 if (who != null) {
8302                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
8303                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
8304                 }
8305 
8306                 final List<ActiveAdmin> admins;
8307                 if (!parent && isManagedProfile(userHandle)) {
8308                     // If we are being asked about a managed profile, just return keyguard features
8309                     // disabled by admins in the profile.
8310                     admins = getUserDataUnchecked(userHandle).mAdminList;
8311                 } else {
8312                     // Otherwise return those set by admins in the user and its profiles.
8313                     admins = getActiveAdminsForLockscreenPoliciesLocked(
8314                             getProfileParentUserIfRequested(userHandle, parent));
8315                 }
8316 
8317                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
8318                 final int N = admins.size();
8319                 for (int i = 0; i < N; i++) {
8320                     ActiveAdmin admin = admins.get(i);
8321                     int userId = admin.getUserHandle().getIdentifier();
8322                     boolean isRequestedUser = !parent && (userId == userHandle);
8323                     if (isRequestedUser || !isManagedProfile(userId)) {
8324                         // If we are being asked explicitly about this user
8325                         // return all disabled features even if its a managed profile.
8326                         which |= admin.disabledKeyguardFeatures;
8327                     } else {
8328                         // Otherwise a managed profile is only allowed to disable
8329                         // some features on the parent user.
8330                         which |= (admin.disabledKeyguardFeatures
8331                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
8332                     }
8333                 }
8334                 return which;
8335             }
8336         } finally {
8337             mInjector.binderRestoreCallingIdentity(ident);
8338         }
8339     }
8340 
8341     @Override
8342     public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
8343             List<String> packageList) {
8344         if (!mHasFeature) {
8345             return;
8346         }
8347         Objects.requireNonNull(packageList, "packageList is null");
8348         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
8349         Preconditions.checkCallAuthorization((caller.hasAdminComponent() &&  isDeviceOwner(caller))
8350                 || (caller.hasPackage()
8351                 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES)));
8352         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEEP_UNINSTALLED_PACKAGES);
8353 
8354         synchronized (getLockObject()) {
8355             // Get the device owner
8356             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
8357             // Set list of packages to be kept even if uninstalled.
8358             deviceOwner.keepUninstalledPackages = packageList;
8359             // Save settings.
8360             saveSettingsLocked(caller.getUserId());
8361             // Notify package manager.
8362             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
8363         }
8364         DevicePolicyEventLogger
8365                 .createEvent(DevicePolicyEnums.SET_KEEP_UNINSTALLED_PACKAGES)
8366                 .setAdmin(caller.getPackageName())
8367                 .setBoolean(/* isDelegate */ who == null)
8368                 .setStrings(packageList.toArray(new String[0]))
8369                 .write();
8370     }
8371 
8372     @Override
8373     public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
8374         if (!mHasFeature) {
8375             return null;
8376         }
8377         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
8378         Preconditions.checkCallAuthorization((caller.hasAdminComponent() &&  isDeviceOwner(caller))
8379                 || (caller.hasPackage()
8380                 && isCallerDelegate(caller, DELEGATION_KEEP_UNINSTALLED_PACKAGES)));
8381 
8382         synchronized (getLockObject()) {
8383             return getKeepUninstalledPackagesLocked();
8384         }
8385     }
8386 
8387     private List<String> getKeepUninstalledPackagesLocked() {
8388         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
8389         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
8390     }
8391 
8392     /**
8393      * Logs a warning when the device doesn't have {@code PackageManager.FEATURE_DEVICE_ADMIN}.
8394      *
8395      * @param message action that was not executed; should not end with a period because the missing
8396      * feature will be appended to it.
8397      */
8398     private void logMissingFeatureAction(String message) {
8399         Slogf.w(LOG_TAG, message + " because device does not have the "
8400                 + PackageManager.FEATURE_DEVICE_ADMIN + " feature.");
8401     }
8402 
8403     @Override
8404     public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId,
8405             boolean setProfileOwnerOnCurrentUserIfNecessary) {
8406         if (!mHasFeature) {
8407             logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(admin)
8408                     + " as device owner for user " + userId);
8409             return false;
8410         }
8411         Preconditions.checkArgument(admin != null);
8412 
8413         final CallerIdentity caller = getCallerIdentity();
8414         // Cannot be called while holding the lock:
8415         final boolean hasIncompatibleAccountsOrNonAdb =
8416                 hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, admin);
8417         synchronized (getLockObject()) {
8418             enforceCanSetDeviceOwnerLocked(caller, admin, userId, hasIncompatibleAccountsOrNonAdb);
8419             Preconditions.checkArgument(isPackageInstalledForUser(admin.getPackageName(), userId),
8420                     "Invalid component " + admin + " for device owner");
8421             final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
8422             Preconditions.checkArgument(activeAdmin != null && !getUserData(
8423                     userId).mRemovingAdmins.contains(admin), "Not active admin: " + admin);
8424 
8425             // Shutting down backup manager service permanently.
8426             toggleBackupServiceActive(UserHandle.USER_SYSTEM, /* makeActive= */ false);
8427             if (isAdb(caller)) {
8428                 // Log device owner provisioning was started using adb.
8429                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
8430                 DevicePolicyEventLogger
8431                         .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
8432                         .setAdmin(admin)
8433                         .setStrings(LOG_TAG_DEVICE_OWNER)
8434                         .write();
8435             }
8436 
8437             mOwners.setDeviceOwner(admin, ownerName, userId);
8438             mOwners.writeDeviceOwner();
8439             updateDeviceOwnerLocked();
8440             setDeviceOwnershipSystemPropertyLocked();
8441 
8442             //TODO(b/180371154): when provisionFullyManagedDevice is used in tests, remove this
8443             // hard-coded default value setting.
8444             if (isAdb(caller)) {
8445                 activeAdmin.mAdminCanGrantSensorsPermissions = true;
8446                 mPolicyCache.setAdminCanGrantSensorsPermissions(userId, true);
8447                 saveSettingsLocked(userId);
8448             }
8449 
8450             mInjector.binderWithCleanCallingIdentity(() -> {
8451                 // Restrict adding a managed profile when a device owner is set on the device.
8452                 // That is to prevent the co-existence of a managed profile and a device owner
8453                 // on the same device.
8454                 // Instead, the device may be provisioned with an organization-owned managed
8455                 // profile, such that the admin on that managed profile has extended management
8456                 // capabilities that can affect the entire device (but not access private data
8457                 // on the primary profile).
8458                 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, true,
8459                         UserHandle.of(userId));
8460                 // TODO Send to system too?
8461                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId);
8462             });
8463             mDeviceAdminServiceController.startServiceForOwner(
8464                     admin.getPackageName(), userId, "set-device-owner");
8465 
8466             Slogf.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
8467 
8468             if (setProfileOwnerOnCurrentUserIfNecessary
8469                     && mInjector.userManagerIsHeadlessSystemUserMode()) {
8470                 int currentForegroundUser = getCurrentForegroundUserId();
8471                 Slogf.i(LOG_TAG, "setDeviceOwner(): setting " + admin
8472                         + " as profile owner on user " + currentForegroundUser);
8473                 // Sets profile owner on current foreground user since
8474                 // the human user will complete the DO setup workflow from there.
8475                 manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin,
8476                         /* managedUser= */ currentForegroundUser, /* adminExtras= */ null,
8477                         /* showDisclaimer= */ false);
8478             }
8479             return true;
8480         }
8481     }
8482 
8483     @Override
8484     public boolean hasDeviceOwner() {
8485         final CallerIdentity caller = getCallerIdentity();
8486         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || canManageUsers(caller));
8487         return mOwners.hasDeviceOwner();
8488     }
8489 
8490     boolean isDeviceOwner(ActiveAdmin admin) {
8491         return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
8492     }
8493 
8494     public boolean isDeviceOwner(ComponentName who, int userId) {
8495         synchronized (getLockObject()) {
8496             return mOwners.hasDeviceOwner()
8497                     && mOwners.getDeviceOwnerUserId() == userId
8498                     && mOwners.getDeviceOwnerComponent().equals(who);
8499         }
8500     }
8501 
8502     private boolean isDeviceOwner(CallerIdentity caller) {
8503         synchronized (getLockObject()) {
8504             if (!mOwners.hasDeviceOwner() || mOwners.getDeviceOwnerUserId() != caller.getUserId()) {
8505                 return false;
8506             }
8507 
8508             if (caller.hasAdminComponent()) {
8509                 return mOwners.getDeviceOwnerComponent().equals(caller.getComponentName());
8510             } else {
8511                 return isUidDeviceOwnerLocked(caller.getUid());
8512             }
8513         }
8514     }
8515 
8516     private boolean isDeviceOwnerPackage(String packageName, int userId) {
8517         synchronized (getLockObject()) {
8518             return mOwners.hasDeviceOwner()
8519                     && mOwners.getDeviceOwnerUserId() == userId
8520                     && mOwners.getDeviceOwnerPackageName().equals(packageName);
8521         }
8522     }
8523 
8524     private boolean isProfileOwnerPackage(String packageName, int userId) {
8525         synchronized (getLockObject()) {
8526             return mOwners.hasProfileOwner(userId)
8527                     && mOwners.getProfileOwnerPackage(userId).equals(packageName);
8528         }
8529     }
8530 
8531     public boolean isProfileOwner(ComponentName who, int userId) {
8532         final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() ->
8533                 getProfileOwnerAsUser(userId));
8534         return who != null && who.equals(profileOwner);
8535     }
8536 
8537     /**
8538      * Returns {@code true} if the provided caller identity is of a profile owner.
8539      * @param caller identity of caller.
8540      * @return true if {@code identity} is a profile owner, false otherwise.
8541      */
8542     public boolean isProfileOwner(CallerIdentity caller) {
8543         synchronized (getLockObject()) {
8544             final ComponentName profileOwner = mInjector.binderWithCleanCallingIdentity(() ->
8545                     getProfileOwnerAsUser(caller.getUserId()));
8546             // No profile owner.
8547             if (profileOwner == null) {
8548                 return false;
8549             }
8550             // The admin ComponentName was specified, check it directly.
8551             if (caller.hasAdminComponent()) {
8552                 return profileOwner.equals(caller.getComponentName());
8553             } else {
8554                 return isUidProfileOwnerLocked(caller.getUid());
8555             }
8556         }
8557     }
8558 
8559     /**
8560      * Checks if the app uid provided is the profile owner. This method should only be called
8561      * if no componentName is available.
8562      *
8563      * @param appUid UID of the caller.
8564      * @return true if the caller is the profile owner
8565      */
8566     private boolean isUidProfileOwnerLocked(int appUid) {
8567         ensureLocked();
8568 
8569         final int userId = UserHandle.getUserId(appUid);
8570         final ComponentName profileOwnerComponent = mOwners.getProfileOwnerComponent(userId);
8571         if (profileOwnerComponent == null) {
8572             return false;
8573         }
8574         for (ActiveAdmin admin : getUserData(userId).mAdminList) {
8575             final ComponentName currentAdminComponent = admin.info.getComponent();
8576             if (admin.getUid() == appUid && profileOwnerComponent.equals(currentAdminComponent)) {
8577                 return true;
8578             }
8579         }
8580         return false;
8581     }
8582 
8583     private boolean hasProfileOwner(int userId) {
8584         synchronized (getLockObject()) {
8585             return mOwners.hasProfileOwner(userId);
8586         }
8587     }
8588 
8589     /**
8590      * Returns {@code true} if the provided caller identity is of a profile owner of an organization
8591      * owned device.
8592      *
8593      * @param caller identity of caller
8594      * @return true if {@code identity} is a profile owner of an organization owned device, false
8595      * otherwise.
8596      */
8597     private boolean isProfileOwnerOfOrganizationOwnedDevice(CallerIdentity caller) {
8598         return isProfileOwner(caller) && isProfileOwnerOfOrganizationOwnedDevice(
8599                 caller.getUserId());
8600     }
8601 
8602     private boolean isProfileOwnerOfOrganizationOwnedDevice(int userId) {
8603         synchronized (getLockObject()) {
8604             return mOwners.isProfileOwnerOfOrganizationOwnedDevice(userId);
8605         }
8606     }
8607 
8608     private boolean isProfileOwnerOfOrganizationOwnedDevice(ComponentName who, int userId) {
8609         return isProfileOwner(who, userId) && isProfileOwnerOfOrganizationOwnedDevice(userId);
8610     }
8611 
8612     private boolean isProfileOwnerOnUser0(CallerIdentity caller) {
8613         return isProfileOwner(caller) && caller.getUserHandle().isSystem();
8614     }
8615 
8616     private boolean isPackage(CallerIdentity caller, String packageName) {
8617         return isCallingFromPackage(packageName, caller.getUid());
8618     }
8619 
8620     @Override
8621     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
8622         if (!mHasFeature) {
8623             return null;
8624         }
8625         if (!callingUserOnly) {
8626             Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity())
8627                     || hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
8628         }
8629         synchronized (getLockObject()) {
8630             if (!mOwners.hasDeviceOwner()) {
8631                 return null;
8632             }
8633             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
8634                     mOwners.getDeviceOwnerUserId()) {
8635                 return null;
8636             }
8637             return mOwners.getDeviceOwnerComponent();
8638         }
8639     }
8640 
8641     private int getDeviceOwnerUserIdUncheckedLocked() {
8642         return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
8643     }
8644 
8645     @Override
8646     public int getDeviceOwnerUserId() {
8647         if (!mHasFeature) {
8648             return UserHandle.USER_NULL;
8649         }
8650         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
8651 
8652         synchronized (getLockObject()) {
8653             return getDeviceOwnerUserIdUncheckedLocked();
8654         }
8655     }
8656 
8657     /**
8658      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
8659      * MANAGE_USERS.
8660      */
8661     @Override
8662     public String getDeviceOwnerName() {
8663         if (!mHasFeature) {
8664             return null;
8665         }
8666         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
8667 
8668         synchronized (getLockObject()) {
8669             if (!mOwners.hasDeviceOwner()) {
8670                 return null;
8671             }
8672             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
8673             // Should setDeviceOwner/ProfileOwner still take a name?
8674             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
8675             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
8676         }
8677     }
8678 
8679     /** Returns the active device owner or {@code null} if there is no device owner. */
8680     @VisibleForTesting
8681     ActiveAdmin getDeviceOwnerAdminLocked() {
8682         ensureLocked();
8683         ComponentName component = mOwners.getDeviceOwnerComponent();
8684         if (component == null) {
8685             return null;
8686         }
8687 
8688         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
8689         final int n = policy.mAdminList.size();
8690         for (int i = 0; i < n; i++) {
8691             ActiveAdmin admin = policy.mAdminList.get(i);
8692             if (component.equals(admin.info.getComponent())) {
8693                 return admin;
8694             }
8695         }
8696         Slogf.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
8697         return null;
8698     }
8699 
8700     ActiveAdmin getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(int userId) {
8701         ActiveAdmin admin = getDeviceOwnerAdminLocked();
8702         if (admin == null) {
8703             admin = getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
8704         }
8705         return admin;
8706     }
8707 
8708     @Override
8709     public void clearDeviceOwner(String packageName) {
8710         Objects.requireNonNull(packageName, "packageName is null");
8711 
8712         final CallerIdentity caller = getCallerIdentity(packageName);
8713         synchronized (getLockObject()) {
8714             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
8715             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
8716             if (!mOwners.hasDeviceOwner()
8717                     || !deviceOwnerComponent.getPackageName().equals(packageName)
8718                     || (deviceOwnerUserId != caller.getUserId())) {
8719                 throw new SecurityException(
8720                         "clearDeviceOwner can only be called by the device owner");
8721             }
8722             enforceUserUnlocked(deviceOwnerUserId);
8723             DevicePolicyData policy = getUserData(deviceOwnerUserId);
8724             if (policy.mPasswordTokenHandle != 0) {
8725                 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, deviceOwnerUserId);
8726             }
8727 
8728             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
8729             mInjector.binderWithCleanCallingIdentity(() -> {
8730                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
8731                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
8732                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED,
8733                         deviceOwnerUserId);
8734             });
8735             Slogf.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
8736         }
8737     }
8738 
8739     private void clearOverrideApnUnchecked() {
8740         if (!mHasTelephonyFeature) {
8741             return;
8742         }
8743         // Disable Override APNs and remove them from database.
8744         setOverrideApnsEnabledUnchecked(false);
8745         final List<ApnSetting> apns = getOverrideApnsUnchecked();
8746         for (int i = 0; i < apns.size(); i ++) {
8747             removeOverrideApnUnchecked(apns.get(i).getId());
8748         }
8749     }
8750 
8751     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
8752         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
8753 
8754         if (admin != null) {
8755             admin.disableCamera = false;
8756             admin.userRestrictions = null;
8757             admin.defaultEnabledRestrictionsAlreadySet.clear();
8758             admin.forceEphemeralUsers = false;
8759             admin.isNetworkLoggingEnabled = false;
8760             admin.requireAutoTime = false;
8761             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
8762         }
8763         final DevicePolicyData policyData = getUserData(userId);
8764         policyData.mCurrentInputMethodSet = false;
8765         saveSettingsLocked(userId);
8766         mPolicyCache.onUserRemoved(userId);
8767         final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
8768         systemPolicyData.mLastSecurityLogRetrievalTime = -1;
8769         systemPolicyData.mLastBugReportRequestTime = -1;
8770         systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
8771         saveSettingsLocked(UserHandle.USER_SYSTEM);
8772         clearUserPoliciesLocked(userId);
8773         clearOverrideApnUnchecked();
8774         clearApplicationRestrictions(userId);
8775         mInjector.getPackageManagerInternal().clearBlockUninstallForUser(userId);
8776 
8777         mOwners.clearDeviceOwner();
8778         mOwners.writeDeviceOwner();
8779         updateDeviceOwnerLocked();
8780 
8781         clearDeviceOwnerUserRestriction(UserHandle.of(userId));
8782         mInjector.securityLogSetLoggingEnabledProperty(false);
8783         mSecurityLogMonitor.stop();
8784         setNetworkLoggingActiveInternal(false);
8785         deleteTransferOwnershipBundleLocked(userId);
8786         toggleBackupServiceActive(UserHandle.USER_SYSTEM, true);
8787     }
8788 
8789     private void clearApplicationRestrictions(int userId) {
8790         // Changing app restrictions involves disk IO, offload it to the background thread.
8791         mBackgroundHandler.post(() -> {
8792             final List<PackageInfo> installedPackageInfos = mInjector.getPackageManager(userId)
8793                     .getInstalledPackages(MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
8794             final UserHandle userHandle = UserHandle.of(userId);
8795             for (final PackageInfo packageInfo : installedPackageInfos) {
8796                 mInjector.getUserManager().setApplicationRestrictions(
8797                         packageInfo.packageName, null /* restrictions */, userHandle);
8798             }
8799         });
8800     }
8801 
8802     @Override
8803     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
8804         if (!mHasFeature) {
8805             logMissingFeatureAction("Cannot set " + ComponentName.flattenToShortString(who)
8806                     + " as profile owner for user " + userHandle);
8807             return false;
8808         }
8809         Preconditions.checkArgument(who != null);
8810 
8811         final CallerIdentity caller = getCallerIdentity();
8812         // Cannot be called while holding the lock:
8813         final boolean hasIncompatibleAccountsOrNonAdb =
8814                 hasIncompatibleAccountsOrNonAdbNoLock(caller, userHandle, who);
8815         synchronized (getLockObject()) {
8816             enforceCanSetProfileOwnerLocked(
8817                     caller, who, userHandle, hasIncompatibleAccountsOrNonAdb);
8818             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8819             Preconditions.checkArgument(
8820                     isPackageInstalledForUser(who.getPackageName(), userHandle)
8821                             && admin != null
8822                             && !getUserData(userHandle).mRemovingAdmins.contains(who),
8823                     "Not active admin: " + who);
8824 
8825             final int parentUserId = getProfileParentId(userHandle);
8826             // When trying to set a profile owner on a new user, it may be that this user is
8827             // a profile - but it may not be a managed profile if there's a restriction on the
8828             // parent to add managed profiles (e.g. if the device has a device owner).
8829             if (parentUserId != userHandle && mUserManager.hasUserRestriction(
8830                     UserManager.DISALLOW_ADD_MANAGED_PROFILE,
8831                     UserHandle.of(parentUserId))) {
8832                 Slogf.i(LOG_TAG, "Cannot set profile owner because of restriction.");
8833                 return false;
8834             }
8835 
8836             if (isAdb(caller)) {
8837                 // Log profile owner provisioning was started using adb.
8838                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
8839                 DevicePolicyEventLogger
8840                         .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
8841                         .setAdmin(who)
8842                         .setStrings(LOG_TAG_PROFILE_OWNER)
8843                         .write();
8844             }
8845 
8846             // Shutting down backup manager service permanently.
8847             toggleBackupServiceActive(userHandle, /* makeActive= */ false);
8848 
8849             mOwners.setProfileOwner(who, ownerName, userHandle);
8850             mOwners.writeProfileOwner(userHandle);
8851             Slogf.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
8852 
8853             mInjector.binderWithCleanCallingIdentity(() -> {
8854                 if (mUserManager.isManagedProfile(userHandle)) {
8855                     maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin,
8856                             UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
8857                     ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
8858                             true /* newOwner */);
8859                 }
8860                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
8861                         userHandle);
8862             });
8863             mDeviceAdminServiceController.startServiceForOwner(
8864                     who.getPackageName(), userHandle, "set-profile-owner");
8865             return true;
8866         }
8867     }
8868 
8869     private void toggleBackupServiceActive(int userId, boolean makeActive) {
8870         long ident = mInjector.binderClearCallingIdentity();
8871         try {
8872             if (mInjector.getIBackupManager() != null) {
8873                 mInjector.getIBackupManager()
8874                         .setBackupServiceActive(userId, makeActive);
8875             }
8876         } catch (RemoteException e) {
8877             throw new IllegalStateException(String.format("Failed %s backup service.",
8878                     makeActive ? "activating" : "deactivating"), e);
8879         } finally {
8880             mInjector.binderRestoreCallingIdentity(ident);
8881         }
8882 
8883     }
8884 
8885     @Override
8886     public void clearProfileOwner(ComponentName who) {
8887         if (!mHasFeature) {
8888             return;
8889         }
8890         Objects.requireNonNull(who, "ComponentName is null");
8891 
8892         final CallerIdentity caller = getCallerIdentity(who);
8893         final int userId = caller.getUserId();
8894         Preconditions.checkCallingUser(!isManagedProfile(userId));
8895 
8896         enforceUserUnlocked(userId);
8897         synchronized (getLockObject()) {
8898             // Check if this is the profile owner who is calling
8899             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
8900 
8901             mInjector.binderWithCleanCallingIdentity(() -> {
8902                 clearProfileOwnerLocked(admin, userId);
8903                 removeActiveAdminLocked(who, userId);
8904                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
8905                         userId);
8906             });
8907             Slogf.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
8908         }
8909     }
8910 
8911     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
8912         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner");
8913 
8914         if (admin != null) {
8915             admin.disableCamera = false;
8916             admin.userRestrictions = null;
8917             admin.defaultEnabledRestrictionsAlreadySet.clear();
8918         }
8919         final DevicePolicyData policyData = getUserData(userId);
8920         policyData.mCurrentInputMethodSet = false;
8921         policyData.mOwnerInstalledCaCerts.clear();
8922         saveSettingsLocked(userId);
8923         clearUserPoliciesLocked(userId);
8924         clearApplicationRestrictions(userId);
8925         mOwners.removeProfileOwner(userId);
8926         mOwners.writeProfileOwner(userId);
8927         deleteTransferOwnershipBundleLocked(userId);
8928         toggleBackupServiceActive(userId, true);
8929         applyManagedProfileRestrictionIfDeviceOwnerLocked();
8930         setNetworkLoggingActiveInternal(false);
8931     }
8932 
8933     @Override
8934     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
8935         if (!mHasFeature) {
8936             return;
8937         }
8938         Objects.requireNonNull(who, "ComponentName is null");
8939 
8940         final CallerIdentity caller = getCallerIdentity(who);
8941         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
8942                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
8943 
8944         mInjector.binderWithCleanCallingIdentity(() ->
8945                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null));
8946 
8947         DevicePolicyEventLogger
8948                 .createEvent(DevicePolicyEnums.SET_DEVICE_OWNER_LOCK_SCREEN_INFO)
8949                 .setAdmin(caller.getComponentName())
8950                 .write();
8951     }
8952 
8953     @Override
8954     public CharSequence getDeviceOwnerLockScreenInfo() {
8955         return mLockPatternUtils.getDeviceOwnerInfo();
8956     }
8957 
8958     private void clearUserPoliciesLocked(int userId) {
8959         // Reset some of the user-specific policies.
8960         final DevicePolicyData policy = getUserData(userId);
8961         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
8962         // Clear delegations.
8963         policy.mDelegationMap.clear();
8964         policy.mStatusBarDisabled = false;
8965         policy.mSecondaryLockscreenEnabled = false;
8966         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
8967         policy.mAffiliationIds.clear();
8968         policy.mLockTaskPackages.clear();
8969         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId);
8970         policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
8971         policy.mUserControlDisabledPackages.clear();
8972         saveSettingsLocked(userId);
8973 
8974         try {
8975             mIPermissionManager.updatePermissionFlagsForAllApps(
8976                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8977                     0  /* flagValues */, userId);
8978             pushUserRestrictions(userId);
8979         } catch (RemoteException re) {
8980             // Shouldn't happen.
8981         }
8982     }
8983 
8984     @Override
8985     public boolean hasUserSetupCompleted() {
8986         return hasUserSetupCompleted(mInjector.userHandleGetCallingUserId());
8987     }
8988 
8989     // This checks only if the Setup Wizard has run.  Since Wear devices pair before
8990     // completing Setup Wizard, and pairing involves transferring user data, calling
8991     // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
8992     private boolean hasUserSetupCompleted(int userHandle) {
8993         if (!mHasFeature) {
8994             return true;
8995         }
8996         return mInjector.hasUserSetupCompleted(getUserData(userHandle));
8997     }
8998 
8999     private boolean hasPaired(int userHandle) {
9000         if (!mHasFeature) {
9001             return true;
9002         }
9003         return getUserData(userHandle).mPaired;
9004     }
9005 
9006     @Override
9007     public int getUserProvisioningState() {
9008         if (!mHasFeature) {
9009             return DevicePolicyManager.STATE_USER_UNMANAGED;
9010         }
9011         final CallerIdentity caller = getCallerIdentity();
9012         Preconditions.checkCallAuthorization(canManageUsers(caller));
9013 
9014         return getUserProvisioningState(caller.getUserId());
9015     }
9016 
9017     private int getUserProvisioningState(int userHandle) {
9018         return getUserData(userHandle).mUserProvisioningState;
9019     }
9020 
9021     @Override
9022     public void setUserProvisioningState(int newState, int userHandle) {
9023         if (!mHasFeature) {
9024             logMissingFeatureAction("Cannot set provisioning state " + newState + " for user "
9025                     + userHandle);
9026             return;
9027         }
9028 
9029         final CallerIdentity caller = getCallerIdentity();
9030         if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
9031                 && getManagedUserId(userHandle) == -1
9032                 && newState != STATE_USER_UNMANAGED) {
9033             // No managed device, user or profile, so setting provisioning state makes no sense.
9034             throw new IllegalStateException("Not allowed to change provisioning state unless a "
9035                       + "device or profile owner is set.");
9036         }
9037 
9038         synchronized (getLockObject()) {
9039             boolean transitionCheckNeeded = true;
9040 
9041             // Calling identity/permission checks.
9042             if (isAdb(caller)) {
9043                 // ADB shell can only move directly from un-managed to finalized as part of directly
9044                 // setting profile-owner or device-owner.
9045                 if (getUserProvisioningState(userHandle) !=
9046                         DevicePolicyManager.STATE_USER_UNMANAGED
9047                         || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
9048                     throw new IllegalStateException("Not allowed to change provisioning state "
9049                             + "unless current provisioning state is unmanaged, and new state is "
9050                             + "finalized.");
9051                 }
9052                 transitionCheckNeeded = false;
9053             } else {
9054                 Preconditions.checkCallAuthorization(
9055                         hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
9056             }
9057 
9058             final DevicePolicyData policyData = getUserData(userHandle);
9059             if (transitionCheckNeeded) {
9060                 // Optional state transition check for non-ADB case.
9061                 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
9062             }
9063             policyData.mUserProvisioningState = newState;
9064             saveSettingsLocked(userHandle);
9065         }
9066     }
9067 
9068     private void checkUserProvisioningStateTransition(int currentState, int newState) {
9069         // Valid transitions for normal use-cases.
9070         switch (currentState) {
9071             case DevicePolicyManager.STATE_USER_UNMANAGED:
9072                 // Can move to any state from unmanaged (except itself as an edge case)..
9073                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
9074                     return;
9075                 }
9076                 break;
9077             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
9078             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
9079                 // Can only move to finalized from these states.
9080                 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
9081                     return;
9082                 }
9083                 break;
9084             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
9085                 // Current user has a managed-profile, but current user is not managed, so
9086                 // rather than moving to finalized state, go back to unmanaged once
9087                 // profile provisioning is complete.
9088                 if (newState == DevicePolicyManager.STATE_USER_PROFILE_FINALIZED) {
9089                     return;
9090                 }
9091                 break;
9092             case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
9093                 // Cannot transition out of finalized.
9094                 break;
9095             case DevicePolicyManager.STATE_USER_PROFILE_FINALIZED:
9096                 // Should only move to an unmanaged state after removing the work profile.
9097                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
9098                     return;
9099                 }
9100                 break;
9101         }
9102 
9103         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
9104         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
9105                 + "from state [" + currentState + "]");
9106     }
9107 
9108     @Override
9109     public void setProfileEnabled(ComponentName who) {
9110         if (!mHasFeature) {
9111             logMissingFeatureAction("Cannot enable profile for "
9112                     + ComponentName.flattenToShortString(who));
9113             return;
9114         }
9115         Objects.requireNonNull(who, "ComponentName is null");
9116 
9117         final CallerIdentity caller = getCallerIdentity(who);
9118         final int userId = caller.getUserId();
9119         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
9120         Preconditions.checkCallingUser(isManagedProfile(userId));
9121 
9122         synchronized (getLockObject()) {
9123             // Check if the profile is already enabled.
9124             UserInfo managedProfile = getUserInfo(userId);
9125             if (managedProfile.isEnabled()) {
9126                 Slogf.e(LOG_TAG,
9127                         "setProfileEnabled is called when the profile is already enabled");
9128                 return;
9129             }
9130             mInjector.binderWithCleanCallingIdentity(() -> {
9131                 mUserManager.setUserEnabled(userId);
9132                 UserInfo parent = mUserManager.getProfileParent(userId);
9133                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
9134                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
9135                 UserHandle parentHandle = new UserHandle(parent.id);
9136                 mLocalService.broadcastIntentToCrossProfileManifestReceiversAsUser(intent,
9137                         parentHandle, /* requiresPermission= */ true);
9138                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
9139                         Intent.FLAG_RECEIVER_FOREGROUND);
9140                 mContext.sendBroadcastAsUser(intent, parentHandle);
9141             });
9142         }
9143     }
9144 
9145     @Override
9146     public void setProfileName(ComponentName who, String profileName) {
9147         Objects.requireNonNull(who, "ComponentName is null");
9148 
9149         final CallerIdentity caller = getCallerIdentity(who);
9150         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
9151 
9152         mInjector.binderWithCleanCallingIdentity(() -> {
9153             mUserManager.setUserName(caller.getUserId(), profileName);
9154             DevicePolicyEventLogger
9155                     .createEvent(DevicePolicyEnums.SET_PROFILE_NAME)
9156                     .setAdmin(caller.getComponentName())
9157                     .write();
9158         });
9159     }
9160 
9161     @Override
9162     public ComponentName getProfileOwnerAsUser(int userId) {
9163         if (!mHasFeature) {
9164             return null;
9165         }
9166         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
9167 
9168         CallerIdentity caller = getCallerIdentity();
9169         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId)
9170                 || hasFullCrossUsersPermission(caller, userId));
9171 
9172         synchronized (getLockObject()) {
9173             return mOwners.getProfileOwnerComponent(userId);
9174         }
9175     }
9176 
9177     // Returns the active profile owner for this user or null if the current user has no
9178     // profile owner.
9179     @VisibleForTesting
9180     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
9181         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
9182         if (profileOwner == null) {
9183             return null;
9184         }
9185         DevicePolicyData policy = getUserData(userHandle);
9186         final int n = policy.mAdminList.size();
9187         for (int i = 0; i < n; i++) {
9188             ActiveAdmin admin = policy.mAdminList.get(i);
9189             if (profileOwner.equals(admin.info.getComponent())) {
9190                 return admin;
9191             }
9192         }
9193         return null;
9194     }
9195 
9196     /**
9197      * Returns the ActiveAdmin associated with the PO or DO on the given user.
9198      */
9199     private @Nullable ActiveAdmin getDeviceOrProfileOwnerAdminLocked(int userHandle) {
9200         ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
9201         if (admin == null && getDeviceOwnerUserIdUncheckedLocked() == userHandle) {
9202             admin = getDeviceOwnerAdminLocked();
9203         }
9204         return admin;
9205     }
9206 
9207     @GuardedBy("getLockObject()")
9208     ActiveAdmin getProfileOwnerOfOrganizationOwnedDeviceLocked(int userHandle) {
9209         return mInjector.binderWithCleanCallingIdentity(() -> {
9210             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
9211                 if (userInfo.isManagedProfile()) {
9212                     if (getProfileOwnerAsUser(userInfo.id) != null
9213                             && isProfileOwnerOfOrganizationOwnedDevice(userInfo.id)) {
9214                         ComponentName who = getProfileOwnerAsUser(userInfo.id);
9215                         return getActiveAdminUncheckedLocked(who, userInfo.id);
9216                     }
9217                 }
9218             }
9219             return null;
9220         });
9221     }
9222 
9223     @Override
9224     public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
9225             @NonNull UserHandle userHandle) {
9226         if (!mHasFeature) {
9227             return null;
9228         }
9229         synchronized (getLockObject()) {
9230             final ComponentName doComponent = mOwners.getDeviceOwnerComponent();
9231             final ComponentName poComponent =
9232                     mOwners.getProfileOwnerComponent(userHandle.getIdentifier());
9233             // Return test only admin if configured to do so.
9234             // TODO(b/182994391): Replace with more generic solution to override the supervision
9235             // component.
9236             if (mConstants.USE_TEST_ADMIN_AS_SUPERVISION_COMPONENT) {
9237                 if (isAdminTestOnlyLocked(doComponent, userHandle.getIdentifier())) {
9238                     return doComponent;
9239                 } else if (isAdminTestOnlyLocked(poComponent, userHandle.getIdentifier())) {
9240                     return poComponent;
9241                 }
9242             }
9243             final String supervisor = mContext.getResources().getString(
9244                     com.android.internal.R.string.config_defaultSupervisionProfileOwnerComponent);
9245             if (supervisor == null) {
9246                 return null;
9247             }
9248             final ComponentName supervisorComponent = ComponentName.unflattenFromString(supervisor);
9249             if (supervisorComponent == null) {
9250                 return null;
9251             }
9252             if (supervisorComponent.equals(doComponent) || supervisorComponent.equals(
9253                     poComponent)) {
9254                 return supervisorComponent;
9255             } else {
9256                 return null;
9257             }
9258         }
9259     }
9260 
9261     @Override
9262     public String getProfileOwnerName(int userHandle) {
9263         if (!mHasFeature) {
9264             return null;
9265         }
9266         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
9267         return getProfileOwnerNameUnchecked(userHandle);
9268     }
9269 
9270     private String getProfileOwnerNameUnchecked(int userHandle) {
9271         ComponentName profileOwner = getProfileOwnerAsUser(userHandle);
9272         if (profileOwner == null) {
9273             return null;
9274         }
9275         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
9276     }
9277 
9278     private @UserIdInt int getOrganizationOwnedProfileUserId() {
9279         for (UserInfo ui : mUserManagerInternal.getUserInfos()) {
9280             if (ui.isManagedProfile() && isProfileOwnerOfOrganizationOwnedDevice(ui.id)) {
9281                 return ui.id;
9282             }
9283         }
9284         return UserHandle.USER_NULL;
9285     }
9286 
9287     @Override
9288     public boolean isOrganizationOwnedDeviceWithManagedProfile() {
9289         if (!mHasFeature) {
9290             return false;
9291         }
9292         return getOrganizationOwnedProfileUserId() != UserHandle.USER_NULL;
9293     }
9294 
9295     @Override
9296     public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) {
9297         final CallerIdentity caller = getCallerIdentity();
9298         ensureCallerIdentityMatchesIfNotSystem(packageName, pid, uid, caller);
9299 
9300         // Verify that the specified packages matches the provided uid.
9301         if (!doesPackageMatchUid(packageName, uid)) {
9302             return false;
9303         }
9304         // A device or profile owner must also have the READ_PHONE_STATE permission to access device
9305         // identifiers. If the package being checked does not have this permission then deny access.
9306         if (!hasPermission(permission.READ_PHONE_STATE, pid, uid)) {
9307             return false;
9308         }
9309 
9310         // Allow access to the device owner or delegate cert installer.
9311         ComponentName deviceOwner = getDeviceOwnerComponent(true);
9312         if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName)
9313                     || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) {
9314             return true;
9315         }
9316         final int userId = UserHandle.getUserId(uid);
9317         // Allow access to the profile owner for the specified user, or delegate cert installer
9318         // But only if this is an organization-owned device.
9319         ComponentName profileOwner = getProfileOwnerAsUser(userId);
9320         final boolean isCallerProfileOwnerOrDelegate = profileOwner != null
9321                 && (profileOwner.getPackageName().equals(packageName)
9322                         || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL));
9323         if (isCallerProfileOwnerOrDelegate && isProfileOwnerOfOrganizationOwnedDevice(userId)) {
9324             return true;
9325         }
9326 
9327         return false;
9328     }
9329 
9330     private boolean doesPackageMatchUid(String packageName, int uid) {
9331         final int userId = UserHandle.getUserId(uid);
9332         try {
9333             ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(packageName, 0, userId);
9334             // Since this call goes directly to PackageManagerService a NameNotFoundException is not
9335             // thrown but null data can be returned; if the appInfo for the specified package cannot
9336             // be found then return false to prevent crashing the app.
9337             if (appInfo == null) {
9338                 Slogf.w(LOG_TAG, "appInfo could not be found for package %s", packageName);
9339                 return false;
9340             } else if (uid != appInfo.uid) {
9341                 String message = String.format("Package %s (uid=%d) does not match provided uid %d",
9342                         packageName, appInfo.uid, uid);
9343                 Slogf.w(LOG_TAG, message);
9344                 throw new SecurityException(message);
9345             }
9346         } catch (RemoteException e) {
9347             // If an exception is caught obtaining the appInfo just return false to prevent crashing
9348             // apps due to an internal error.
9349             Slogf.e(LOG_TAG, e, "Exception caught obtaining appInfo for package %s", packageName);
9350             return false;
9351         }
9352         return true;
9353     }
9354 
9355     private void ensureCallerIdentityMatchesIfNotSystem(String packageName, int pid, int uid,
9356             CallerIdentity caller) {
9357         // If the caller is not a system app then it should only be able to check its own device
9358         // identifier access.
9359         int callingUid = caller.getUid();
9360         int callingPid = mInjector.binderGetCallingPid();
9361         if (UserHandle.getAppId(callingUid) >= Process.FIRST_APPLICATION_UID
9362                 && (callingUid != uid || callingPid != pid)) {
9363             String message = String.format(
9364                     "Calling uid %d, pid %d cannot check device identifier access for package %s "
9365                             + "(uid=%d, pid=%d)", callingUid, callingPid, packageName, uid, pid);
9366             Slogf.w(LOG_TAG, message);
9367             throw new SecurityException(message);
9368         }
9369     }
9370 
9371     /**
9372      * Canonical name for a given package.
9373      */
9374     private String getApplicationLabel(String packageName, @UserIdInt int userId) {
9375         return mInjector.binderWithCleanCallingIdentity(() -> {
9376             final Context userContext;
9377             try {
9378                 UserHandle userHandle = UserHandle.of(userId);
9379                 userContext = mContext.createPackageContextAsUser(packageName, /* flags= */ 0,
9380                         userHandle);
9381             } catch (PackageManager.NameNotFoundException nnfe) {
9382                 Slogf.w(LOG_TAG, nnfe, "%s is not installed for user %d", packageName, userId);
9383                 return null;
9384             }
9385             ApplicationInfo appInfo = userContext.getApplicationInfo();
9386             CharSequence result = null;
9387             if (appInfo != null) {
9388                 result = appInfo.loadUnsafeLabel(userContext.getPackageManager());
9389             }
9390             return result != null ? result.toString() : null;
9391         });
9392     }
9393 
9394     /**
9395      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
9396      * permission.
9397      * The profile owner can only be set before the user setup phase has completed,
9398      * except for:
9399      * - SYSTEM_UID
9400      * - adb unless hasIncompatibleAccountsOrNonAdb is true.
9401      */
9402     private void enforceCanSetProfileOwnerLocked(
9403             CallerIdentity caller, @Nullable ComponentName owner, int userHandle,
9404             boolean hasIncompatibleAccountsOrNonAdb) {
9405         UserInfo info = getUserInfo(userHandle);
9406         if (info == null) {
9407             // User doesn't exist.
9408             throw new IllegalArgumentException(
9409                     "Attempted to set profile owner for invalid userId: " + userHandle);
9410         }
9411         if (info.isGuest()) {
9412             throw new IllegalStateException("Cannot set a profile owner on a guest");
9413         }
9414         if (mOwners.hasProfileOwner(userHandle)) {
9415             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
9416                     + "is already set.");
9417         }
9418         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
9419             throw new IllegalStateException("Trying to set the profile owner, but the user "
9420                     + "already has a device owner.");
9421         }
9422         if (isAdb(caller)) {
9423             if ((mIsWatch || hasUserSetupCompleted(userHandle))
9424                     && hasIncompatibleAccountsOrNonAdb) {
9425                 throw new IllegalStateException("Not allowed to set the profile owner because "
9426                         + "there are already some accounts on the profile");
9427             }
9428             return;
9429         }
9430         Preconditions.checkCallAuthorization(
9431                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
9432 
9433         if ((mIsWatch || hasUserSetupCompleted(userHandle))) {
9434             Preconditions.checkState(isSystemUid(caller),
9435                     "Cannot set the profile owner on a user which is already set-up");
9436 
9437             if (!mIsWatch) {
9438                 // Only the default supervision profile owner can be set as profile owner after SUW
9439                 final String supervisor = mContext.getResources().getString(
9440                         com.android.internal.R.string
9441                                 .config_defaultSupervisionProfileOwnerComponent);
9442                 if (supervisor == null) {
9443                     throw new IllegalStateException("Unable to set profile owner post-setup, no"
9444                             + "default supervisor profile owner defined");
9445                 }
9446 
9447                 final ComponentName supervisorComponent = ComponentName.unflattenFromString(
9448                         supervisor);
9449                 if (!owner.equals(supervisorComponent)) {
9450                     throw new IllegalStateException("Unable to set non-default profile owner"
9451                             + " post-setup " + owner);
9452                 }
9453             }
9454         }
9455     }
9456 
9457     /**
9458      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
9459      * permission.
9460      */
9461     private void enforceCanSetDeviceOwnerLocked(
9462             CallerIdentity caller, @Nullable ComponentName owner, @UserIdInt int deviceOwnerUserId,
9463             boolean hasIncompatibleAccountsOrNonAdb) {
9464         if (!isAdb(caller)) {
9465             Preconditions.checkCallAuthorization(
9466                     hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
9467         }
9468 
9469         final int code = checkDeviceOwnerProvisioningPreConditionLocked(owner,
9470                 /* deviceOwnerUserId= */ deviceOwnerUserId, /* callingUserId*/ caller.getUserId(),
9471                 isAdb(caller), hasIncompatibleAccountsOrNonAdb);
9472         if (code != CODE_OK) {
9473             throw new IllegalStateException(
9474                     computeProvisioningErrorString(code, deviceOwnerUserId));
9475         }
9476     }
9477 
9478     private static String computeProvisioningErrorString(int code, @UserIdInt int userId) {
9479         switch (code) {
9480             case CODE_OK:
9481                 return "OK";
9482             case CODE_HAS_DEVICE_OWNER:
9483                 return "Trying to set the device owner, but device owner is already set.";
9484             case CODE_USER_HAS_PROFILE_OWNER:
9485                 return "Trying to set the device owner, but the user already has a profile owner.";
9486             case CODE_USER_NOT_RUNNING:
9487                 return "User " + userId + " not running.";
9488             case CODE_NOT_SYSTEM_USER:
9489                 return "User " + userId + " is not system user.";
9490             case CODE_USER_SETUP_COMPLETED:
9491                 return  "Cannot set the device owner if the device is already set-up.";
9492             case CODE_NONSYSTEM_USER_EXISTS:
9493                 return "Not allowed to set the device owner because there are already several"
9494                         + " users on the device.";
9495             case CODE_ACCOUNTS_NOT_EMPTY:
9496                 return "Not allowed to set the device owner because there are already some accounts"
9497                         + " on the device.";
9498             case CODE_HAS_PAIRED:
9499                 return "Not allowed to set the device owner because this device has already "
9500                         + "paired.";
9501             default:
9502                 return "Unexpected @ProvisioningPreCondition: " + code;
9503         }
9504 
9505     }
9506 
9507     private void enforceUserUnlocked(int userId) {
9508         // Since we're doing this operation on behalf of an app, we only
9509         // want to use the actual "unlocked" state.
9510         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
9511                 "User must be running and unlocked");
9512     }
9513 
9514     private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
9515         if (parent) {
9516             enforceUserUnlocked(getProfileParentId(userId));
9517         } else {
9518             enforceUserUnlocked(userId);
9519         }
9520     }
9521 
9522     private boolean canManageUsers(CallerIdentity caller) {
9523         return isSystemUid(caller) || isRootUid(caller)
9524                 || hasCallingOrSelfPermission(permission.MANAGE_USERS);
9525     }
9526 
9527     private boolean hasPermission(String permission, int pid, int uid) {
9528         return mContext.checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED;
9529     }
9530 
9531     private boolean hasCallingPermission(String permission) {
9532         return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED;
9533     }
9534 
9535     private boolean hasCallingOrSelfPermission(String permission) {
9536         return mContext.checkCallingOrSelfPermission(permission)
9537                 == PackageManager.PERMISSION_GRANTED;
9538     }
9539 
9540     private boolean hasPermissionForPreflight(CallerIdentity caller, String permission) {
9541         final int callingPid = mInjector.binderGetCallingPid();
9542         final String packageName = mContext.getPackageName();
9543 
9544         return PermissionChecker.checkPermissionForPreflight(mContext, permission, callingPid,
9545                 caller.getUid(), packageName) == PermissionChecker.PERMISSION_GRANTED;
9546     }
9547 
9548     private boolean hasFullCrossUsersPermission(CallerIdentity caller, int userHandle) {
9549         return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller)
9550                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL);
9551     }
9552 
9553     private boolean hasCrossUsersPermission(CallerIdentity caller, int userHandle) {
9554         return (userHandle == caller.getUserId()) || isSystemUid(caller) || isRootUid(caller)
9555                 || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS);
9556     }
9557 
9558     private boolean canUserUseLockTaskLocked(int userId) {
9559         if (isUserAffiliatedWithDeviceLocked(userId)) {
9560             return true;
9561         }
9562 
9563         // Unaffiliated profile owners are not allowed to use lock when there is a device owner.
9564         if (mOwners.hasDeviceOwner()) {
9565             return false;
9566         }
9567 
9568         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
9569         if (profileOwner == null) {
9570             return false;
9571         }
9572 
9573         // Managed profiles are not allowed to use lock task
9574         if (isManagedProfile(userId)) {
9575             return false;
9576         }
9577 
9578         return true;
9579     }
9580 
9581     private void enforceCanCallLockTaskLocked(CallerIdentity caller) {
9582         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
9583 
9584         final int userId =  caller.getUserId();
9585         if (!canUserUseLockTaskLocked(userId)) {
9586             throw new SecurityException("User " + userId + " is not allowed to use lock task");
9587         }
9588     }
9589 
9590     private boolean isSystemUid(CallerIdentity caller) {
9591         return UserHandle.isSameApp(caller.getUid(), Process.SYSTEM_UID);
9592     }
9593 
9594     private boolean isRootUid(CallerIdentity caller) {
9595         return UserHandle.isSameApp(caller.getUid(), Process.ROOT_UID);
9596     }
9597 
9598     private boolean isShellUid(CallerIdentity caller) {
9599         return UserHandle.isSameApp(caller.getUid(), Process.SHELL_UID);
9600     }
9601 
9602     private @UserIdInt int getCurrentForegroundUserId() {
9603         try {
9604             UserInfo currentUser = mInjector.getIActivityManager().getCurrentUser();
9605             if (currentUser == null) {
9606                 // TODO(b/206107460): should not happen on production, but it's happening on unit
9607                 // tests that are not properly setting the expectation (because they don't need it)
9608                 Slogf.wtf(LOG_TAG, "getCurrentForegroundUserId(): mInjector.getIActivityManager()"
9609                         + ".getCurrentUser() returned null, please ignore when running unit tests");
9610                 return ActivityManager.getCurrentUser();
9611             }
9612             return currentUser.id;
9613         } catch (RemoteException e) {
9614             Slogf.wtf(LOG_TAG, "cannot get current user");
9615         }
9616         return UserHandle.USER_NULL;
9617     }
9618 
9619     @Override
9620     public List<UserHandle> listForegroundAffiliatedUsers() {
9621         checkIsDeviceOwner(getCallerIdentity());
9622 
9623         return mInjector.binderWithCleanCallingIdentity(() -> {
9624             int userId = getCurrentForegroundUserId();
9625             boolean isAffiliated;
9626             synchronized (getLockObject()) {
9627                 isAffiliated = isUserAffiliatedWithDeviceLocked(userId);
9628             }
9629 
9630             if (!isAffiliated) return Collections.emptyList();
9631 
9632             List<UserHandle> users = new ArrayList<>(1);
9633             users.add(UserHandle.of(userId));
9634 
9635             return users;
9636         });
9637     }
9638 
9639     protected int getProfileParentId(int userHandle) {
9640         return mInjector.binderWithCleanCallingIdentity(() -> {
9641             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
9642             return parentUser != null ? parentUser.id : userHandle;
9643         });
9644     }
9645 
9646     private int getProfileParentUserIfRequested(int userHandle, boolean parent) {
9647         if (parent) {
9648             return getProfileParentId(userHandle);
9649         }
9650 
9651         return userHandle;
9652     }
9653 
9654     private int getCredentialOwner(final int userHandle, final boolean parent) {
9655         return mInjector.binderWithCleanCallingIdentity(() -> {
9656             int effectiveUserHandle = userHandle;
9657             if (parent) {
9658                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
9659                 if (parentProfile != null) {
9660                     effectiveUserHandle = parentProfile.id;
9661                 }
9662             }
9663             return mUserManager.getCredentialOwnerProfile(effectiveUserHandle);
9664         });
9665     }
9666 
9667     private boolean isManagedProfile(int userHandle) {
9668         final UserInfo user = getUserInfo(userHandle);
9669         return user != null && user.isManagedProfile();
9670     }
9671 
9672     private void enableIfNecessary(String packageName, int userId) {
9673         try {
9674             final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
9675                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
9676             if (ai.enabledSetting
9677                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
9678                 mIPackageManager.setApplicationEnabledSetting(packageName,
9679                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
9680                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
9681             }
9682         } catch (RemoteException e) {
9683         }
9684     }
9685 
9686     private void dumpPerUserData(IndentingPrintWriter pw) {
9687         int userCount = mUserData.size();
9688         for (int i = 0; i < userCount; i++) {
9689             int userId = mUserData.keyAt(i);
9690             DevicePolicyData policy = getUserData(userId);
9691             policy.dump(pw);
9692             pw.println();
9693 
9694             if (userId == UserHandle.USER_SYSTEM) {
9695                 pw.increaseIndent();
9696                 PersonalAppsSuspensionHelper.forUser(mContext, userId).dump(pw);
9697                 pw.decreaseIndent();
9698                 pw.println();
9699             } else {
9700                 // pm.getUnsuspendablePackages() will fail if it's called for a different user;
9701                 // as this dump is mostly useful for system user anyways, we can just ignore the
9702                 // others (rather than changing the permission check in the PM method)
9703                 Slogf.d(LOG_TAG, "skipping PersonalAppsSuspensionHelper.dump() for user " + userId);
9704             }
9705         }
9706     }
9707 
9708     @Override
9709     protected void dump(FileDescriptor fd, PrintWriter printWriter, String[] args) {
9710         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, printWriter)) return;
9711 
9712         try (IndentingPrintWriter pw = new IndentingPrintWriter(printWriter, "  ")) {
9713             pw.println("Current Device Policy Manager state:");
9714             pw.increaseIndent();
9715 
9716             dumpImmutableState(pw);
9717             synchronized (getLockObject()) {
9718                 mOwners.dump(pw);
9719                 pw.println();
9720                 mDeviceAdminServiceController.dump(pw);
9721                 pw.println();
9722                 dumpPerUserData(pw);
9723                 pw.println();
9724                 mConstants.dump(pw);
9725                 pw.println();
9726                 mStatLogger.dump(pw);
9727                 pw.println();
9728                 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
9729                 pw.println("Logout user: " + getLogoutUserIdUnchecked());
9730                 pw.println();
9731 
9732                 if (mPendingUserCreatedCallbackTokens.isEmpty()) {
9733                     pw.println("no pending user created callback tokens");
9734                 } else {
9735                     int size = mPendingUserCreatedCallbackTokens.size();
9736                     pw.printf("%d pending user created callback token%s\n", size,
9737                             (size == 1 ? "" : "s"));
9738                 }
9739                 pw.println();
9740 
9741                 mPolicyCache.dump(pw);
9742                 pw.println();
9743                 mStateCache.dump(pw);
9744                 pw.println();
9745             }
9746             mHandler.post(() -> handleDump(pw));
9747             dumpResources(pw);
9748         }
9749     }
9750 
9751     // Dump state that is guarded by the handler
9752     private void handleDump(IndentingPrintWriter pw) {
9753         if (mNetworkLoggingNotificationUserId != UserHandle.USER_NULL) {
9754             pw.println("mNetworkLoggingNotificationUserId:  " + mNetworkLoggingNotificationUserId);
9755         }
9756     }
9757 
9758     private void dumpImmutableState(IndentingPrintWriter pw) {
9759         pw.println("Immutable state:");
9760         pw.increaseIndent();
9761         pw.printf("mHasFeature=%b\n", mHasFeature);
9762         pw.printf("mIsWatch=%b\n", mIsWatch);
9763         pw.printf("mIsAutomotive=%b\n", mIsAutomotive);
9764         pw.printf("mHasTelephonyFeature=%b\n", mHasTelephonyFeature);
9765         pw.printf("mSafetyChecker=%s\n", mSafetyChecker);
9766         pw.decreaseIndent();
9767     }
9768 
9769     private void dumpResources(IndentingPrintWriter pw) {
9770         mOverlayPackagesProvider.dump(pw);
9771         pw.println();
9772 
9773         pw.println("Other overlayable app resources");
9774         pw.increaseIndent();
9775         dumpResources(pw, mContext, "cross_profile_apps", R.array.cross_profile_apps);
9776         dumpResources(pw, mContext, "vendor_cross_profile_apps", R.array.vendor_cross_profile_apps);
9777         dumpResources(pw, mContext, "config_packagesExemptFromSuspension",
9778                 R.array.config_packagesExemptFromSuspension);
9779         dumpResources(pw, mContext, "policy_exempt_apps", R.array.policy_exempt_apps);
9780         dumpResources(pw, mContext, "vendor_policy_exempt_apps", R.array.vendor_policy_exempt_apps);
9781         pw.decreaseIndent();
9782         pw.println();
9783     }
9784 
9785     static void dumpResources(IndentingPrintWriter pw, Context context, String resName, int resId) {
9786         dumpApps(pw, resName, context.getResources().getStringArray(resId));
9787     }
9788 
9789     static void dumpApps(IndentingPrintWriter pw, String name, String[] apps) {
9790         dumpApps(pw, name, Arrays.asList(apps));
9791     }
9792 
9793     static void dumpApps(IndentingPrintWriter pw, String name, List apps) {
9794         if (apps == null || apps.isEmpty()) {
9795             pw.printf("%s: empty\n", name);
9796             return;
9797         }
9798         int size = apps.size();
9799         pw.printf("%s: %d app%s\n", name, size, size == 1 ? "" : "s");
9800         pw.increaseIndent();
9801         for (int i = 0; i < size; i++) {
9802             pw.printf("%d: %s\n", i, apps.get(i));
9803         }
9804         pw.decreaseIndent();
9805     }
9806 
9807     @Override
9808     public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
9809             String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
9810         new DevicePolicyManagerServiceShellCommand(DevicePolicyManagerService.this).exec(
9811                 this, in, out, err, args, callback, resultReceiver);
9812 
9813     }
9814 
9815     private String getEncryptionStatusName(int encryptionStatus) {
9816         switch (encryptionStatus) {
9817             case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
9818                 return "inactive";
9819             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
9820                 return "block default key";
9821             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
9822                 return "block";
9823             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
9824                 return "per-user";
9825             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
9826                 return "unsupported";
9827             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
9828                 return "activating";
9829             default:
9830                 return "unknown";
9831         }
9832     }
9833 
9834     @Override
9835     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
9836             ComponentName activity) {
9837         Objects.requireNonNull(who, "ComponentName is null");
9838         final CallerIdentity caller = getCallerIdentity(who);
9839         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
9840 
9841         final int userHandle = caller.getUserId();
9842         synchronized (getLockObject()) {
9843             long id = mInjector.binderClearCallingIdentity();
9844             try {
9845                 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
9846                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
9847             } catch (RemoteException re) {
9848                 // Shouldn't happen
9849             } finally {
9850                 mInjector.binderRestoreCallingIdentity(id);
9851             }
9852         }
9853         final String activityPackage =
9854                 (activity != null ? activity.getPackageName() : null);
9855         DevicePolicyEventLogger
9856                 .createEvent(DevicePolicyEnums.ADD_PERSISTENT_PREFERRED_ACTIVITY)
9857                 .setAdmin(who)
9858                 .setStrings(activityPackage, getIntentFilterActions(filter))
9859                 .write();
9860     }
9861 
9862     @Override
9863     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
9864         Objects.requireNonNull(who, "ComponentName is null");
9865         final CallerIdentity caller = getCallerIdentity(who);
9866         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
9867 
9868         final int userHandle = caller.getUserId();
9869         synchronized (getLockObject()) {
9870             long id = mInjector.binderClearCallingIdentity();
9871             try {
9872                 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
9873                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
9874             } catch (RemoteException re) {
9875                 // Shouldn't happen
9876             } finally {
9877                 mInjector.binderRestoreCallingIdentity(id);
9878             }
9879         }
9880     }
9881 
9882     @Override
9883     public void setDefaultSmsApplication(ComponentName admin, String packageName, boolean parent) {
9884         Objects.requireNonNull(admin, "ComponentName is null");
9885 
9886         final CallerIdentity caller = getCallerIdentity(admin);
9887         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
9888                 || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)));
9889         if (parent) {
9890             mInjector.binderWithCleanCallingIdentity(() -> enforcePackageIsSystemPackage(
9891                     packageName, getProfileParentId(mInjector.userHandleGetCallingUserId())));
9892         }
9893 
9894         mInjector.binderWithCleanCallingIdentity(() ->
9895                 SmsApplication.setDefaultApplication(packageName, mContext));
9896     }
9897 
9898     @Override
9899     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
9900             String packageName) {
9901         try {
9902             setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
9903         } catch (IllegalArgumentException e) {
9904             return false;
9905         }
9906         return true;
9907     }
9908 
9909     @Override
9910     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
9911         final List<String> delegatePackages = getDelegatePackages(admin,
9912                 DELEGATION_APP_RESTRICTIONS);
9913         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
9914     }
9915 
9916     @Override
9917     public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
9918         return isCallerDelegate(callerPackage, getCallerIdentity().getUid(),
9919                 DELEGATION_APP_RESTRICTIONS);
9920     }
9921 
9922     @Override
9923     public void setApplicationRestrictions(ComponentName who, String callerPackage,
9924             String packageName, Bundle settings) {
9925         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
9926         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
9927                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
9928                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS)));
9929         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_RESTRICTIONS);
9930 
9931         mInjector.binderWithCleanCallingIdentity(() -> {
9932             mUserManager.setApplicationRestrictions(packageName, settings,
9933                     caller.getUserHandle());
9934             DevicePolicyEventLogger
9935                     .createEvent(DevicePolicyEnums.SET_APPLICATION_RESTRICTIONS)
9936                     .setAdmin(caller.getPackageName())
9937                     .setBoolean(/* isDelegate */ who == null)
9938                     .setStrings(packageName)
9939                     .write();
9940         });
9941     }
9942 
9943     @Override
9944     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
9945             PersistableBundle args, boolean parent) {
9946         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
9947             return;
9948         }
9949         Objects.requireNonNull(admin, "admin is null");
9950         Objects.requireNonNull(agent, "agent is null");
9951         final int userHandle = UserHandle.getCallingUserId();
9952         synchronized (getLockObject()) {
9953             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
9954                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
9955             checkCanExecuteOrThrowUnsafe(
9956                     DevicePolicyManager.OPERATION_SET_TRUST_AGENT_CONFIGURATION);
9957 
9958             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
9959             saveSettingsLocked(userHandle);
9960         }
9961     }
9962 
9963     @Override
9964     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
9965             ComponentName agent, int userHandle, boolean parent) {
9966         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
9967             return null;
9968         }
9969         Objects.requireNonNull(agent, "agent null");
9970         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
9971 
9972         final CallerIdentity caller = getCallerIdentity(admin);
9973         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
9974 
9975         synchronized (getLockObject()) {
9976             final String componentName = agent.flattenToString();
9977             if (admin != null) {
9978                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
9979                 if (ap == null) return null;
9980                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
9981                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
9982                 List<PersistableBundle> result = new ArrayList<>();
9983                 result.add(trustAgentInfo.options);
9984                 return result;
9985             }
9986 
9987             // Return strictest policy for this user and profiles that are visible from this user.
9988             List<PersistableBundle> result = null;
9989             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
9990             // of the options. If any admin doesn't have options, discard options for the rest
9991             // and return null.
9992             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
9993                     getProfileParentUserIfRequested(userHandle, parent));
9994             boolean allAdminsHaveOptions = true;
9995             final int N = admins.size();
9996             for (int i = 0; i < N; i++) {
9997                 final ActiveAdmin active = admins.get(i);
9998 
9999                 final boolean disablesTrust = (active.disabledKeyguardFeatures
10000                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
10001                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
10002                 if (info != null && info.options != null && !info.options.isEmpty()) {
10003                     if (disablesTrust) {
10004                         if (result == null) {
10005                             result = new ArrayList<>();
10006                         }
10007                         result.add(info.options);
10008                     } else {
10009                         Slogf.w(LOG_TAG, "Ignoring admin %s because it has trust options but "
10010                                 + "doesn't declare KEYGUARD_DISABLE_TRUST_AGENTS", active.info);
10011                     }
10012                 } else if (disablesTrust) {
10013                     allAdminsHaveOptions = false;
10014                     break;
10015                 }
10016             }
10017             return allAdminsHaveOptions ? result : null;
10018         }
10019     }
10020 
10021     @Override
10022     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
10023         Objects.requireNonNull(who, "ComponentName is null");
10024         final CallerIdentity caller = getCallerIdentity(who);
10025         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
10026         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_RESTRICTIONS_PROVIDER);
10027 
10028         synchronized (getLockObject()) {
10029             int userHandle = caller.getUserId();
10030             DevicePolicyData userData = getUserData(userHandle);
10031             userData.mRestrictionsProvider = permissionProvider;
10032             saveSettingsLocked(userHandle);
10033         }
10034     }
10035 
10036     @Override
10037     public ComponentName getRestrictionsProvider(int userHandle) {
10038         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
10039                 String.format(NOT_SYSTEM_CALLER_MSG, "query the permission provider"));
10040         synchronized (getLockObject()) {
10041             DevicePolicyData userData = getUserData(userHandle);
10042             return userData != null ? userData.mRestrictionsProvider : null;
10043         }
10044     }
10045 
10046     @Override
10047     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
10048         Objects.requireNonNull(who, "ComponentName is null");
10049         final CallerIdentity caller = getCallerIdentity(who);
10050         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
10051         int callingUserId = caller.getUserId();
10052         synchronized (getLockObject()) {
10053             long id = mInjector.binderClearCallingIdentity();
10054             try {
10055                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
10056                 if (parent == null) {
10057                     Slogf.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
10058                             + "parent");
10059                     return;
10060                 }
10061                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
10062                     mIPackageManager.addCrossProfileIntentFilter(
10063                             filter, who.getPackageName(), callingUserId, parent.id, 0);
10064                 }
10065                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
10066                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
10067                             parent.id, callingUserId, 0);
10068                 }
10069             } catch (RemoteException re) {
10070                 // Shouldn't happen
10071             } finally {
10072                 mInjector.binderRestoreCallingIdentity(id);
10073             }
10074         }
10075         DevicePolicyEventLogger
10076                 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_INTENT_FILTER)
10077                 .setAdmin(who)
10078                 .setStrings(getIntentFilterActions(filter))
10079                 .setInt(flags)
10080                 .write();
10081     }
10082 
10083     private static String[] getIntentFilterActions(IntentFilter filter) {
10084         if (filter == null) {
10085             return null;
10086         }
10087         final int actionsCount = filter.countActions();
10088         final String[] actions = new String[actionsCount];
10089         for (int i = 0; i < actionsCount; i++) {
10090             actions[i] = filter.getAction(i);
10091         }
10092         return actions;
10093     }
10094 
10095     @Override
10096     public void clearCrossProfileIntentFilters(ComponentName who) {
10097         Objects.requireNonNull(who, "ComponentName is null");
10098         final CallerIdentity caller = getCallerIdentity(who);
10099         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
10100 
10101         int callingUserId = caller.getUserId();
10102         synchronized (getLockObject()) {
10103             long id = mInjector.binderClearCallingIdentity();
10104             try {
10105                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
10106                 if (parent == null) {
10107                     Slogf.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
10108                             + "parent");
10109                     return;
10110                 }
10111                 // Removing those that go from the managed profile to the parent.
10112                 mIPackageManager.clearCrossProfileIntentFilters(
10113                         callingUserId, who.getPackageName());
10114                 // And those that go from the parent to the managed profile.
10115                 // If we want to support multiple managed profiles, we will have to only remove
10116                 // those that have callingUserId as their target.
10117                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
10118             } catch (RemoteException re) {
10119                 // Shouldn't happen
10120             } finally {
10121                 mInjector.binderRestoreCallingIdentity(id);
10122             }
10123         }
10124     }
10125 
10126     /**
10127      * @return true if all packages in enabledPackages are either in the list
10128      * permittedList or are a system app.
10129      */
10130     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
10131             List<String> permittedList, int userIdToCheck) {
10132         long id = mInjector.binderClearCallingIdentity();
10133         try {
10134             // If we have an enabled packages list for a managed profile the packages
10135             // we should check are installed for the parent user.
10136             UserInfo user = getUserInfo(userIdToCheck);
10137             if (user.isManagedProfile()) {
10138                 userIdToCheck = user.profileGroupId;
10139             }
10140 
10141             for (String enabledPackage : enabledPackages) {
10142                 boolean systemService = false;
10143                 try {
10144                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
10145                             enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
10146                             userIdToCheck);
10147                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10148                 } catch (RemoteException e) {
10149                     Slogf.i(LOG_TAG, "Can't talk to package managed", e);
10150                 }
10151                 if (!systemService && !permittedList.contains(enabledPackage)) {
10152                     return false;
10153                 }
10154             }
10155         } finally {
10156             mInjector.binderRestoreCallingIdentity(id);
10157         }
10158         return true;
10159     }
10160 
10161     /**
10162      * Invoke a method in AccessibilityManager ensuring the client is removed.
10163      */
10164     private <T> T withAccessibilityManager(
10165             int userId, Function<AccessibilityManager, T> function) {
10166         // Not using AccessibilityManager.getInstance because that guesses
10167         // at the user you require based on callingUid and caches for a given
10168         // process.
10169         final IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
10170         final IAccessibilityManager service = iBinder == null
10171                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
10172         final AccessibilityManager am = new AccessibilityManager(mContext, service, userId);
10173         try {
10174             return function.apply(am);
10175         } finally {
10176             am.removeClient();
10177         }
10178     }
10179 
10180     @Override
10181     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
10182         if (!mHasFeature) {
10183             return false;
10184         }
10185         Objects.requireNonNull(who, "ComponentName is null");
10186         final CallerIdentity caller = getCallerIdentity(who);
10187 
10188         if (packageList != null) {
10189             int userId = caller.getUserId();
10190             final List<AccessibilityServiceInfo> enabledServices;
10191             long id = mInjector.binderClearCallingIdentity();
10192             try {
10193                 UserInfo user = getUserInfo(userId);
10194                 if (user.isManagedProfile()) {
10195                     userId = user.profileGroupId;
10196                 }
10197                 enabledServices = withAccessibilityManager(userId,
10198                         am -> am.getEnabledAccessibilityServiceList(FEEDBACK_ALL_MASK));
10199             } finally {
10200                 mInjector.binderRestoreCallingIdentity(id);
10201             }
10202 
10203             if (enabledServices != null) {
10204                 List<String> enabledPackages = new ArrayList<>();
10205                 for (AccessibilityServiceInfo service : enabledServices) {
10206                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
10207                 }
10208                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
10209                         userId)) {
10210                     Slogf.e(LOG_TAG, "Cannot set permitted accessibility services, "
10211                             + "because it contains already enabled accesibility services.");
10212                     return false;
10213                 }
10214             }
10215         }
10216 
10217         synchronized (getLockObject()) {
10218             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
10219             admin.permittedAccessiblityServices = packageList;
10220             saveSettingsLocked(UserHandle.getCallingUserId());
10221         }
10222         final String[] packageArray =
10223                 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null;
10224         DevicePolicyEventLogger
10225                 .createEvent(DevicePolicyEnums.SET_PERMITTED_ACCESSIBILITY_SERVICES)
10226                 .setAdmin(who)
10227                 .setStrings(packageArray)
10228                 .write();
10229         return true;
10230     }
10231 
10232     @Override
10233     public List getPermittedAccessibilityServices(ComponentName who) {
10234         if (!mHasFeature) {
10235             return null;
10236         }
10237         Objects.requireNonNull(who, "ComponentName is null");
10238         final CallerIdentity caller = getCallerIdentity(who);
10239         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
10240 
10241         synchronized (getLockObject()) {
10242             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
10243             return admin.permittedAccessiblityServices;
10244         }
10245     }
10246 
10247     @Override
10248     public List getPermittedAccessibilityServicesForUser(int userId) {
10249         if (!mHasFeature) {
10250             return null;
10251         }
10252         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
10253 
10254         synchronized (getLockObject()) {
10255             List<String> result = null;
10256             // If we have multiple profiles we return the intersection of the
10257             // permitted lists. This can happen in cases where we have a device
10258             // and profile owner.
10259             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
10260             for (int profileId : profileIds) {
10261                 // Just loop though all admins, only device or profiles
10262                 // owners can have permitted lists set.
10263                 DevicePolicyData policy = getUserDataUnchecked(profileId);
10264                 final int N = policy.mAdminList.size();
10265                 for (int j = 0; j < N; j++) {
10266                     ActiveAdmin admin = policy.mAdminList.get(j);
10267                     List<String> fromAdmin = admin.permittedAccessiblityServices;
10268                     if (fromAdmin != null) {
10269                         if (result == null) {
10270                             result = new ArrayList<>(fromAdmin);
10271                         } else {
10272                             result.retainAll(fromAdmin);
10273                         }
10274                     }
10275                 }
10276             }
10277 
10278             // If we have a permitted list add all system accessibility services.
10279             if (result != null) {
10280                 long id = mInjector.binderClearCallingIdentity();
10281                 try {
10282                     UserInfo user = getUserInfo(userId);
10283                     if (user.isManagedProfile()) {
10284                         userId = user.profileGroupId;
10285                     }
10286                     final List<AccessibilityServiceInfo> installedServices =
10287                             withAccessibilityManager(userId,
10288                                     AccessibilityManager::getInstalledAccessibilityServiceList);
10289 
10290                     if (installedServices != null) {
10291                         for (AccessibilityServiceInfo service : installedServices) {
10292                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
10293                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
10294                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10295                                 result.add(serviceInfo.packageName);
10296                             }
10297                         }
10298                     }
10299                 } finally {
10300                     mInjector.binderRestoreCallingIdentity(id);
10301                 }
10302             }
10303 
10304             return result;
10305         }
10306     }
10307 
10308     @Override
10309     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
10310             int userHandle) {
10311         if (!mHasFeature) {
10312             return true;
10313         }
10314         Objects.requireNonNull(who, "ComponentName is null");
10315         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
10316         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
10317                 String.format(NOT_SYSTEM_CALLER_MSG,
10318                         "query if an accessibility service is disabled by admin"));
10319 
10320         synchronized (getLockObject()) {
10321             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10322             if (admin == null) {
10323                 return false;
10324             }
10325             if (admin.permittedAccessiblityServices == null) {
10326                 return true;
10327             }
10328             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
10329                     admin.permittedAccessiblityServices, userHandle);
10330         }
10331     }
10332 
10333     @Override
10334     public boolean setPermittedInputMethods(ComponentName who, List packageList,
10335             boolean calledOnParentInstance) {
10336         if (!mHasFeature) {
10337             return false;
10338         }
10339         Objects.requireNonNull(who, "ComponentName is null");
10340 
10341         final CallerIdentity caller = getCallerIdentity(who);
10342         final int userId = getProfileParentUserIfRequested(
10343                 caller.getUserId(), calledOnParentInstance);
10344         if (calledOnParentInstance) {
10345             Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
10346             Preconditions.checkArgument(packageList == null || packageList.isEmpty(),
10347                     "Permitted input methods must allow all input methods or only "
10348                             + "system input methods when called on the parent instance of an "
10349                             + "organization-owned device");
10350         } else {
10351             Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
10352         }
10353 
10354         if (packageList != null) {
10355             List<InputMethodInfo> enabledImes = mInjector.binderWithCleanCallingIdentity(() ->
10356                     InputMethodManagerInternal.get().getEnabledInputMethodListAsUser(userId));
10357             if (enabledImes != null) {
10358                 List<String> enabledPackages = new ArrayList<String>();
10359                 for (InputMethodInfo ime : enabledImes) {
10360                     enabledPackages.add(ime.getPackageName());
10361                 }
10362                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
10363                         userId)) {
10364                     Slogf.e(LOG_TAG, "Cannot set permitted input methods, because the list of "
10365                             + "permitted input methods excludes an already-enabled input method.");
10366                     return false;
10367                 }
10368             }
10369         }
10370 
10371         synchronized (getLockObject()) {
10372             final ActiveAdmin admin = getParentOfAdminIfRequired(
10373                     getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParentInstance);
10374             admin.permittedInputMethods = packageList;
10375             saveSettingsLocked(caller.getUserId());
10376         }
10377 
10378         DevicePolicyEventLogger
10379                 .createEvent(DevicePolicyEnums.SET_PERMITTED_INPUT_METHODS)
10380                 .setAdmin(who)
10381                 .setStrings(getStringArrayForLogging(packageList, calledOnParentInstance))
10382                 .write();
10383         return true;
10384     }
10385 
10386     private String[] getStringArrayForLogging(List list, boolean calledOnParentInstance) {
10387         List<String> stringList = new ArrayList<String>();
10388         stringList.add(calledOnParentInstance ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT);
10389         if (list == null) {
10390             stringList.add(NULL_STRING_ARRAY);
10391         } else {
10392             stringList.addAll((List<String>) list);
10393         }
10394         return stringList.toArray(new String[0]);
10395     }
10396 
10397     @Override
10398     public List getPermittedInputMethods(ComponentName who, boolean calledOnParentInstance) {
10399         if (!mHasFeature) {
10400             return null;
10401         }
10402         Objects.requireNonNull(who, "ComponentName is null");
10403 
10404         final CallerIdentity caller = getCallerIdentity(who);
10405         if (calledOnParentInstance) {
10406             Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
10407         } else {
10408             Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
10409         }
10410 
10411         synchronized (getLockObject()) {
10412             final ActiveAdmin admin = getParentOfAdminIfRequired(
10413                     getProfileOwnerOrDeviceOwnerLocked(caller), calledOnParentInstance);
10414             return admin.permittedInputMethods;
10415         }
10416     }
10417 
10418     @Override
10419     public List getPermittedInputMethodsForCurrentUser() {
10420         final CallerIdentity caller = getCallerIdentity();
10421         Preconditions.checkCallAuthorization(canManageUsers(caller));
10422 
10423         synchronized (getLockObject()) {
10424             List<String> result = null;
10425             // Only device or profile owners can have permitted lists set.
10426             List<ActiveAdmin> admins = getActiveAdminsForAffectedUserLocked(caller.getUserId());
10427             for (ActiveAdmin admin: admins) {
10428                 List<String> fromAdmin = admin.permittedInputMethods;
10429                 if (fromAdmin != null) {
10430                     if (result == null) {
10431                         result = new ArrayList<String>(fromAdmin);
10432                     } else {
10433                         result.retainAll(fromAdmin);
10434                     }
10435                 }
10436             }
10437 
10438             // If we have a permitted list add all system input methods.
10439             if (result != null) {
10440                 List<InputMethodInfo> imes = InputMethodManagerInternal
10441                         .get().getInputMethodListAsUser(caller.getUserId());
10442                 if (imes != null) {
10443                     for (InputMethodInfo ime : imes) {
10444                         ServiceInfo serviceInfo = ime.getServiceInfo();
10445                         ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
10446                         if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10447                             result.add(serviceInfo.packageName);
10448                         }
10449                     }
10450                 }
10451             }
10452             return result;
10453         }
10454     }
10455 
10456     @Override
10457     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
10458             int userHandle, boolean calledOnParentInstance) {
10459         if (!mHasFeature) {
10460             return true;
10461         }
10462         Objects.requireNonNull(who, "ComponentName is null");
10463         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
10464         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
10465                 String.format(NOT_SYSTEM_CALLER_MSG,
10466                         "query if an input method is disabled by admin"));
10467 
10468         synchronized (getLockObject()) {
10469             ActiveAdmin admin = getParentOfAdminIfRequired(
10470                     getActiveAdminUncheckedLocked(who, userHandle), calledOnParentInstance);
10471             if (admin == null) {
10472                 return false;
10473             }
10474             if (admin.permittedInputMethods == null) {
10475                 return true;
10476             }
10477             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
10478                     admin.permittedInputMethods, userHandle);
10479         }
10480     }
10481 
10482     @Override
10483     public boolean setPermittedCrossProfileNotificationListeners(
10484             ComponentName who, List<String> packageList) {
10485         if (!mHasFeature) {
10486             return false;
10487         }
10488         Objects.requireNonNull(who, "ComponentName is null");
10489         final CallerIdentity caller = getCallerIdentity(who);
10490 
10491         if (!isManagedProfile(caller.getUserId())) {
10492             return false;
10493         }
10494 
10495         synchronized (getLockObject()) {
10496             ActiveAdmin admin = getProfileOwnerLocked(caller);
10497             admin.permittedNotificationListeners = packageList;
10498             saveSettingsLocked(caller.getUserId());
10499         }
10500         return true;
10501     }
10502 
10503     @Override
10504     public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
10505         if (!mHasFeature) {
10506             return null;
10507         }
10508         Objects.requireNonNull(who, "ComponentName is null");
10509         final CallerIdentity caller = getCallerIdentity(who);
10510 
10511         synchronized (getLockObject()) {
10512             // API contract is to return null if there are no permitted cross-profile notification
10513             // listeners, including in Device Owner mode.
10514             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
10515             return admin.permittedNotificationListeners;
10516         }
10517     }
10518 
10519     @Override
10520     public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
10521         if (!mHasFeature) {
10522             return true;
10523         }
10524 
10525         Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
10526         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
10527                 String.format(NOT_SYSTEM_CALLER_MSG,
10528                         "query if a notification listener service is permitted"));
10529 
10530         synchronized (getLockObject()) {
10531             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
10532             if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
10533                 return true;
10534             }
10535             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
10536                     profileOwner.permittedNotificationListeners, userId);
10537 
10538         }
10539     }
10540 
10541     private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
10542         DevicePolicyData policyData = getUserData(userHandle);
10543         if (policyData.mAdminBroadcastPending) {
10544             // Send the initialization data to profile owner and delete the data
10545             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
10546             boolean clearInitBundle = true;
10547             if (admin != null) {
10548                 PersistableBundle initBundle = policyData.mInitBundle;
10549                 clearInitBundle = sendAdminCommandLocked(admin,
10550                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
10551                         initBundle == null ? null : new Bundle(initBundle),
10552                         /* result= */ null ,
10553                         /* inForeground= */ true);
10554             }
10555             if (clearInitBundle) {
10556                 // If there's no admin or we've successfully called the admin, clear the init bundle
10557                 // otherwise, keep it around
10558                 policyData.mInitBundle = null;
10559                 policyData.mAdminBroadcastPending = false;
10560                 saveSettingsLocked(userHandle);
10561             }
10562         }
10563     }
10564 
10565     @Override
10566     public void finalizeWorkProfileProvisioning(UserHandle managedProfileUser,
10567             Account migratedAccount) {
10568         Preconditions.checkCallAuthorization(
10569                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
10570 
10571         if (!isManagedProfile(managedProfileUser.getIdentifier())) {
10572             throw new IllegalStateException("Given user is not a managed profile");
10573         }
10574         ComponentName profileOwnerComponent =
10575                 mOwners.getProfileOwnerComponent(managedProfileUser.getIdentifier());
10576         if (profileOwnerComponent == null) {
10577             throw new IllegalStateException("There is no profile owner on the given profile");
10578         }
10579         Intent primaryProfileSuccessIntent = new Intent(ACTION_MANAGED_PROFILE_PROVISIONED);
10580         primaryProfileSuccessIntent.setPackage(profileOwnerComponent.getPackageName());
10581         primaryProfileSuccessIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES
10582                 | Intent.FLAG_RECEIVER_FOREGROUND);
10583         primaryProfileSuccessIntent.putExtra(Intent.EXTRA_USER, managedProfileUser);
10584 
10585         if (migratedAccount != null) {
10586             primaryProfileSuccessIntent.putExtra(EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE,
10587                     migratedAccount);
10588         }
10589 
10590         mContext.sendBroadcastAsUser(primaryProfileSuccessIntent,
10591                 UserHandle.of(getProfileParentId(managedProfileUser.getIdentifier())));
10592     }
10593 
10594     @Override
10595     public UserHandle createAndManageUser(ComponentName admin, String name,
10596             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
10597         Objects.requireNonNull(admin, "admin is null");
10598         Objects.requireNonNull(profileOwner, "profileOwner is null");
10599         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
10600             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
10601                     + admin + " are not in the same package");
10602         }
10603         final CallerIdentity caller = getCallerIdentity(admin);
10604         // Only allow the system user to use this method
10605         Preconditions.checkCallAuthorization(caller.getUserHandle().isSystem(),
10606                 "createAndManageUser was called from non-system user");
10607         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
10608         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CREATE_AND_MANAGE_USER);
10609 
10610         final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
10611         final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
10612                 && UserManager.isDeviceInDemoMode(mContext);
10613         final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
10614         final int targetSdkVersion;
10615 
10616         // Create user.
10617         UserHandle user = null;
10618         synchronized (getLockObject()) {
10619             final long id = mInjector.binderClearCallingIdentity();
10620             try {
10621                 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion(
10622                         caller.getUid());
10623 
10624                 // Return detail error code for checks inside
10625                 // UserManagerService.createUserInternalUnchecked.
10626                 DeviceStorageMonitorInternal deviceStorageMonitorInternal =
10627                         LocalServices.getService(DeviceStorageMonitorInternal.class);
10628                 if (deviceStorageMonitorInternal.isMemoryLow()) {
10629                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
10630                         throw new ServiceSpecificException(
10631                                 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage");
10632                     } else {
10633                         return null;
10634                     }
10635                 }
10636                 if (!mUserManager.canAddMoreUsers()) {
10637                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
10638                         throw new ServiceSpecificException(
10639                                 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached");
10640                     } else {
10641                         return null;
10642                     }
10643                 }
10644 
10645                 int userInfoFlags = ephemeral ? UserInfo.FLAG_EPHEMERAL : 0;
10646                 String userType = demo ? UserManager.USER_TYPE_FULL_DEMO
10647                         : UserManager.USER_TYPE_FULL_SECONDARY;
10648                 String[] disallowedPackages = null;
10649                 if (!leaveAllSystemAppsEnabled) {
10650                     disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
10651                             UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
10652                             new String[0]);
10653                 }
10654 
10655                 Object token = new Object();
10656                 Slogf.d(LOG_TAG, "Adding new pending token: " + token);
10657                 mPendingUserCreatedCallbackTokens.add(token);
10658                 try {
10659                     UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
10660                             userType, userInfoFlags, disallowedPackages, token);
10661                     if (userInfo != null) {
10662                         user = userInfo.getUserHandle();
10663                     }
10664                 } catch (UserManager.CheckedUserOperationException e) {
10665                     Slogf.e(LOG_TAG, "Couldn't createUserEvenWhenDisallowed", e);
10666                 }
10667             } finally {
10668                 mInjector.binderRestoreCallingIdentity(id);
10669             }
10670         } // synchronized
10671 
10672         if (user == null) {
10673             if (targetSdkVersion >= Build.VERSION_CODES.P) {
10674                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
10675                         "failed to create user");
10676             } else {
10677                 return null;
10678             }
10679         }
10680 
10681         final int userHandle = user.getIdentifier();
10682         final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED)
10683                 .putExtra(Intent.EXTRA_USER_HANDLE, userHandle)
10684                 .putExtra(
10685                         DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
10686                         leaveAllSystemAppsEnabled)
10687                 .setPackage(getManagedProvisioningPackage(mContext))
10688                 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10689         mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
10690 
10691         final long id = mInjector.binderClearCallingIdentity();
10692         try {
10693             manageUserUnchecked(admin, profileOwner, userHandle, adminExtras,
10694                     /* showDisclaimer= */ true);
10695 
10696             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
10697                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
10698                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
10699             }
10700 
10701             return user;
10702         } catch (Throwable re) {
10703             mUserManager.removeUser(userHandle);
10704             if (targetSdkVersion >= Build.VERSION_CODES.P) {
10705                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
10706                         re.getMessage());
10707             } else {
10708                 return null;
10709             }
10710         } finally {
10711             mInjector.binderRestoreCallingIdentity(id);
10712         }
10713     }
10714 
10715     private void manageUserUnchecked(ComponentName admin, ComponentName profileOwner,
10716             @UserIdInt int userId, @Nullable PersistableBundle adminExtras,
10717             boolean showDisclaimer) {
10718         synchronized (getLockObject()) {
10719             if (VERBOSE_LOG) {
10720                 Slogf.v(LOG_TAG, "manageUserUnchecked(): admin=" + admin + ", po=" + profileOwner
10721                         + ", userId=" + userId + ", hasAdminExtras=" + (adminExtras != null)
10722                         + ", showDisclaimer=" + showDisclaimer);
10723             }
10724         }
10725         final String adminPkg = admin.getPackageName();
10726         mInjector.binderWithCleanCallingIdentity(() -> {
10727             try {
10728                 // Install the profile owner if not present.
10729                 if (!mIPackageManager.isPackageAvailable(adminPkg, userId)) {
10730                     mIPackageManager.installExistingPackageAsUser(adminPkg, userId,
10731                             PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
10732                             PackageManager.INSTALL_REASON_POLICY,
10733                             /* allowlistedRestrictedPermissions= */ null);
10734                 }
10735             } catch (RemoteException e) {
10736                 // Does not happen, same process
10737                 Slogf.wtf(LOG_TAG, e, "Failed to install admin package %s for user %d",
10738                         adminPkg, userId);
10739             }
10740         });
10741 
10742         // Set admin.
10743         setActiveAdmin(profileOwner, /* refreshing= */ true, userId);
10744         final String ownerName = getProfileOwnerNameUnchecked(
10745                 Process.myUserHandle().getIdentifier());
10746         setProfileOwner(profileOwner, ownerName, userId);
10747 
10748         synchronized (getLockObject()) {
10749             DevicePolicyData policyData = getUserData(userId);
10750             policyData.mInitBundle = adminExtras;
10751             policyData.mAdminBroadcastPending = true;
10752             policyData.mNewUserDisclaimer = showDisclaimer
10753                     ? DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED
10754                     : DevicePolicyData.NEW_USER_DISCLAIMER_NOT_NEEDED;
10755             saveSettingsLocked(userId);
10756 
10757         }
10758     }
10759 
10760     private void handleNewUserCreated(UserInfo user, @Nullable Object token) {
10761         if (VERBOSE_LOG) {
10762             Slogf.v(LOG_TAG, "handleNewUserCreated(): user=" + user.toFullString()
10763                     + ", token=" + token);
10764         }
10765 
10766         final int userId = user.id;
10767         if (token != null) {
10768             synchronized (getLockObject()) {
10769                 if (mPendingUserCreatedCallbackTokens.contains(token)) {
10770                     // Ignore because it was triggered by createAndManageUser()
10771                     Slogf.d(LOG_TAG, "handleNewUserCreated(): ignoring for user " + userId
10772                             + " due to token" + token);
10773                     mPendingUserCreatedCallbackTokens.remove(token);
10774                     return;
10775                 }
10776             }
10777         }
10778 
10779         if (!mOwners.hasDeviceOwner() || !user.isFull() || user.isManagedProfile()
10780                 || user.isGuest()) {
10781             return;
10782         }
10783 
10784         if (mInjector.userManagerIsHeadlessSystemUserMode()) {
10785             ComponentName admin = mOwners.getDeviceOwnerComponent();
10786             Slogf.i(LOG_TAG, "Automatically setting profile owner (" + admin + ") on new user "
10787                     + userId);
10788             manageUserUnchecked(/* deviceOwner= */ admin, /* profileOwner= */ admin,
10789                     /* managedUser= */ userId, /* adminExtras= */ null, /* showDisclaimer= */ true);
10790         } else {
10791             Slogf.i(LOG_TAG, "User %d added on DO mode; setting ShowNewUserDisclaimer", userId);
10792             setShowNewUserDisclaimer(userId, DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED);
10793         }
10794     }
10795 
10796     @Override
10797     public void resetNewUserDisclaimer() {
10798         CallerIdentity callerIdentity = getCallerIdentity();
10799         canManageUsers(callerIdentity);
10800 
10801         setShowNewUserDisclaimer(callerIdentity.getUserId(),
10802                 DevicePolicyData.NEW_USER_DISCLAIMER_SHOWN);
10803     }
10804 
10805     private void setShowNewUserDisclaimer(@UserIdInt int userId, String value) {
10806         Slogf.i(LOG_TAG, "Setting new user disclaimer for user " + userId + " as " + value);
10807         synchronized (getLockObject()) {
10808             DevicePolicyData policyData = getUserData(userId);
10809             policyData.mNewUserDisclaimer = value;
10810             saveSettingsLocked(userId);
10811         }
10812     }
10813 
10814     private void showNewUserDisclaimerIfNecessary(@UserIdInt int userId) {
10815         boolean mustShow;
10816         synchronized (getLockObject()) {
10817             DevicePolicyData policyData = getUserData(userId);
10818             if (VERBOSE_LOG) {
10819                 Slogf.v(LOG_TAG, "showNewUserDisclaimerIfNecessary(" + userId + "): "
10820                         + policyData.mNewUserDisclaimer + ")");
10821             }
10822             mustShow = DevicePolicyData.NEW_USER_DISCLAIMER_NEEDED
10823                     .equals(policyData.mNewUserDisclaimer);
10824         }
10825         if (!mustShow) return;
10826 
10827         Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_NEW_USER_DISCLAIMER);
10828 
10829         // TODO(b/172691310): add CTS tests to make sure disclaimer is shown
10830         Slogf.i(LOG_TAG, "Dispatching ACTION_SHOW_NEW_USER_DISCLAIMER intent");
10831         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
10832     }
10833 
10834     @Override
10835     public boolean removeUser(ComponentName who, UserHandle userHandle) {
10836         Objects.requireNonNull(who, "ComponentName is null");
10837         Objects.requireNonNull(userHandle, "UserHandle is null");
10838         final CallerIdentity caller = getCallerIdentity(who);
10839         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
10840         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REMOVE_USER);
10841 
10842         return mInjector.binderWithCleanCallingIdentity(() -> {
10843             String restriction = isManagedProfile(userHandle.getIdentifier())
10844                     ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
10845                     : UserManager.DISALLOW_REMOVE_USER;
10846             if (isAdminAffectedByRestriction(who, restriction, caller.getUserId())) {
10847                 Slogf.w(LOG_TAG, "The device owner cannot remove a user because %s is enabled, and "
10848                         + "was not set by the device owner", restriction);
10849                 return false;
10850             }
10851             return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
10852         });
10853     }
10854 
10855     private boolean isAdminAffectedByRestriction(
10856             ComponentName admin, String userRestriction, int userId) {
10857         switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
10858             case UserManager.RESTRICTION_NOT_SET:
10859                 return false;
10860             case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
10861                 return !isDeviceOwner(admin, userId);
10862             case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
10863                 return !isProfileOwner(admin, userId);
10864             default:
10865                 return true;
10866         }
10867     }
10868 
10869     @Override
10870     public boolean switchUser(ComponentName who, UserHandle userHandle) {
10871         Objects.requireNonNull(who, "ComponentName is null");
10872         final CallerIdentity caller = getCallerIdentity(who);
10873         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
10874         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SWITCH_USER);
10875 
10876         boolean switched = false;
10877         // Save previous logout user id in case of failure
10878         int logoutUserId = getLogoutUserIdUnchecked();
10879         synchronized (getLockObject()) {
10880             long id = mInjector.binderClearCallingIdentity();
10881             try {
10882                 int userId = UserHandle.USER_SYSTEM;
10883                 if (userHandle != null) {
10884                     userId = userHandle.getIdentifier();
10885                 }
10886                 Slogf.i(LOG_TAG, "Switching to user %d (logout user is %d)", userId, logoutUserId);
10887                 setLogoutUserIdLocked(UserHandle.USER_CURRENT);
10888                 switched = mInjector.getIActivityManager().switchUser(userId);
10889                 if (!switched) {
10890                     Slogf.w(LOG_TAG, "Failed to switch to user %d", userId);
10891                 }
10892                 return switched;
10893             } catch (RemoteException e) {
10894                 Slogf.e(LOG_TAG, "Couldn't switch user", e);
10895                 return false;
10896             } finally {
10897                 mInjector.binderRestoreCallingIdentity(id);
10898                 if (!switched) {
10899                     setLogoutUserIdLocked(logoutUserId);
10900                 }
10901             }
10902         }
10903     }
10904 
10905     @Override
10906     public int getLogoutUserId() {
10907         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
10908 
10909         return getLogoutUserIdUnchecked();
10910     }
10911 
10912     private @UserIdInt int getLogoutUserIdUnchecked() {
10913         if (!mInjector.userManagerIsHeadlessSystemUserMode()) {
10914             // mLogoutUserId is USER_SYSTEM as well, but there's no need to acquire the lock
10915             return UserHandle.USER_SYSTEM;
10916         }
10917         synchronized (getLockObject()) {
10918             return mLogoutUserId;
10919         }
10920     }
10921 
10922     @Override
10923     public void clearLogoutUser() {
10924         CallerIdentity caller = getCallerIdentity();
10925         Preconditions.checkCallAuthorization(canManageUsers(caller));
10926 
10927         Slogf.i(LOG_TAG, "Clearing logout user as requested by %s", caller);
10928         clearLogoutUserUnchecked();
10929     }
10930 
10931     private void clearLogoutUserUnchecked() {
10932         if (!mInjector.userManagerIsHeadlessSystemUserMode()) return; // ignore
10933 
10934         synchronized (getLockObject()) {
10935             setLogoutUserIdLocked(UserHandle.USER_NULL);
10936         }
10937     }
10938 
10939     @GuardedBy("getLockObject()")
10940     private void setLogoutUserIdLocked(@UserIdInt int userId) {
10941         if (!mInjector.userManagerIsHeadlessSystemUserMode()) return; // ignore
10942 
10943         if (userId == UserHandle.USER_CURRENT) {
10944             userId = getCurrentForegroundUserId();
10945         }
10946 
10947         Slogf.d(LOG_TAG, "setLogoutUserId(): %d -> %d", mLogoutUserId, userId);
10948         mLogoutUserId = userId;
10949     }
10950 
10951     @Override
10952     public int startUserInBackground(ComponentName who, UserHandle userHandle) {
10953         Objects.requireNonNull(who, "ComponentName is null");
10954         Objects.requireNonNull(userHandle, "UserHandle is null");
10955         final CallerIdentity caller = getCallerIdentity(who);
10956         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
10957         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_START_USER_IN_BACKGROUND);
10958 
10959         final int userId = userHandle.getIdentifier();
10960         if (isManagedProfile(userId)) {
10961             Slogf.w(LOG_TAG, "Managed profile cannot be started in background");
10962             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
10963         }
10964 
10965         final long id = mInjector.binderClearCallingIdentity();
10966         try {
10967             if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) {
10968                 Slogf.w(LOG_TAG, "Cannot start user %d, too many users in background", userId);
10969                 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS;
10970             }
10971 
10972             Slogf.i(LOG_TAG, "Starting user %d in background", userId);
10973             if (mInjector.getIActivityManager().startUserInBackground(userId)) {
10974                 return UserManager.USER_OPERATION_SUCCESS;
10975             } else {
10976                 Slogf.w(LOG_TAG, "failed to start user %d in background", userId);
10977                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
10978             }
10979         } catch (RemoteException e) {
10980             // Same process, should not happen.
10981             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
10982         } finally {
10983             mInjector.binderRestoreCallingIdentity(id);
10984         }
10985     }
10986 
10987     @Override
10988     public int stopUser(ComponentName who, UserHandle userHandle) {
10989         Objects.requireNonNull(who, "ComponentName is null");
10990         Objects.requireNonNull(userHandle, "UserHandle is null");
10991         final CallerIdentity caller = getCallerIdentity(who);
10992         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
10993         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_STOP_USER);
10994 
10995         final int userId = userHandle.getIdentifier();
10996         if (isManagedProfile(userId)) {
10997             Slogf.w(LOG_TAG, "Managed profile cannot be stopped");
10998             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
10999         }
11000 
11001         return stopUserUnchecked(userId);
11002     }
11003 
11004     @Override
11005     public int logoutUser(ComponentName who) {
11006         Objects.requireNonNull(who, "ComponentName is null");
11007         final CallerIdentity caller = getCallerIdentity(who);
11008         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
11009         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_LOGOUT_USER);
11010 
11011         final int callingUserId = caller.getUserId();
11012         synchronized (getLockObject()) {
11013             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
11014                 throw new SecurityException("Admin " + who +
11015                         " is neither the device owner or affiliated user's profile owner.");
11016             }
11017         }
11018 
11019         if (isManagedProfile(callingUserId)) {
11020             Slogf.w(LOG_TAG, "Managed profile cannot be logout");
11021             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
11022         }
11023 
11024         // TODO(b/204585343): remove the headless system user check?
11025         if (mInjector.userManagerIsHeadlessSystemUserMode() && callingUserId != mInjector
11026                 .binderWithCleanCallingIdentity(() -> getCurrentForegroundUserId())) {
11027             Slogf.d(LOG_TAG, "logoutUser(): user %d is in background, just stopping, not switching",
11028                     callingUserId);
11029             return stopUserUnchecked(callingUserId);
11030         }
11031 
11032         int logoutUserId = getLogoutUserIdUnchecked();
11033         if (logoutUserId == UserHandle.USER_NULL) {
11034             // Could happen on devices using headless system user mode when called before calling
11035             // switchUser() or startUserInBackground() first
11036             Slogf.w(LOG_TAG, "logoutUser(): could not determine which user to switch to");
11037             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
11038         }
11039         final long id = mInjector.binderClearCallingIdentity();
11040         try {
11041             Slogf.i(LOG_TAG, "logoutUser(): switching to user %d", logoutUserId);
11042             if (!mInjector.getIActivityManager().switchUser(logoutUserId)) {
11043                 Slogf.w(LOG_TAG, "Failed to switch to user %d", logoutUserId);
11044                 // This should never happen as target user is determined by getPreviousUserId()
11045                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
11046             }
11047             clearLogoutUserUnchecked();
11048         } catch (RemoteException e) {
11049             // Same process, should not happen.
11050             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
11051         } finally {
11052             mInjector.binderRestoreCallingIdentity(id);
11053         }
11054 
11055         return stopUserUnchecked(callingUserId);
11056     }
11057 
11058     private int stopUserUnchecked(@UserIdInt int userId) {
11059         Slogf.i(LOG_TAG, "Stopping user %d", userId);
11060         final long id = mInjector.binderClearCallingIdentity();
11061         try {
11062             switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) {
11063                 case ActivityManager.USER_OP_SUCCESS:
11064                     return UserManager.USER_OPERATION_SUCCESS;
11065                 case ActivityManager.USER_OP_IS_CURRENT:
11066                     return UserManager.USER_OPERATION_ERROR_CURRENT_USER;
11067                 default:
11068                     return UserManager.USER_OPERATION_ERROR_UNKNOWN;
11069             }
11070         } catch (RemoteException e) {
11071             // Same process, should not happen.
11072             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
11073         } finally {
11074             mInjector.binderRestoreCallingIdentity(id);
11075         }
11076     }
11077 
11078     @Override
11079     public List<UserHandle> getSecondaryUsers(ComponentName who) {
11080         Objects.requireNonNull(who, "ComponentName is null");
11081         final CallerIdentity caller = getCallerIdentity(who);
11082         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
11083 
11084         return mInjector.binderWithCleanCallingIdentity(() -> {
11085             final List<UserInfo> userInfos = mInjector.getUserManager().getAliveUsers();
11086             final List<UserHandle> userHandles = new ArrayList<>();
11087             for (UserInfo userInfo : userInfos) {
11088                 UserHandle userHandle = userInfo.getUserHandle();
11089                 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
11090                     userHandles.add(userInfo.getUserHandle());
11091                 }
11092             }
11093             return userHandles;
11094         });
11095     }
11096 
11097     @Override
11098     public boolean isEphemeralUser(ComponentName who) {
11099         Objects.requireNonNull(who, "ComponentName is null");
11100 
11101         final CallerIdentity caller = getCallerIdentity(who);
11102         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
11103 
11104         return mInjector.binderWithCleanCallingIdentity(
11105                 () -> mInjector.getUserManager().isUserEphemeral(caller.getUserId()));
11106     }
11107 
11108     @Override
11109     public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
11110             String packageName) {
11111         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11112         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11113                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11114                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_APP_RESTRICTIONS)));
11115 
11116         return mInjector.binderWithCleanCallingIdentity(() -> {
11117             Bundle bundle = mUserManager.getApplicationRestrictions(packageName,
11118                     caller.getUserHandle());
11119            // if no restrictions were saved, mUserManager.getApplicationRestrictions
11120            // returns null, but DPM method should return an empty Bundle as per JavaDoc
11121            return bundle != null ? bundle : Bundle.EMPTY;
11122         });
11123     }
11124 
11125     /**
11126      * Returns the apps that are non-exempt from some policies (such as suspension), and populates
11127      * the given set with the apps that are exempt.
11128      *
11129      * @param packageNames apps to check
11130      * @param outputExemptApps will be populate with subset of {@code packageNames} that is exempt
11131      * from some policy restrictions
11132      *
11133      * @return subset of {@code packageNames} that is affected by some policy restrictions.
11134      */
11135     private String[] populateNonExemptAndExemptFromPolicyApps(String[] packageNames,
11136             Set<String> outputExemptApps) {
11137         Preconditions.checkArgument(outputExemptApps.isEmpty(), "outputExemptApps is not empty");
11138         List<String> exemptAppsList = listPolicyExemptAppsUnchecked();
11139         if (exemptAppsList.isEmpty()) {
11140             return packageNames;
11141         }
11142         // Using a set so contains() is O(1)
11143         Set<String> exemptApps = new HashSet<>(exemptAppsList);
11144         List<String> nonExemptApps = new ArrayList<>(packageNames.length);
11145         for (int i = 0; i < packageNames.length; i++) {
11146             String app = packageNames[i];
11147             if (exemptApps.contains(app)) {
11148                 outputExemptApps.add(app);
11149             } else {
11150                 nonExemptApps.add(app);
11151             }
11152         }
11153         String[] result = new String[nonExemptApps.size()];
11154         nonExemptApps.toArray(result);
11155         return result;
11156     }
11157 
11158     @Override
11159     public String[] setPackagesSuspended(ComponentName who, String callerPackage,
11160             String[] packageNames, boolean suspended) {
11161         Objects.requireNonNull(packageNames, "array of packages cannot be null");
11162         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11163         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11164                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11165                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS)));
11166         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PACKAGES_SUSPENDED);
11167 
11168         // Must remove the exempt apps from the input before calling PM, then add them back to
11169         // the array returned to the caller
11170         Set<String> exemptApps = new HashSet<>();
11171         packageNames = populateNonExemptAndExemptFromPolicyApps(packageNames, exemptApps);
11172 
11173         String[] nonSuspendedPackages = null;
11174         synchronized (getLockObject()) {
11175             long id = mInjector.binderClearCallingIdentity();
11176             try {
11177                 nonSuspendedPackages = mIPackageManager.setPackagesSuspendedAsUser(packageNames,
11178                         suspended, null, null, null, PLATFORM_PACKAGE_NAME, caller.getUserId());
11179             } catch (RemoteException re) {
11180                 // Shouldn't happen.
11181                 Slogf.e(LOG_TAG, "Failed talking to the package manager", re);
11182             } finally {
11183                 mInjector.binderRestoreCallingIdentity(id);
11184             }
11185         }
11186         DevicePolicyEventLogger
11187                 .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED)
11188                 .setAdmin(caller.getPackageName())
11189                 .setBoolean(/* isDelegate */ who == null)
11190                 .setStrings(packageNames)
11191                 .write();
11192 
11193         if (nonSuspendedPackages == null) {
11194             Slogf.w(LOG_TAG, "PM failed to suspend packages (%s)", Arrays.toString(packageNames));
11195             return packageNames;
11196         }
11197         if (exemptApps.isEmpty()) {
11198             return nonSuspendedPackages;
11199         }
11200 
11201         String[] result = buildNonSuspendedPackagesUnionArray(nonSuspendedPackages, exemptApps);
11202         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Returning %s", Arrays.toString(result));
11203         return result;
11204     }
11205 
11206     /**
11207      * Returns an array containing the union of the given non-suspended packages and
11208      * exempt apps. Assumes both parameters are non-null and non-empty.
11209      */
11210     private String[] buildNonSuspendedPackagesUnionArray(String[] nonSuspendedPackages,
11211             Set<String> exemptApps) {
11212         String[] result = new String[nonSuspendedPackages.length + exemptApps.size()];
11213         int index = 0;
11214         for (String app : nonSuspendedPackages) {
11215             result[index++] = app;
11216         }
11217         for (String app : exemptApps) {
11218             result[index++] = app;
11219         }
11220         return result;
11221     }
11222 
11223     @Override
11224     public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
11225         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11226         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11227                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11228                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS)));
11229 
11230         synchronized (getLockObject()) {
11231             long id = mInjector.binderClearCallingIdentity();
11232             try {
11233                 return mIPackageManager.isPackageSuspendedForUser(packageName, caller.getUserId());
11234             } catch (RemoteException re) {
11235                 // Shouldn't happen.
11236                 Slogf.e(LOG_TAG, "Failed talking to the package manager", re);
11237             } finally {
11238                 mInjector.binderRestoreCallingIdentity(id);
11239             }
11240             return false;
11241         }
11242     }
11243 
11244     @Override
11245     public List<String> listPolicyExemptApps() {
11246         CallerIdentity caller = getCallerIdentity();
11247         Preconditions.checkCallAuthorization(
11248                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS) || isDeviceOwner(caller)
11249                         || isProfileOwner(caller));
11250 
11251         return listPolicyExemptAppsUnchecked();
11252     }
11253 
11254     private List<String> listPolicyExemptAppsUnchecked() {
11255         // TODO(b/181238156): decide whether it should only list the apps set by the resources,
11256         // or also the "critical" apps defined by PersonalAppsSuspensionHelper (like SMS app).
11257         // If it's the latter, refactor PersonalAppsSuspensionHelper so it (or a superclass) takes
11258         // the resources on constructor.
11259         String[] core = mContext.getResources().getStringArray(R.array.policy_exempt_apps);
11260         String[] vendor = mContext.getResources().getStringArray(R.array.vendor_policy_exempt_apps);
11261 
11262         int size = core.length + vendor.length;
11263         Set<String> apps = new ArraySet<>(size);
11264         for (String app : core) {
11265             apps.add(app);
11266         }
11267         for (String app : vendor) {
11268             apps.add(app);
11269         }
11270 
11271         return new ArrayList<>(apps);
11272     }
11273 
11274     @Override
11275     public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner,
11276             boolean parent) {
11277         Objects.requireNonNull(who, "ComponentName is null");
11278 
11279         final CallerIdentity caller = getCallerIdentity(who);
11280 
11281         if (!UserRestrictionsUtils.isValidRestriction(key)) {
11282             return;
11283         }
11284 
11285         int userHandle = caller.getUserId();
11286         synchronized (getLockObject()) {
11287             final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
11288                     getProfileOwnerOrDeviceOwnerLocked(caller), parent);
11289 
11290             if (isDeviceOwner(caller)) {
11291                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
11292                     throw new SecurityException("Device owner cannot set user restriction " + key);
11293                 }
11294                 Preconditions.checkArgument(!parent,
11295                         "Cannot use the parent instance in Device Owner mode");
11296             } else {
11297                 boolean profileOwnerCanChangeOnItself = !parent
11298                         && UserRestrictionsUtils.canProfileOwnerChange(key, userHandle);
11299                 boolean orgOwnedProfileOwnerCanChangesGlobally = parent
11300                         && isProfileOwnerOfOrganizationOwnedDevice(caller)
11301                         && UserRestrictionsUtils.canProfileOwnerOfOrganizationOwnedDeviceChange(
11302                         key);
11303 
11304                 if (!profileOwnerCanChangeOnItself && !orgOwnedProfileOwnerCanChangesGlobally) {
11305                     throw new SecurityException("Profile owner cannot set user restriction " + key);
11306                 }
11307             }
11308             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_USER_RESTRICTION);
11309 
11310             // Save the restriction to ActiveAdmin.
11311             final Bundle restrictions = activeAdmin.ensureUserRestrictions();
11312             if (enabledFromThisOwner) {
11313                 restrictions.putBoolean(key, true);
11314             } else {
11315                 restrictions.remove(key);
11316             }
11317             saveUserRestrictionsLocked(userHandle);
11318         }
11319         final int eventId = enabledFromThisOwner
11320                 ? DevicePolicyEnums.ADD_USER_RESTRICTION
11321                 : DevicePolicyEnums.REMOVE_USER_RESTRICTION;
11322         DevicePolicyEventLogger
11323                 .createEvent(eventId)
11324                 .setAdmin(caller.getComponentName())
11325                 .setStrings(key, parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
11326                 .write();
11327         if (SecurityLog.isLoggingEnabled()) {
11328             final int eventTag = enabledFromThisOwner
11329                     ? SecurityLog.TAG_USER_RESTRICTION_ADDED
11330                     : SecurityLog.TAG_USER_RESTRICTION_REMOVED;
11331             SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key);
11332         }
11333     }
11334 
11335     private void saveUserRestrictionsLocked(int userId) {
11336         saveSettingsLocked(userId);
11337         pushUserRestrictions(userId);
11338         sendChangedNotification(userId);
11339     }
11340 
11341     /**
11342      * Pushes the user restrictions originating from a specific user.
11343      *
11344      * If called by the profile owner of an organization-owned device, the global and local
11345      * user restrictions will be an accumulation of the global user restrictions from the profile
11346      * owner active admin and its parent active admin. The key of the local user restrictions set
11347      * will be the target user id.
11348      */
11349     private void pushUserRestrictions(int originatingUserId) {
11350         final Bundle global;
11351         final RestrictionsSet local = new RestrictionsSet();
11352         final boolean isDeviceOwner;
11353         synchronized (getLockObject()) {
11354             isDeviceOwner = mOwners.isDeviceOwnerUserId(originatingUserId);
11355             if (isDeviceOwner) {
11356                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11357                 if (deviceOwner == null) {
11358                     return; // Shouldn't happen.
11359                 }
11360                 global = deviceOwner.getGlobalUserRestrictions(OWNER_TYPE_DEVICE_OWNER);
11361                 local.updateRestrictions(originatingUserId, deviceOwner.getLocalUserRestrictions(
11362                         OWNER_TYPE_DEVICE_OWNER));
11363             } else {
11364                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(originatingUserId);
11365                 if (profileOwner == null) {
11366                     return;
11367                 }
11368                 global = profileOwner.getGlobalUserRestrictions(OWNER_TYPE_PROFILE_OWNER);
11369                 local.updateRestrictions(originatingUserId, profileOwner.getLocalUserRestrictions(
11370                         OWNER_TYPE_PROFILE_OWNER));
11371                 // Global (device-wide) and local user restrictions set by the profile owner of an
11372                 // organization-owned device are stored in the parent ActiveAdmin instance.
11373                 if (isProfileOwnerOfOrganizationOwnedDevice(
11374                         profileOwner.getUserHandle().getIdentifier())) {
11375                     // The global restrictions set on the parent ActiveAdmin instance need to be
11376                     // merged with the global restrictions set on the profile owner ActiveAdmin
11377                     // instance, since both are to be applied device-wide.
11378                     UserRestrictionsUtils.merge(global,
11379                             profileOwner.getParentActiveAdmin().getGlobalUserRestrictions(
11380                                     OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
11381                     // The local restrictions set on the parent ActiveAdmin instance are only to be
11382                     // applied to the primary user. They therefore need to be added the local
11383                     // restriction set with the primary user id as the key, in this case the
11384                     // primary user id is the target user.
11385                     local.updateRestrictions(
11386                             getProfileParentId(profileOwner.getUserHandle().getIdentifier()),
11387                             profileOwner.getParentActiveAdmin().getLocalUserRestrictions(
11388                                     OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
11389                 }
11390             }
11391         }
11392         mUserManagerInternal.setDevicePolicyUserRestrictions(originatingUserId, global, local,
11393                 isDeviceOwner);
11394     }
11395 
11396     @Override
11397     public Bundle getUserRestrictions(ComponentName who, boolean parent) {
11398         if (!mHasFeature) {
11399             return null;
11400         }
11401         Objects.requireNonNull(who, "ComponentName is null");
11402 
11403         final CallerIdentity caller = getCallerIdentity(who);
11404         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller)
11405                 || (parent && isProfileOwnerOfOrganizationOwnedDevice(caller)));
11406 
11407         synchronized (getLockObject()) {
11408             final ActiveAdmin activeAdmin = getParentOfAdminIfRequired(
11409                     getProfileOwnerOrDeviceOwnerLocked(caller), parent);
11410             return activeAdmin.userRestrictions;
11411         }
11412     }
11413 
11414     @Override
11415     public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
11416             boolean hidden, boolean parent) {
11417         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11418         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11419                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11420                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS)));
11421 
11422         List<String> exemptApps = listPolicyExemptAppsUnchecked();
11423         if (exemptApps.contains(packageName)) {
11424             Slogf.d(LOG_TAG, "setApplicationHidden(): ignoring %s as it's on policy-exempt list",
11425                     packageName);
11426             return false;
11427         }
11428 
11429         final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
11430         boolean result;
11431         synchronized (getLockObject()) {
11432             if (parent) {
11433                 Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(
11434                         caller.getUserId()) && isManagedProfile(caller.getUserId()));
11435                 // Ensure the package provided is a system package, this is to ensure that this
11436                 // API cannot be used to leak if certain non-system package exists in the person
11437                 // profile.
11438                 mInjector.binderWithCleanCallingIdentity(() ->
11439                         enforcePackageIsSystemPackage(packageName, userId));
11440             }
11441             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_APPLICATION_HIDDEN);
11442 
11443             if (VERBOSE_LOG) {
11444                 Slogf.v(LOG_TAG, "calling pm.setApplicationHiddenSettingAsUser(%s, %b, %d)",
11445                         packageName, hidden, userId);
11446             }
11447             result = mInjector.binderWithCleanCallingIdentity(() -> mIPackageManager
11448                     .setApplicationHiddenSettingAsUser(packageName, hidden, userId));
11449         }
11450         DevicePolicyEventLogger
11451                 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN)
11452                 .setAdmin(caller.getPackageName())
11453                 .setBoolean(/* isDelegate */ who == null)
11454                 .setStrings(packageName, hidden ? "hidden" : "not_hidden",
11455                         parent ? CALLED_FROM_PARENT : NOT_CALLED_FROM_PARENT)
11456                 .write();
11457         return result;
11458     }
11459 
11460     @Override
11461     public boolean isApplicationHidden(ComponentName who, String callerPackage,
11462             String packageName, boolean parent) {
11463         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11464         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11465                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11466                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PACKAGE_ACCESS)));
11467 
11468         final int userId = parent ? getProfileParentId(caller.getUserId()) : caller.getUserId();
11469         synchronized (getLockObject()) {
11470             if (parent) {
11471                 Preconditions.checkCallAuthorization(
11472                         isProfileOwnerOfOrganizationOwnedDevice(caller.getUserId())
11473                         && isManagedProfile(caller.getUserId()));
11474                 // Ensure the package provided is a system package.
11475                 mInjector.binderWithCleanCallingIdentity(() ->
11476                         enforcePackageIsSystemPackage(packageName, userId));
11477             }
11478 
11479             return mInjector.binderWithCleanCallingIdentity(
11480                     () -> mIPackageManager.getApplicationHiddenSettingAsUser(packageName, userId));
11481         }
11482     }
11483 
11484     private void enforcePackageIsSystemPackage(String packageName, int userId)
11485             throws RemoteException {
11486         boolean isSystem;
11487         try {
11488             isSystem = isSystemApp(mIPackageManager, packageName, userId);
11489         } catch (IllegalArgumentException e) {
11490             isSystem = false;
11491         }
11492         if (!isSystem) {
11493             throw new IllegalArgumentException("The provided package is not a system package");
11494         }
11495     }
11496 
11497     @Override
11498     public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
11499         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11500         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11501                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11502                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP)));
11503 
11504         synchronized (getLockObject()) {
11505             final boolean isDemo = isCurrentUserDemo();
11506             int userId = caller.getUserId();
11507             long id = mInjector.binderClearCallingIdentity();
11508             try {
11509                 if (VERBOSE_LOG) {
11510                     Slogf.v(LOG_TAG, "installing " + packageName + " for " + userId);
11511                 }
11512 
11513                 Preconditions.checkArgument(isDemo || isSystemApp(mIPackageManager, packageName,
11514                         getProfileParentId(userId)), "Only system apps can be enabled this way");
11515 
11516                 // Install the app.
11517                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
11518                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
11519                         PackageManager.INSTALL_REASON_POLICY, null);
11520                 if (isDemo) {
11521                     // Ensure the app is also ENABLED for demo users.
11522                     mIPackageManager.setApplicationEnabledSetting(packageName,
11523                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
11524                             PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
11525                 }
11526             } catch (RemoteException re) {
11527                 // shouldn't happen
11528                 Slogf.wtf(LOG_TAG, "Failed to install " + packageName, re);
11529             } finally {
11530                 mInjector.binderRestoreCallingIdentity(id);
11531             }
11532         }
11533         DevicePolicyEventLogger
11534                 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP)
11535                 .setAdmin(caller.getPackageName())
11536                 .setBoolean(/* isDelegate */ who == null)
11537                 .setStrings(packageName)
11538                 .write();
11539     }
11540 
11541     @Override
11542     public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
11543         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11544         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11545                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11546                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_ENABLE_SYSTEM_APP)));
11547 
11548         int numberOfAppsInstalled = 0;
11549         synchronized (getLockObject()) {
11550             long id = mInjector.binderClearCallingIdentity();
11551             try {
11552                 final int parentUserId = getProfileParentId(caller.getUserId());
11553                 List<ResolveInfo> activitiesToEnable = mIPackageManager
11554                         .queryIntentActivities(intent,
11555                                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11556                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
11557                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
11558                                 parentUserId)
11559                         .getList();
11560 
11561                 if (VERBOSE_LOG) {
11562                     Slogf.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
11563                 }
11564                 if (activitiesToEnable != null) {
11565                     for (ResolveInfo info : activitiesToEnable) {
11566                         if (info.activityInfo != null) {
11567                             String packageName = info.activityInfo.packageName;
11568                             if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
11569                                 numberOfAppsInstalled++;
11570                                 mIPackageManager.installExistingPackageAsUser(packageName,
11571                                         caller.getUserId(),
11572                                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
11573                                         PackageManager.INSTALL_REASON_POLICY, null);
11574                             } else {
11575                                 Slogf.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
11576                                         + " system app");
11577                             }
11578                         }
11579                     }
11580                 }
11581             } catch (RemoteException e) {
11582                 // shouldn't happen
11583                 Slogf.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
11584                 return 0;
11585             } finally {
11586                 mInjector.binderRestoreCallingIdentity(id);
11587             }
11588         }
11589         DevicePolicyEventLogger
11590                 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP_WITH_INTENT)
11591                 .setAdmin(caller.getPackageName())
11592                 .setBoolean(/* isDelegate */ who == null)
11593                 .setStrings(intent.getAction())
11594                 .write();
11595         return numberOfAppsInstalled;
11596     }
11597 
11598     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
11599             throws RemoteException {
11600         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
11601                 userId);
11602         if (appInfo == null) {
11603             throw new IllegalArgumentException("The application " + packageName +
11604                     " is not present on this device");
11605         }
11606         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11607     }
11608 
11609     @Override
11610     public boolean installExistingPackage(ComponentName who, String callerPackage,
11611             String packageName) {
11612         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11613         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11614                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11615                 || (caller.hasPackage()
11616                 && isCallerDelegate(caller, DELEGATION_INSTALL_EXISTING_PACKAGE)));
11617 
11618         boolean result;
11619         synchronized (getLockObject()) {
11620             Preconditions.checkCallAuthorization(
11621                     isUserAffiliatedWithDeviceLocked(caller.getUserId()),
11622                             "Admin %s is neither the device owner or "
11623                                     + "affiliated user's profile owner.", who);
11624             final long id = mInjector.binderClearCallingIdentity();
11625             try {
11626                 if (VERBOSE_LOG) {
11627                     Slogf.v(LOG_TAG, "installing " + packageName + " for " + caller.getUserId());
11628                 }
11629 
11630                 // Install the package.
11631                 result = mIPackageManager.installExistingPackageAsUser(packageName,
11632                         caller.getUserId(),
11633                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
11634                         PackageManager.INSTALL_REASON_POLICY, null)
11635                         == PackageManager.INSTALL_SUCCEEDED;
11636             } catch (RemoteException re) {
11637                 // shouldn't happen
11638                 return false;
11639             } finally {
11640                 mInjector.binderRestoreCallingIdentity(id);
11641             }
11642         }
11643         if (result) {
11644             DevicePolicyEventLogger
11645                     .createEvent(DevicePolicyEnums.INSTALL_EXISTING_PACKAGE)
11646                     .setAdmin(caller.getPackageName())
11647                     .setBoolean(/* isDelegate */ who == null)
11648                     .setStrings(packageName)
11649                     .write();
11650         }
11651         return result;
11652     }
11653 
11654     @Override
11655     public void setAccountManagementDisabled(ComponentName who, String accountType,
11656             boolean disabled, boolean parent) {
11657         if (!mHasFeature) {
11658             return;
11659         }
11660         Objects.requireNonNull(who, "ComponentName is null");
11661         final CallerIdentity caller = getCallerIdentity(who);
11662         synchronized (getLockObject()) {
11663             /*
11664              * When called on the parent DPM instance (parent == true), affects active admin
11665              * selection in two ways:
11666              * * The ActiveAdmin must be of an org-owned profile owner.
11667              * * The parent ActiveAdmin instance should be used for managing the restriction.
11668              */
11669             final ActiveAdmin ap;
11670             if (parent) {
11671                 ap = getParentOfAdminIfRequired(getOrganizationOwnedProfileOwnerLocked(caller),
11672                         parent);
11673             } else {
11674                 ap = getParentOfAdminIfRequired(getProfileOwnerOrDeviceOwnerLocked(caller), parent);
11675             }
11676 
11677             if (disabled) {
11678                 ap.accountTypesWithManagementDisabled.add(accountType);
11679             } else {
11680                 ap.accountTypesWithManagementDisabled.remove(accountType);
11681             }
11682             saveSettingsLocked(UserHandle.getCallingUserId());
11683         }
11684     }
11685 
11686     @Override
11687     public String[] getAccountTypesWithManagementDisabled() {
11688         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId(), false);
11689     }
11690 
11691     @Override
11692     public String[] getAccountTypesWithManagementDisabledAsUser(int userId, boolean parent) {
11693         if (!mHasFeature) {
11694             return null;
11695         }
11696         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
11697 
11698         final CallerIdentity caller = getCallerIdentity();
11699         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
11700 
11701         synchronized (getLockObject()) {
11702             final ArraySet<String> resultSet = new ArraySet<>();
11703 
11704             if (!parent) {
11705                 final DevicePolicyData policy = getUserData(userId);
11706                 for (ActiveAdmin admin : policy.mAdminList) {
11707                     resultSet.addAll(admin.accountTypesWithManagementDisabled);
11708                 }
11709             }
11710 
11711             // Check if there's a profile owner of an org-owned device and the method is called for
11712             // the parent user of this profile owner.
11713             final ActiveAdmin orgOwnedAdmin =
11714                     getProfileOwnerOfOrganizationOwnedDeviceLocked(userId);
11715             final boolean shouldGetParentAccounts = orgOwnedAdmin != null && (parent
11716                     || UserHandle.getUserId(orgOwnedAdmin.getUid()) != userId);
11717             if (shouldGetParentAccounts) {
11718                 resultSet.addAll(
11719                         orgOwnedAdmin.getParentActiveAdmin().accountTypesWithManagementDisabled);
11720             }
11721             return resultSet.toArray(new String[resultSet.size()]);
11722         }
11723     }
11724 
11725     @Override
11726     public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
11727             boolean uninstallBlocked) {
11728         final CallerIdentity caller = getCallerIdentity(who, callerPackage);
11729         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
11730                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
11731                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_BLOCK_UNINSTALL)));
11732 
11733         final int userId = caller.getUserId();
11734         synchronized (getLockObject()) {
11735             long id = mInjector.binderClearCallingIdentity();
11736             try {
11737                 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
11738             } catch (RemoteException re) {
11739                 // Shouldn't happen.
11740                 Slogf.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
11741             } finally {
11742                 mInjector.binderRestoreCallingIdentity(id);
11743             }
11744         }
11745         if (uninstallBlocked) {
11746             final PackageManagerInternal pmi = mInjector.getPackageManagerInternal();
11747             pmi.removeNonSystemPackageSuspensions(packageName, userId);
11748             pmi.removeDistractingPackageRestrictions(packageName, userId);
11749             pmi.flushPackageRestrictions(userId);
11750         }
11751         DevicePolicyEventLogger
11752                 .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED)
11753                 .setAdmin(caller.getPackageName())
11754                 .setBoolean(/* isDelegate */ who == null)
11755                 .setStrings(packageName)
11756                 .write();
11757     }
11758 
11759     @Override
11760     public boolean isUninstallBlocked(ComponentName who, String packageName) {
11761         // This function should return true if and only if the package is blocked by
11762         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
11763         // when the package is a system app, or when it is an active device admin.
11764         final int userId = UserHandle.getCallingUserId();
11765 
11766         synchronized (getLockObject()) {
11767             //TODO: This is a silly access control check. Remove.
11768             if (who != null) {
11769                 final CallerIdentity caller = getCallerIdentity(who);
11770                 Preconditions.checkCallAuthorization(
11771                         isProfileOwner(caller) || isDeviceOwner(caller));
11772             }
11773             long id = mInjector.binderClearCallingIdentity();
11774             try {
11775                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
11776             } catch (RemoteException re) {
11777                 // Shouldn't happen.
11778                 Slogf.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
11779             } finally {
11780                 mInjector.binderRestoreCallingIdentity(id);
11781             }
11782         }
11783         return false;
11784     }
11785 
11786     @Override
11787     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
11788         if (!mHasFeature) {
11789             return;
11790         }
11791         Objects.requireNonNull(who, "ComponentName is null");
11792         final CallerIdentity caller = getCallerIdentity(who);
11793         Preconditions.checkCallAuthorization(isProfileOwner(caller));
11794 
11795         synchronized (getLockObject()) {
11796             ActiveAdmin admin = getProfileOwnerLocked(caller);
11797             if (admin.disableCallerId != disabled) {
11798                 admin.disableCallerId = disabled;
11799                 saveSettingsLocked(caller.getUserId());
11800             }
11801         }
11802         DevicePolicyEventLogger
11803                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALLER_ID_DISABLED)
11804                 .setAdmin(who)
11805                 .setBoolean(disabled)
11806                 .write();
11807     }
11808 
11809     @Override
11810     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
11811         if (!mHasFeature) {
11812             return false;
11813         }
11814         Objects.requireNonNull(who, "ComponentName is null");
11815         final CallerIdentity caller = getCallerIdentity(who);
11816         Preconditions.checkCallAuthorization(isProfileOwner(caller));
11817 
11818         synchronized (getLockObject()) {
11819             ActiveAdmin admin = getProfileOwnerLocked(caller);
11820             return admin.disableCallerId;
11821         }
11822     }
11823 
11824     @Override
11825     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
11826         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
11827 
11828         final CallerIdentity caller = getCallerIdentity();
11829         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
11830 
11831         synchronized (getLockObject()) {
11832             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
11833             return (admin != null) ? admin.disableCallerId : false;
11834         }
11835     }
11836 
11837     @Override
11838     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
11839         if (!mHasFeature) {
11840             return;
11841         }
11842         Objects.requireNonNull(who, "ComponentName is null");
11843         final CallerIdentity caller = getCallerIdentity(who);
11844         Preconditions.checkCallAuthorization(isProfileOwner(caller));
11845 
11846         synchronized (getLockObject()) {
11847             ActiveAdmin admin = getProfileOwnerLocked(caller);
11848             if (admin.disableContactsSearch != disabled) {
11849                 admin.disableContactsSearch = disabled;
11850                 saveSettingsLocked(caller.getUserId());
11851             }
11852         }
11853         DevicePolicyEventLogger
11854                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED)
11855                 .setAdmin(who)
11856                 .setBoolean(disabled)
11857                 .write();
11858     }
11859 
11860     @Override
11861     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
11862         if (!mHasFeature) {
11863             return false;
11864         }
11865         Objects.requireNonNull(who, "ComponentName is null");
11866         final CallerIdentity caller = getCallerIdentity(who);
11867         Preconditions.checkCallAuthorization(isProfileOwner(caller));
11868 
11869         synchronized (getLockObject()) {
11870             ActiveAdmin admin = getProfileOwnerLocked(caller);
11871             return admin.disableContactsSearch;
11872         }
11873     }
11874 
11875     @Override
11876     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
11877         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
11878 
11879         final CallerIdentity caller = getCallerIdentity();
11880         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
11881 
11882         synchronized (getLockObject()) {
11883             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
11884             return (admin != null) ? admin.disableContactsSearch : false;
11885         }
11886     }
11887 
11888     @Override
11889     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
11890             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
11891         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
11892                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
11893         final int callingUserId = UserHandle.getCallingUserId();
11894 
11895         mInjector.binderWithCleanCallingIdentity(() -> {
11896             synchronized (getLockObject()) {
11897                 final int managedUserId = getManagedUserId(callingUserId);
11898                 if (managedUserId < 0) {
11899                     return;
11900                 }
11901                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
11902                     if (VERBOSE_LOG) {
11903                         Slogf.v(LOG_TAG, "Cross-profile contacts access disabled for user %d",
11904                                 managedUserId);
11905                     }
11906                     return;
11907                 }
11908                 ContactsInternal.startQuickContactWithErrorToastForUser(
11909                         mContext, intent, new UserHandle(managedUserId));
11910             }
11911         });
11912     }
11913 
11914     /**
11915      * @return true if cross-profile QuickContact is disabled
11916      */
11917     private boolean isCrossProfileQuickContactDisabled(@UserIdInt int userId) {
11918         return getCrossProfileCallerIdDisabledForUser(userId)
11919                 && getCrossProfileContactsSearchDisabledForUser(userId);
11920     }
11921 
11922     /**
11923      * @return the user ID of the managed user that is linked to the current user, if any.
11924      * Otherwise -1.
11925      */
11926     public int getManagedUserId(@UserIdInt int callingUserId) {
11927         if (VERBOSE_LOG) Slogf.v(LOG_TAG, "getManagedUserId: callingUserId=%d", callingUserId);
11928 
11929         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
11930             if (ui.id == callingUserId || !ui.isManagedProfile()) {
11931                 continue; // Caller user self, or not a managed profile.  Skip.
11932             }
11933             if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Managed user=%d", ui.id);
11934             return ui.id;
11935         }
11936         if (VERBOSE_LOG)  Slogf.v(LOG_TAG, "Managed user not found.");
11937         return -1;
11938     }
11939 
11940     @Override
11941     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
11942         if (!mHasFeature) {
11943             return;
11944         }
11945         Objects.requireNonNull(who, "ComponentName is null");
11946 
11947         final CallerIdentity caller = getCallerIdentity(who);
11948         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
11949 
11950         synchronized (getLockObject()) {
11951             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
11952             if (admin.disableBluetoothContactSharing != disabled) {
11953                 admin.disableBluetoothContactSharing = disabled;
11954                 saveSettingsLocked(caller.getUserId());
11955             }
11956         }
11957         DevicePolicyEventLogger
11958                 .createEvent(DevicePolicyEnums.SET_BLUETOOTH_CONTACT_SHARING_DISABLED)
11959                 .setAdmin(who)
11960                 .setBoolean(disabled)
11961                 .write();
11962     }
11963 
11964     @Override
11965     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
11966         if (!mHasFeature) {
11967             return false;
11968         }
11969         Objects.requireNonNull(who, "ComponentName is null");
11970 
11971         final CallerIdentity caller = getCallerIdentity(who);
11972         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
11973 
11974         synchronized (getLockObject()) {
11975             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
11976             return admin.disableBluetoothContactSharing;
11977         }
11978     }
11979 
11980     @Override
11981     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
11982         // TODO: Should there be a check to make sure this relationship is
11983         // within a profile group?
11984         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
11985         synchronized (getLockObject()) {
11986             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
11987             return (admin != null) ? admin.disableBluetoothContactSharing : false;
11988         }
11989     }
11990 
11991     @Override
11992     public void setSecondaryLockscreenEnabled(ComponentName who, boolean enabled) {
11993         Objects.requireNonNull(who, "ComponentName is null");
11994 
11995         // Check can set secondary lockscreen enabled
11996         final CallerIdentity caller = getCallerIdentity(who);
11997         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
11998         Preconditions.checkCallAuthorization(!isManagedProfile(caller.getUserId()),
11999                 "User %d is not allowed to call setSecondaryLockscreenEnabled",
12000                         caller.getUserId());
12001 
12002         synchronized (getLockObject()) {
12003             // Allow testOnly admins to bypass supervision config requirement.
12004             Preconditions.checkCallAuthorization(isAdminTestOnlyLocked(who, caller.getUserId())
12005                     || isDefaultSupervisor(caller), "Admin %s is not the "
12006                     + "default supervision component", caller.getComponentName());
12007             DevicePolicyData policy = getUserData(caller.getUserId());
12008             policy.mSecondaryLockscreenEnabled = enabled;
12009             saveSettingsLocked(caller.getUserId());
12010         }
12011     }
12012 
12013     @Override
12014     public boolean isSecondaryLockscreenEnabled(@NonNull UserHandle userHandle) {
12015         synchronized (getLockObject()) {
12016             return getUserData(userHandle.getIdentifier()).mSecondaryLockscreenEnabled;
12017         }
12018     }
12019 
12020     private boolean isDefaultSupervisor(CallerIdentity caller) {
12021         final String supervisor = mContext.getResources().getString(
12022                 com.android.internal.R.string.config_defaultSupervisionProfileOwnerComponent);
12023         if (supervisor == null) {
12024             return false;
12025         }
12026         final ComponentName supervisorComponent = ComponentName.unflattenFromString(supervisor);
12027         return caller.getComponentName().equals(supervisorComponent);
12028     }
12029 
12030     @Override
12031     public void setPreferentialNetworkServiceEnabled(boolean enabled) {
12032         if (!mHasFeature) {
12033             return;
12034         }
12035         final CallerIdentity caller = getCallerIdentity();
12036         Preconditions.checkCallAuthorization(isProfileOwner(caller),
12037                 "Caller is not profile owner;"
12038                         + " only profile owner may control the preferntial network service");
12039         synchronized (getLockObject()) {
12040             final ActiveAdmin requiredAdmin = getProfileOwnerAdminLocked(
12041                     caller.getUserId());
12042             if (requiredAdmin != null
12043                     && requiredAdmin.mPreferentialNetworkServiceEnabled != enabled) {
12044                 requiredAdmin.mPreferentialNetworkServiceEnabled = enabled;
12045                 saveSettingsLocked(caller.getUserId());
12046             }
12047         }
12048         updateNetworkPreferenceForUser(caller.getUserId(), enabled);
12049         DevicePolicyEventLogger
12050                 .createEvent(DevicePolicyEnums.SET_PREFERENTIAL_NETWORK_SERVICE_ENABLED)
12051                 .setBoolean(enabled)
12052                 .write();
12053     }
12054 
12055     @Override
12056     public boolean isPreferentialNetworkServiceEnabled(int userHandle) {
12057         if (!mHasFeature) {
12058             return false;
12059         }
12060 
12061         final CallerIdentity caller = getCallerIdentity();
12062         Preconditions.checkCallAuthorization(isProfileOwner(caller),
12063                 "Caller is not profile owner");
12064         synchronized (getLockObject()) {
12065             final ActiveAdmin requiredAdmin = getProfileOwnerAdminLocked(userHandle);
12066             if (requiredAdmin != null) {
12067                 return requiredAdmin.mPreferentialNetworkServiceEnabled;
12068             } else {
12069                 return false;
12070             }
12071         }
12072     }
12073 
12074     @Override
12075     public void setLockTaskPackages(ComponentName who, String[] packages)
12076             throws SecurityException {
12077         Objects.requireNonNull(who, "ComponentName is null");
12078         Objects.requireNonNull(packages, "packages is null");
12079         final CallerIdentity caller = getCallerIdentity(who);
12080 
12081         synchronized (getLockObject()) {
12082             enforceCanCallLockTaskLocked(caller);
12083             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_PACKAGES);
12084             final int userHandle = caller.getUserId();
12085             setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
12086         }
12087     }
12088 
12089     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
12090         DevicePolicyData policy = getUserData(userHandle);
12091         policy.mLockTaskPackages = packages;
12092 
12093         // Store the settings persistently.
12094         saveSettingsLocked(userHandle);
12095         updateLockTaskPackagesLocked(packages, userHandle);
12096     }
12097 
12098     @Override
12099     public String[] getLockTaskPackages(ComponentName who) {
12100         Objects.requireNonNull(who, "ComponentName is null");
12101         final CallerIdentity caller = getCallerIdentity(who);
12102         final int userHandle = caller.getUserId();
12103 
12104         synchronized (getLockObject()) {
12105             enforceCanCallLockTaskLocked(caller);
12106             final List<String> packages = getUserData(userHandle).mLockTaskPackages;
12107             return packages.toArray(new String[packages.size()]);
12108         }
12109     }
12110 
12111     @Override
12112     public boolean isLockTaskPermitted(String pkg) {
12113         // Check policy-exempt apps first, as it doesn't require the lock
12114         if (listPolicyExemptAppsUnchecked().contains(pkg)) {
12115             if (VERBOSE_LOG) {
12116                 Slogf.v(LOG_TAG, "isLockTaskPermitted(%s): returning true for policy-exempt app",
12117                             pkg);
12118             }
12119             return true;
12120         }
12121 
12122         final int userId = mInjector.userHandleGetCallingUserId();
12123         synchronized (getLockObject()) {
12124             return getUserData(userId).mLockTaskPackages.contains(pkg);
12125         }
12126     }
12127 
12128     @Override
12129     public void setLockTaskFeatures(ComponentName who, int flags) {
12130         Objects.requireNonNull(who, "ComponentName is null");
12131 
12132         // Throw if Overview is used without Home.
12133         boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0;
12134         boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0;
12135         Preconditions.checkArgument(hasHome || !hasOverview,
12136                 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME");
12137         boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0;
12138         Preconditions.checkArgument(hasHome || !hasNotification,
12139             "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");
12140 
12141         final CallerIdentity caller = getCallerIdentity(who);
12142         final int userHandle = caller.getUserId();
12143         synchronized (getLockObject()) {
12144             enforceCanCallLockTaskLocked(caller);
12145             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOCK_TASK_FEATURES);
12146             setLockTaskFeaturesLocked(userHandle, flags);
12147         }
12148     }
12149 
12150     private void setLockTaskFeaturesLocked(int userHandle, int flags) {
12151         DevicePolicyData policy = getUserData(userHandle);
12152         policy.mLockTaskFeatures = flags;
12153         saveSettingsLocked(userHandle);
12154         updateLockTaskFeaturesLocked(flags, userHandle);
12155     }
12156 
12157     @Override
12158     public int getLockTaskFeatures(ComponentName who) {
12159         Objects.requireNonNull(who, "ComponentName is null");
12160         final CallerIdentity caller = getCallerIdentity(who);
12161         final int userHandle = caller.getUserId();
12162         synchronized (getLockObject()) {
12163             enforceCanCallLockTaskLocked(caller);
12164             return getUserData(userHandle).mLockTaskFeatures;
12165         }
12166     }
12167 
12168     private void maybeClearLockTaskPolicyLocked() {
12169         mInjector.binderWithCleanCallingIdentity(() -> {
12170             final List<UserInfo> userInfos = mUserManager.getAliveUsers();
12171             for (int i = userInfos.size() - 1; i >= 0; i--) {
12172                 int userId = userInfos.get(i).id;
12173                 if (canUserUseLockTaskLocked(userId)) {
12174                     continue;
12175                 }
12176 
12177                 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
12178                 if (!lockTaskPackages.isEmpty()) {
12179                     Slogf.d(LOG_TAG,
12180                             "User id " + userId + " not affiliated. Clearing lock task packages");
12181                     setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
12182                 }
12183                 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
12184                 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){
12185                     Slogf.d(LOG_TAG,
12186                             "User id " + userId + " not affiliated. Clearing lock task features");
12187                     setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
12188                 }
12189             }
12190         });
12191     }
12192 
12193     @Override
12194     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
12195         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
12196                 String.format(NOT_SYSTEM_CALLER_MSG, "call notifyLockTaskModeChanged"));
12197         synchronized (getLockObject()) {
12198             final DevicePolicyData policy = getUserData(userHandle);
12199 
12200             if (policy.mStatusBarDisabled) {
12201                 // Status bar is managed by LockTaskController during LockTask, so we cancel this
12202                 // policy when LockTask starts, and reapply it when LockTask ends
12203                 setStatusBarDisabledInternal(!isEnabled, userHandle);
12204             }
12205 
12206             Bundle adminExtras = new Bundle();
12207             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
12208             for (ActiveAdmin admin : policy.mAdminList) {
12209                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
12210                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
12211                 if (ownsDevice || ownsProfile) {
12212                     if (isEnabled) {
12213                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
12214                                 adminExtras, null);
12215                     } else {
12216                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
12217                     }
12218                     DevicePolicyEventLogger
12219                             .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED)
12220                             .setAdmin(admin.info.getPackageName())
12221                             .setBoolean(isEnabled)
12222                             .setStrings(pkg)
12223                             .write();
12224                 }
12225             }
12226         }
12227     }
12228 
12229     @Override
12230     public void setGlobalSetting(ComponentName who, String setting, String value) {
12231         Objects.requireNonNull(who, "ComponentName is null");
12232         final CallerIdentity caller = getCallerIdentity(who);
12233         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
12234 
12235         DevicePolicyEventLogger
12236                 .createEvent(DevicePolicyEnums.SET_GLOBAL_SETTING)
12237                 .setAdmin(who)
12238                 .setStrings(setting, value)
12239                 .write();
12240 
12241         synchronized (getLockObject()) {
12242             // Some settings are no supported any more. However we do not want to throw a
12243             // SecurityException to avoid breaking apps.
12244             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
12245                 Slogf.i(LOG_TAG, "Global setting no longer supported: %s", setting);
12246                 return;
12247             }
12248 
12249             if (!GLOBAL_SETTINGS_ALLOWLIST.contains(setting)
12250                     && !UserManager.isDeviceInDemoMode(mContext)) {
12251                 throw new SecurityException(String.format(
12252                         "Permission denial: device owners cannot update %1$s", setting));
12253             }
12254 
12255             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
12256                 // ignore if it contradicts an existing policy
12257                 long timeMs = getMaximumTimeToLock(
12258                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
12259                 if (timeMs > 0 && timeMs < Long.MAX_VALUE) {
12260                     return;
12261                 }
12262             }
12263 
12264             mInjector.binderWithCleanCallingIdentity(
12265                     () -> mInjector.settingsGlobalPutString(setting, value));
12266         }
12267     }
12268 
12269     @Override
12270     public void setSystemSetting(ComponentName who, String setting, String value) {
12271         Objects.requireNonNull(who, "ComponentName is null");
12272         Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
12273         final CallerIdentity caller = getCallerIdentity(who);
12274         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
12275         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_SETTING);
12276 
12277         synchronized (getLockObject()) {
12278             if (!SYSTEM_SETTINGS_ALLOWLIST.contains(setting)) {
12279                 throw new SecurityException(String.format(
12280                         "Permission denial: device owners cannot update %1$s", setting));
12281             }
12282 
12283             mInjector.binderWithCleanCallingIdentity(() ->
12284                     mInjector.settingsSystemPutStringForUser(setting, value, caller.getUserId()));
12285         }
12286     }
12287 
12288     @Override
12289     public void setConfiguredNetworksLockdownState(ComponentName who, boolean lockdown) {
12290         if (!mHasFeature) {
12291             return;
12292         }
12293         Preconditions.checkNotNull(who, "ComponentName is null");
12294 
12295         final CallerIdentity caller = getCallerIdentity(who);
12296         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
12297                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
12298 
12299         mInjector.binderWithCleanCallingIdentity(() ->
12300                 mInjector.settingsGlobalPutInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN,
12301                         lockdown ? 1 : 0));
12302 
12303         DevicePolicyEventLogger
12304                 .createEvent(DevicePolicyEnums.ALLOW_MODIFICATION_OF_ADMIN_CONFIGURED_NETWORKS)
12305                 .setAdmin(caller.getComponentName())
12306                 .setBoolean(lockdown)
12307                 .write();
12308     }
12309 
12310     @Override
12311     public boolean hasLockdownAdminConfiguredNetworks(ComponentName who) {
12312         if (!mHasFeature) {
12313             return false;
12314         }
12315         Preconditions.checkNotNull(who, "ComponentName is null");
12316 
12317         final CallerIdentity caller = getCallerIdentity(who);
12318         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
12319                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
12320 
12321         return mInjector.binderWithCleanCallingIdentity(() ->
12322                 mInjector.settingsGlobalGetInt(Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) > 0);
12323     }
12324 
12325     @Override
12326     public void setLocationEnabled(ComponentName who, boolean locationEnabled) {
12327         Preconditions.checkNotNull(who, "ComponentName is null");
12328 
12329         final CallerIdentity caller = getCallerIdentity(who);
12330         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
12331 
12332         UserHandle userHandle = caller.getUserHandle();
12333         if (mIsAutomotive && !locationEnabled) {
12334             Slogf.i(LOG_TAG, "setLocationEnabled(%s, %b): ignoring for user %s on automotive build",
12335                     who.flattenToShortString(), locationEnabled, userHandle);
12336             return;
12337         }
12338 
12339         mInjector.binderWithCleanCallingIdentity(() -> {
12340             boolean wasLocationEnabled = mInjector.getLocationManager().isLocationEnabledForUser(
12341                     userHandle);
12342             Slogf.v(LOG_TAG, "calling locationMgr.setLocationEnabledForUser(%b, %s) when it was %b",
12343                     locationEnabled, userHandle, wasLocationEnabled);
12344             mInjector.getLocationManager().setLocationEnabledForUser(locationEnabled, userHandle);
12345 
12346             // make a best effort to only show the notification if the admin is actually enabling
12347             // location. this is subject to race conditions with settings changes, but those are
12348             // unlikely to realistically interfere
12349             if (locationEnabled && !wasLocationEnabled) {
12350                 showLocationSettingsEnabledNotification(userHandle);
12351             }
12352         });
12353 
12354         DevicePolicyEventLogger
12355                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
12356                 .setAdmin(who)
12357                 .setStrings(Settings.Secure.LOCATION_MODE, Integer.toString(
12358                         locationEnabled ? Settings.Secure.LOCATION_MODE_ON
12359                                 : Settings.Secure.LOCATION_MODE_OFF))
12360                 .write();
12361     }
12362 
12363     private void showLocationSettingsEnabledNotification(UserHandle user) {
12364         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
12365                 .addFlags(FLAG_ACTIVITY_NEW_TASK);
12366         // Fill the component explicitly to prevent the PendingIntent from being intercepted
12367         // and fired with crafted target. b/155183624
12368         ActivityInfo targetInfo = intent.resolveActivityInfo(
12369                 mInjector.getPackageManager(user.getIdentifier()),
12370                 PackageManager.MATCH_SYSTEM_ONLY);
12371         if (targetInfo != null) {
12372             intent.setComponent(targetInfo.getComponentName());
12373         } else {
12374             Slogf.wtf(LOG_TAG, "Failed to resolve intent for location settings");
12375         }
12376 
12377         // Simple notification clicks are immutable
12378         PendingIntent locationSettingsIntent = mInjector.pendingIntentGetActivityAsUser(mContext, 0,
12379                 intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE, null,
12380                 user);
12381         Notification notification = new Notification.Builder(mContext,
12382                 SystemNotificationChannels.DEVICE_ADMIN)
12383                 .setSmallIcon(R.drawable.ic_info_outline)
12384                 .setContentTitle(mContext.getString(R.string.location_changed_notification_title))
12385                 .setContentText(mContext.getString(R.string.location_changed_notification_text))
12386                 .setColor(mContext.getColor(R.color.system_notification_accent_color))
12387                 .setShowWhen(true)
12388                 .setContentIntent(locationSettingsIntent)
12389                 .setAutoCancel(true)
12390                 .build();
12391         mInjector.getNotificationManager().notify(SystemMessage.NOTE_LOCATION_CHANGED,
12392                 notification);
12393     }
12394 
12395     @Override
12396     public boolean setTime(ComponentName who, long millis) {
12397         Objects.requireNonNull(who, "ComponentName is null");
12398 
12399         final CallerIdentity caller = getCallerIdentity(who);
12400         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
12401                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
12402 
12403         // Don't allow set time when auto time is on.
12404         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
12405             return false;
12406         }
12407         DevicePolicyEventLogger
12408                 .createEvent(DevicePolicyEnums.SET_TIME)
12409                 .setAdmin(caller.getComponentName())
12410                 .write();
12411         mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
12412         return true;
12413     }
12414 
12415     @Override
12416     public boolean setTimeZone(ComponentName who, String timeZone) {
12417         Objects.requireNonNull(who, "ComponentName is null");
12418 
12419         final CallerIdentity caller = getCallerIdentity(who);
12420         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
12421                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
12422 
12423         // Don't allow set timezone when auto timezone is on.
12424         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
12425             return false;
12426         }
12427         mInjector.binderWithCleanCallingIdentity(() ->
12428                 mInjector.getAlarmManager().setTimeZone(timeZone));
12429 
12430         DevicePolicyEventLogger
12431                 .createEvent(DevicePolicyEnums.SET_TIME_ZONE)
12432                 .setAdmin(caller.getComponentName())
12433                 .write();
12434         return true;
12435     }
12436 
12437     @Override
12438     public void setSecureSetting(ComponentName who, String setting, String value) {
12439         Objects.requireNonNull(who, "ComponentName is null");
12440         final CallerIdentity caller = getCallerIdentity(who);
12441         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
12442 
12443         int callingUserId = caller.getUserId();
12444         synchronized (getLockObject()) {
12445             if (isDeviceOwner(who, callingUserId)) {
12446                 if (!SECURE_SETTINGS_DEVICEOWNER_ALLOWLIST.contains(setting)
12447                         && !isCurrentUserDemo()) {
12448                     throw new SecurityException(String.format(
12449                             "Permission denial: Device owners cannot update %1$s", setting));
12450                 }
12451             } else if (!SECURE_SETTINGS_ALLOWLIST.contains(setting) && !isCurrentUserDemo()) {
12452                 throw new SecurityException(String.format(
12453                         "Permission denial: Profile owners cannot update %1$s", setting));
12454             }
12455             if (setting.equals(Settings.Secure.LOCATION_MODE)
12456                     && isSetSecureSettingLocationModeCheckEnabled(who.getPackageName(),
12457                     callingUserId)) {
12458                 throw new UnsupportedOperationException(Settings.Secure.LOCATION_MODE + " is "
12459                         + "deprecated. Please use setLocationEnabled() instead.");
12460             }
12461             if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
12462                 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
12463                     throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
12464                             + " is deprecated. Please use one of the user restrictions "
12465                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
12466                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY + " instead.");
12467                 }
12468                 if (!mUserManager.isManagedProfile(callingUserId)) {
12469                     Slogf.e(LOG_TAG, "Ignoring setSecureSetting request for "
12470                             + setting + ". User restriction "
12471                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
12472                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY
12473                             + " should be used instead.");
12474                 } else {
12475                     try {
12476                         setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
12477                                 (Integer.parseInt(value) == 0) ? true : false, /* parent */ false);
12478                         DevicePolicyEventLogger
12479                                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
12480                                 .setAdmin(who)
12481                                 .setStrings(setting, value)
12482                                 .write();
12483                     } catch (NumberFormatException exc) {
12484                         Slogf.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
12485                     }
12486                 }
12487                 return;
12488             }
12489             mInjector.binderWithCleanCallingIdentity(() -> {
12490                 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
12491                     final String currentValue = mInjector.settingsSecureGetStringForUser(
12492                             Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
12493                     if (!TextUtils.equals(currentValue, value)) {
12494                         // Tell the content observer that the next change will be due to the owner
12495                         // changing the value. There is a small race condition here that we cannot
12496                         // avoid: Change notifications are sent asynchronously, so it is possible
12497                         // that there are prior notifications queued up before the one we are about
12498                         // to trigger. This is a corner case that will have no impact in practice.
12499                         mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
12500                     }
12501                     getUserData(callingUserId).mCurrentInputMethodSet = true;
12502                     saveSettingsLocked(callingUserId);
12503                 }
12504                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
12505                 // Notify the user if it's the location mode setting that's been set, to any value
12506                 // other than 'off'.
12507                 if (setting.equals(Settings.Secure.LOCATION_MODE)
12508                         && (Integer.parseInt(value) != 0)) {
12509                     showLocationSettingsEnabledNotification(UserHandle.of(callingUserId));
12510                 }
12511             });
12512         }
12513         DevicePolicyEventLogger
12514                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
12515                 .setAdmin(who)
12516                 .setStrings(setting, value)
12517                 .write();
12518     }
12519 
12520     private boolean isSetSecureSettingLocationModeCheckEnabled(String packageName, int userId) {
12521         return mInjector.isChangeEnabled(USE_SET_LOCATION_ENABLED, packageName, userId);
12522     }
12523 
12524     @Override
12525     public void setMasterVolumeMuted(ComponentName who, boolean on) {
12526         Objects.requireNonNull(who, "ComponentName is null");
12527         final CallerIdentity caller = getCallerIdentity(who);
12528         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
12529         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_MASTER_VOLUME_MUTED);
12530 
12531         synchronized (getLockObject()) {
12532             setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on, /* parent */ false);
12533             DevicePolicyEventLogger
12534                     .createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED)
12535                     .setAdmin(who)
12536                     .setBoolean(on)
12537                     .write();
12538         }
12539     }
12540 
12541     @Override
12542     public boolean isMasterVolumeMuted(ComponentName who) {
12543         Objects.requireNonNull(who, "ComponentName is null");
12544         final CallerIdentity caller = getCallerIdentity(who);
12545         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
12546 
12547         synchronized (getLockObject()) {
12548             AudioManager audioManager =
12549                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
12550             return audioManager.isMasterMute();
12551         }
12552     }
12553 
12554     @Override
12555     public void setUserIcon(ComponentName who, Bitmap icon) {
12556         Objects.requireNonNull(who, "ComponentName is null");
12557         final CallerIdentity caller = getCallerIdentity(who);
12558         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
12559 
12560         synchronized (getLockObject()) {
12561             mInjector.binderWithCleanCallingIdentity(
12562                     () -> mUserManagerInternal.setUserIcon(caller.getUserId(), icon));
12563         }
12564         DevicePolicyEventLogger
12565                 .createEvent(DevicePolicyEnums.SET_USER_ICON)
12566                 .setAdmin(who)
12567                 .write();
12568     }
12569 
12570     @Override
12571     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
12572         Objects.requireNonNull(who, "ComponentName is null");
12573         final CallerIdentity caller = getCallerIdentity(who);
12574         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
12575 
12576         final int userId = caller.getUserId();
12577         synchronized (getLockObject()) {
12578             Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
12579                     String.format(
12580                             "Admin %s is neither the device owner or affiliated user's profile "
12581                                     + "owner.", who));
12582         }
12583         if (isManagedProfile(userId)) {
12584             throw new SecurityException("Managed profile cannot disable keyguard");
12585         }
12586         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_KEYGUARD_DISABLED);
12587 
12588         long ident = mInjector.binderClearCallingIdentity();
12589         try {
12590             // disallow disabling the keyguard if a password is currently set
12591             if (disabled && mLockPatternUtils.isSecure(userId)) {
12592                 return false;
12593             }
12594             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
12595             if (disabled) {
12596                 mInjector
12597                         .getIWindowManager()
12598                         .dismissKeyguard(null /* callback */, null /* message */);
12599             }
12600             DevicePolicyEventLogger
12601                     .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED)
12602                     .setAdmin(who)
12603                     .setBoolean(disabled)
12604                     .write();
12605         } catch (RemoteException e) {
12606             // Same process, does not happen.
12607         } finally {
12608             mInjector.binderRestoreCallingIdentity(ident);
12609         }
12610         return true;
12611     }
12612 
12613     @Override
12614     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
12615         final CallerIdentity caller = getCallerIdentity(who);
12616         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
12617 
12618         int userId = caller.getUserId();
12619         synchronized (getLockObject()) {
12620             Preconditions.checkCallAuthorization(isUserAffiliatedWithDeviceLocked(userId),
12621                     "Admin " + who
12622                             + " is neither the device owner or affiliated user's profile owner.");
12623             if (isManagedProfile(userId)) {
12624                 throw new SecurityException("Managed profile cannot disable status bar");
12625             }
12626             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_STATUS_BAR_DISABLED);
12627 
12628             DevicePolicyData policy = getUserData(userId);
12629             if (policy.mStatusBarDisabled != disabled) {
12630                 boolean isLockTaskMode = false;
12631                 try {
12632                     isLockTaskMode = mInjector.getIActivityTaskManager().getLockTaskModeState()
12633                             != LOCK_TASK_MODE_NONE;
12634                 } catch (RemoteException e) {
12635                     Slogf.e(LOG_TAG, "Failed to get LockTask mode");
12636                 }
12637                 if (!isLockTaskMode) {
12638                     if (!setStatusBarDisabledInternal(disabled, userId)) {
12639                         return false;
12640                     }
12641                 }
12642                 policy.mStatusBarDisabled = disabled;
12643                 saveSettingsLocked(userId);
12644             }
12645         }
12646         DevicePolicyEventLogger
12647                 .createEvent(DevicePolicyEnums.SET_STATUS_BAR_DISABLED)
12648                 .setAdmin(who)
12649                 .setBoolean(disabled)
12650                 .write();
12651         return true;
12652     }
12653 
12654     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
12655         long ident = mInjector.binderClearCallingIdentity();
12656         try {
12657             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
12658                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
12659             if (statusBarService != null) {
12660                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
12661                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
12662                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
12663                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
12664                 return true;
12665             }
12666         } catch (RemoteException e) {
12667             Slogf.e(LOG_TAG, "Failed to disable the status bar", e);
12668         } finally {
12669             mInjector.binderRestoreCallingIdentity(ident);
12670         }
12671         return false;
12672     }
12673 
12674     /**
12675      * We need to update the internal state of whether a user has completed setup or a
12676      * device has paired once. After that, we ignore any changes that reset the
12677      * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
12678      * as we don't trust any apps that might try to reset them.
12679      * <p>
12680      * Unfortunately, we don't know which user's setup state was changed, so we write all of
12681      * them.
12682      */
12683     void updateUserSetupCompleteAndPaired() {
12684         List<UserInfo> users = mUserManager.getAliveUsers();
12685         final int N = users.size();
12686         for (int i = 0; i < N; i++) {
12687             int userHandle = users.get(i).id;
12688             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
12689                     userHandle) != 0) {
12690                 DevicePolicyData policy = getUserData(userHandle);
12691                 if (!policy.mUserSetupComplete) {
12692                     policy.mUserSetupComplete = true;
12693                     if (userHandle == UserHandle.USER_SYSTEM) {
12694                         mStateCache.setDeviceProvisioned(true);
12695                     }
12696                     synchronized (getLockObject()) {
12697                         saveSettingsLocked(userHandle);
12698                     }
12699                 }
12700             }
12701             if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
12702                     userHandle) != 0) {
12703                 DevicePolicyData policy = getUserData(userHandle);
12704                 if (!policy.mPaired) {
12705                     policy.mPaired = true;
12706                     synchronized (getLockObject()) {
12707                         saveSettingsLocked(userHandle);
12708                     }
12709                 }
12710             }
12711         }
12712     }
12713 
12714     private class SetupContentObserver extends ContentObserver {
12715         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
12716                 Settings.Secure.USER_SETUP_COMPLETE);
12717         private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
12718                 Settings.Global.DEVICE_PROVISIONED);
12719         private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
12720         private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
12721                 Settings.Secure.DEFAULT_INPUT_METHOD);
12722 
12723         @GuardedBy("getLockObject()")
12724         private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
12725 
12726         public SetupContentObserver(Handler handler) {
12727             super(handler);
12728         }
12729 
12730         void register() {
12731             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
12732             mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
12733             if (mIsWatch) {
12734                 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
12735             }
12736             mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
12737         }
12738 
12739         @GuardedBy("getLockObject()")
12740         private void addPendingChangeByOwnerLocked(int userId) {
12741             mUserIdsWithPendingChangesByOwner.add(userId);
12742         }
12743 
12744         @Override
12745         public void onChange(boolean selfChange, Uri uri, int userId) {
12746             if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
12747                 updateUserSetupCompleteAndPaired();
12748             } else if (mDeviceProvisioned.equals(uri)) {
12749                 synchronized (getLockObject()) {
12750                     // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
12751                     // is delayed until device is marked as provisioned.
12752                     setDeviceOwnershipSystemPropertyLocked();
12753                 }
12754             } else if (mDefaultImeChanged.equals(uri)) {
12755                 synchronized (getLockObject()) {
12756                     if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
12757                         // This change notification was triggered by the owner changing the current
12758                         // IME. Ignore it.
12759                         mUserIdsWithPendingChangesByOwner.remove(userId);
12760                     } else {
12761                         // This change notification was triggered by the user manually changing the
12762                         // current IME.
12763                         getUserData(userId).mCurrentInputMethodSet = false;
12764                         saveSettingsLocked(userId);
12765                     }
12766                 }
12767             }
12768         }
12769     }
12770 
12771     private class DevicePolicyConstantsObserver extends ContentObserver {
12772         final Uri mConstantsUri =
12773                 Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS);
12774 
12775         DevicePolicyConstantsObserver(Handler handler) {
12776             super(handler);
12777         }
12778 
12779         void register() {
12780             mInjector.registerContentObserver(
12781                     mConstantsUri, /* notifyForDescendents= */ false, this, UserHandle.USER_ALL);
12782         }
12783 
12784         @Override
12785         public void onChange(boolean selfChange, Uri uri, int userId) {
12786             mConstants = loadConstants();
12787 
12788             mInjector.binderWithCleanCallingIdentity(() -> {
12789                 final Intent intent = new Intent(
12790                         DevicePolicyManager.ACTION_DEVICE_POLICY_CONSTANTS_CHANGED);
12791                 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12792                 final List<UserInfo> users = mUserManager.getAliveUsers();
12793                 for (int i = 0; i < users.size(); i++) {
12794                     mContext.sendBroadcastAsUser(intent, UserHandle.of(users.get(i).id));
12795                 }
12796             });
12797         }
12798     }
12799 
12800     @VisibleForTesting
12801     final class LocalService extends DevicePolicyManagerInternal
12802             implements DevicePolicyManagerLiteInternal {
12803         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
12804 
12805         @Override
12806         public List<String> getCrossProfileWidgetProviders(int profileId) {
12807             synchronized (getLockObject()) {
12808                 if (mOwners == null) {
12809                     return Collections.emptyList();
12810                 }
12811                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
12812                 if (ownerComponent == null) {
12813                     return Collections.emptyList();
12814                 }
12815 
12816                 DevicePolicyData policy = getUserDataUnchecked(profileId);
12817                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
12818 
12819                 if (admin == null || admin.crossProfileWidgetProviders == null
12820                         || admin.crossProfileWidgetProviders.isEmpty()) {
12821                     return Collections.emptyList();
12822                 }
12823 
12824                 return admin.crossProfileWidgetProviders;
12825             }
12826         }
12827 
12828         @Override
12829         public void addOnCrossProfileWidgetProvidersChangeListener(
12830                 OnCrossProfileWidgetProvidersChangeListener listener) {
12831             synchronized (getLockObject()) {
12832                 if (mWidgetProviderListeners == null) {
12833                     mWidgetProviderListeners = new ArrayList<>();
12834                 }
12835                 if (!mWidgetProviderListeners.contains(listener)) {
12836                     mWidgetProviderListeners.add(listener);
12837                 }
12838             }
12839         }
12840 
12841         @Override
12842         public @Nullable ComponentName getProfileOwnerOrDeviceOwnerSupervisionComponent(
12843                 @NonNull UserHandle userHandle) {
12844             return DevicePolicyManagerService.this.getProfileOwnerOrDeviceOwnerSupervisionComponent(
12845                     userHandle);
12846         }
12847 
12848         @Override
12849         public boolean isActiveDeviceOwner(int uid) {
12850             return isDeviceOwner(new CallerIdentity(uid, null, null));
12851         }
12852 
12853         @Override
12854         public boolean isActiveProfileOwner(int uid) {
12855             return isProfileOwner(new CallerIdentity(uid, null, null));
12856         }
12857 
12858         @Override
12859         public boolean isActiveSupervisionApp(int uid) {
12860             if (!isProfileOwner(new CallerIdentity(uid, null, null))) {
12861                 return false;
12862             }
12863             synchronized (getLockObject()) {
12864                 final ActiveAdmin admin = getProfileOwnerAdminLocked(UserHandle.getUserId(uid));
12865                 if (admin == null) {
12866                     return false;
12867                 }
12868 
12869                 final String supervisionString = mContext.getResources().getString(
12870                         com.android.internal.R.string
12871                                 .config_defaultSupervisionProfileOwnerComponent);
12872                 if (supervisionString == null) {
12873                     return false;
12874                 }
12875 
12876                 final ComponentName supervisorComponent = ComponentName.unflattenFromString(
12877                         supervisionString);
12878                 return admin.info.getComponent().equals(supervisorComponent);
12879             }
12880         }
12881 
12882         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
12883             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
12884             synchronized (getLockObject()) {
12885                 listeners = new ArrayList<>(mWidgetProviderListeners);
12886             }
12887             final int listenerCount = listeners.size();
12888             for (int i = 0; i < listenerCount; i++) {
12889                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
12890                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
12891             }
12892         }
12893 
12894         @Override
12895         public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
12896             // This method is called from AM with its lock held, so don't take the DPMS lock.
12897             // b/29242568
12898 
12899             if (getEnforcingAdminAndUserDetailsInternal(userId, null) != null
12900                     || useDefaultIfNoAdmin) {
12901                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(userId);
12902             }
12903             return null;
12904         }
12905 
12906         @Override
12907         public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
12908             Intent intent = null;
12909             if (getEnforcingAdminAndUserDetailsInternal(userId, userRestriction) != null) {
12910                 intent = DevicePolicyManagerService.this.createShowAdminSupportIntent(userId);
12911                 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, userRestriction);
12912             }
12913             return intent;
12914         }
12915 
12916         @Override
12917         public boolean isUserAffiliatedWithDevice(int userId) {
12918             return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
12919         }
12920 
12921         @Override
12922         public boolean canSilentlyInstallPackage(String callerPackage, int callerUid) {
12923             if (callerPackage == null) {
12924                 return false;
12925             }
12926             if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid))
12927                     && (isActiveProfileOwner(callerUid)
12928                         || isActiveDeviceOwner(callerUid))) {
12929                 // device owner or a profile owner affiliated with the device owner
12930                 return true;
12931             }
12932             return false;
12933         }
12934 
12935         @Override
12936         public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) {
12937             mInjector.binderWithCleanCallingIdentity(() -> {
12938                 synchronized (getLockObject()) {
12939                     updateMaximumTimeToLockLocked(userId);
12940                     updatePasswordQualityCacheForUserGroup(userId);
12941                 }
12942             });
12943             DevicePolicyEventLogger
12944                     .createEvent(DevicePolicyEnums.SEPARATE_PROFILE_CHALLENGE_CHANGED)
12945                     .setBoolean(isSeparateProfileChallengeEnabled(userId))
12946                     .write();
12947         }
12948 
12949         @Override
12950         public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) {
12951             synchronized (getLockObject()) {
12952                 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING,
12953                         UserHandle.of(userId))) {
12954                     Slogf.e(LOG_TAG, "printing is enabled for user %d", userId);
12955                     return null;
12956                 }
12957                 String ownerPackage = mOwners.getProfileOwnerPackage(userId);
12958                 if (ownerPackage == null) {
12959                     ownerPackage = mOwners.getDeviceOwnerPackageName();
12960                 }
12961                 final String packageName = ownerPackage;
12962                 PackageManager pm = mInjector.getPackageManager();
12963                 PackageInfo packageInfo = mInjector.binderWithCleanCallingIdentity(() -> {
12964                     try {
12965                         return pm.getPackageInfo(packageName, 0);
12966                     } catch (NameNotFoundException e) {
12967                         Slogf.e(LOG_TAG, "getPackageInfo error", e);
12968                         return null;
12969                     }
12970                 });
12971                 if (packageInfo == null) {
12972                     Slogf.e(LOG_TAG, "packageInfo is inexplicably null");
12973                     return null;
12974                 }
12975                 ApplicationInfo appInfo = packageInfo.applicationInfo;
12976                 if (appInfo == null) {
12977                     Slogf.e(LOG_TAG, "appInfo is inexplicably null");
12978                     return null;
12979                 }
12980                 CharSequence appLabel = pm.getApplicationLabel(appInfo);
12981                 if (appLabel == null) {
12982                     Slogf.e(LOG_TAG, "appLabel is inexplicably null");
12983                     return null;
12984                 }
12985                 return ((Context) ActivityThread.currentActivityThread().getSystemUiContext())
12986                         .getResources().getString(R.string.printing_disabled_by, appLabel);
12987             }
12988         }
12989 
12990         @Override
12991         protected DevicePolicyCache getDevicePolicyCache() {
12992             return mPolicyCache;
12993         }
12994 
12995         @Override
12996         protected DeviceStateCache getDeviceStateCache() {
12997             return mStateCache;
12998         }
12999 
13000         @Override
13001         public List<String> getAllCrossProfilePackages() {
13002             return DevicePolicyManagerService.this.getAllCrossProfilePackages();
13003         }
13004 
13005         @Override
13006         public List<String> getDefaultCrossProfilePackages() {
13007             return DevicePolicyManagerService.this.getDefaultCrossProfilePackages();
13008         }
13009 
13010         /**
13011          * Sends the {@code intent} to the packages with cross profile capabilities.
13012          *
13013          * <p>This means the application must have the {@code crossProfile} property and
13014          * and at least one of the following permissions:
13015          *
13016          * <ul>
13017          *     <li>{@link android.Manifest.permission.INTERACT_ACROSS_PROFILES}
13018          *     <li>{@link android.Manifest.permission.INTERACT_ACROSS_USERS}
13019          *     <li>{@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission or the
13020          *     {@link AppOpsManager.OP_INTERACT_ACROSS_PROFILES} app operation authorization.
13021          * </ul>
13022          *
13023          * <p>Note: The intent itself is not modified but copied before use.
13024          *
13025          * @param intent Template for the intent sent to the packages.
13026          * @param parentHandle Handle of the user that will receive the intents.
13027          * @param requiresPermission If false, all packages with the {@code crossProfile} property
13028          *                           will receive the intent.
13029          */
13030         @Override
13031         public void broadcastIntentToCrossProfileManifestReceiversAsUser(Intent intent,
13032                 UserHandle parentHandle, boolean requiresPermission) {
13033             Objects.requireNonNull(intent);
13034             Objects.requireNonNull(parentHandle);
13035             final int userId = parentHandle.getIdentifier();
13036             Slogf.i(LOG_TAG, "Sending %s broadcast to manifest receivers.", intent.getAction());
13037             try {
13038                 final List<ResolveInfo> receivers = mIPackageManager.queryIntentReceivers(
13039                         intent, /* resolvedType= */ null,
13040                         STOCK_PM_FLAGS, parentHandle.getIdentifier()).getList();
13041                 for (ResolveInfo receiver : receivers) {
13042                     final String packageName = receiver.getComponentInfo().packageName;
13043                     if (checkCrossProfilePackagePermissions(packageName, userId,
13044                             requiresPermission)
13045                             || checkModifyQuietModePermission(packageName, userId)) {
13046                         Slogf.i(LOG_TAG, "Sending %s broadcast to %s.", intent.getAction(),
13047                                 packageName);
13048                         final Intent packageIntent = new Intent(intent)
13049                                 .setComponent(receiver.getComponentInfo().getComponentName())
13050                                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
13051                         mContext.sendBroadcastAsUser(packageIntent, parentHandle);
13052                     }
13053                 }
13054             } catch (RemoteException ex) {
13055                 Slogf.w(LOG_TAG, "Cannot get list of broadcast receivers for %s because: %s.",
13056                         intent.getAction(), ex);
13057             }
13058         }
13059 
13060         /**
13061          * Checks whether the package {@code packageName} has the {@code MODIFY_QUIET_MODE}
13062          * permission granted for the user {@code userId}.
13063          */
13064         private boolean checkModifyQuietModePermission(String packageName, @UserIdInt int userId) {
13065             try {
13066                 final int uid = Objects.requireNonNull(
13067                         mInjector.getPackageManager().getApplicationInfoAsUser(
13068                                 Objects.requireNonNull(packageName), /* flags= */ 0, userId)).uid;
13069                 return PackageManager.PERMISSION_GRANTED
13070                         == ActivityManager.checkComponentPermission(
13071                         android.Manifest.permission.MODIFY_QUIET_MODE, uid, /* owningUid= */
13072                         -1, /* exported= */ true);
13073             } catch (NameNotFoundException ex) {
13074                 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
13075                         packageName);
13076                 return false;
13077             }
13078         }
13079 
13080         /**
13081          * Checks whether the package {@code packageName} has the required permissions to receive
13082          * cross-profile broadcasts on behalf of the user {@code userId}.
13083          */
13084         private boolean checkCrossProfilePackagePermissions(String packageName,
13085                 @UserIdInt int userId, boolean requiresPermission) {
13086             final PackageManagerInternal pmInternal = LocalServices.getService(
13087                     PackageManagerInternal.class);
13088             final AndroidPackage androidPackage = pmInternal.getPackage(packageName);
13089             if (androidPackage == null || !androidPackage.isCrossProfile()) {
13090                 return false;
13091             }
13092             if (!requiresPermission) {
13093                 return true;
13094             }
13095             if (!isPackageEnabled(packageName, userId)) {
13096                 return false;
13097             }
13098             try {
13099                 final CrossProfileAppsInternal crossProfileAppsService = LocalServices.getService(
13100                         CrossProfileAppsInternal.class);
13101                 return crossProfileAppsService.verifyPackageHasInteractAcrossProfilePermission(
13102                         packageName, userId);
13103             } catch (NameNotFoundException ex) {
13104                 Slogf.w(LOG_TAG, "Cannot find the package %s to check for permissions.",
13105                         packageName);
13106                 return false;
13107             }
13108         }
13109 
13110         private boolean isPackageEnabled(String packageName, @UserIdInt int userId) {
13111             final int callingUid = Binder.getCallingUid();
13112             final long ident = Binder.clearCallingIdentity();
13113             try {
13114                 final PackageInfo info = mInjector.getPackageManagerInternal()
13115                         .getPackageInfo(
13116                                 packageName,
13117                                 MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
13118                                 callingUid,
13119                                 userId);
13120                 return info != null && info.applicationInfo.enabled;
13121             } finally {
13122                 Binder.restoreCallingIdentity(ident);
13123             }
13124         }
13125 
13126         @Override
13127         public ComponentName getProfileOwnerAsUser(@UserIdInt int userId) {
13128             return DevicePolicyManagerService.this.getProfileOwnerAsUser(userId);
13129         }
13130 
13131         @Override
13132         public int getDeviceOwnerUserId() {
13133             return DevicePolicyManagerService.this.getDeviceOwnerUserId();
13134         }
13135 
13136         @Override
13137         public boolean isDeviceOrProfileOwnerInCallingUser(String packageName) {
13138             return isDeviceOwnerInCallingUser(packageName)
13139                     || isProfileOwnerInCallingUser(packageName);
13140         }
13141 
13142         private boolean isDeviceOwnerInCallingUser(String packageName) {
13143             final ComponentName deviceOwnerInCallingUser =
13144                     DevicePolicyManagerService.this.getDeviceOwnerComponent(
13145                             /* callingUserOnly= */ true);
13146             return deviceOwnerInCallingUser != null
13147                     && packageName.equals(deviceOwnerInCallingUser.getPackageName());
13148         }
13149 
13150         private boolean isProfileOwnerInCallingUser(String packageName) {
13151             final ComponentName profileOwnerInCallingUser =
13152                     getProfileOwnerAsUser(UserHandle.getCallingUserId());
13153             return profileOwnerInCallingUser != null
13154                     && packageName.equals(profileOwnerInCallingUser.getPackageName());
13155         }
13156 
13157         @Override
13158         public boolean supportsResetOp(int op) {
13159             return op == AppOpsManager.OP_INTERACT_ACROSS_PROFILES
13160                     && LocalServices.getService(CrossProfileAppsInternal.class) != null;
13161         }
13162 
13163         @Override
13164         public void resetOp(int op, String packageName, @UserIdInt int userId) {
13165             if (op != AppOpsManager.OP_INTERACT_ACROSS_PROFILES) {
13166                 throw new IllegalArgumentException("Unsupported op for DPM reset: " + op);
13167             }
13168             LocalServices.getService(CrossProfileAppsInternal.class)
13169                     .setInteractAcrossProfilesAppOp(
13170                             packageName, findInteractAcrossProfilesResetMode(packageName), userId);
13171         }
13172 
13173         @Override
13174         public void notifyUnsafeOperationStateChanged(DevicePolicySafetyChecker checker, int reason,
13175                 boolean isSafe) {
13176             // TODO(b/178494483): use EventLog instead
13177             // TODO(b/178494483): log metrics?
13178             if (VERBOSE_LOG) {
13179                 Slogf.v(LOG_TAG, "notifyUnsafeOperationStateChanged(): %s=%b",
13180                         DevicePolicyManager.operationSafetyReasonToString(reason), isSafe);
13181             }
13182             Preconditions.checkArgument(mSafetyChecker == checker,
13183                     "invalid checker: should be %s, was %s", mSafetyChecker, checker);
13184 
13185             Bundle extras = new Bundle();
13186             extras.putInt(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_REASON, reason);
13187             extras.putBoolean(DeviceAdminReceiver.EXTRA_OPERATION_SAFETY_STATE, isSafe);
13188 
13189             if (mOwners.hasDeviceOwner()) {
13190                 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying DO");
13191                 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED,
13192                         extras);
13193             }
13194             for (int profileOwnerId : mOwners.getProfileOwnerKeys()) {
13195                 if (VERBOSE_LOG) Slogf.v(LOG_TAG, "Notifying PO for user " + profileOwnerId);
13196                 sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_OPERATION_SAFETY_STATE_CHANGED,
13197                         extras, profileOwnerId);
13198             }
13199         }
13200 
13201         private @Mode int findInteractAcrossProfilesResetMode(String packageName) {
13202             return getDefaultCrossProfilePackages().contains(packageName)
13203                     ? AppOpsManager.MODE_ALLOWED
13204                     : AppOpsManager.opToDefaultMode(AppOpsManager.OP_INTERACT_ACROSS_PROFILES);
13205         }
13206     }
13207 
13208     private Intent createShowAdminSupportIntent(int userId) {
13209         // This method is called with AMS lock held, so don't take DPMS lock
13210         final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
13211         intent.putExtra(Intent.EXTRA_USER_ID, userId);
13212         intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
13213         return intent;
13214     }
13215 
13216     /**
13217      * @param restriction The restriction enforced by admin. It could be any user restriction or
13218      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA},
13219      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE} and  {@link
13220      *                    DevicePolicyManager#POLICY_SUSPEND_PACKAGES}.
13221      */
13222     private Bundle getEnforcingAdminAndUserDetailsInternal(int userId, String restriction) {
13223         Bundle result = null;
13224 
13225         // For POLICY_SUSPEND_PACKAGES return PO or DO to keep the behavior same as
13226         // before the bug fix for b/192245204.
13227         if (restriction == null || DevicePolicyManager.POLICY_SUSPEND_PACKAGES.equals(
13228                 restriction)) {
13229             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
13230             if (profileOwner != null) {
13231                 result = new Bundle();
13232                 result.putInt(Intent.EXTRA_USER_ID, userId);
13233                 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
13234                         profileOwner);
13235                 return result;
13236             }
13237             final Pair<Integer, ComponentName> deviceOwner =
13238                     mOwners.getDeviceOwnerUserIdAndComponent();
13239             if (deviceOwner != null && deviceOwner.first == userId) {
13240                 result = new Bundle();
13241                 result.putInt(Intent.EXTRA_USER_ID, userId);
13242                 result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
13243                         deviceOwner.second);
13244                 return result;
13245             }
13246         } else if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)
13247                 || DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
13248             synchronized (getLockObject()) {
13249                 final DevicePolicyData policy = getUserData(userId);
13250                 final int N = policy.mAdminList.size();
13251                 for (int i = 0; i < N; i++) {
13252                     final ActiveAdmin admin = policy.mAdminList.get(i);
13253                     if ((admin.disableCamera &&
13254                             DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction))
13255                             || (admin.disableScreenCapture && DevicePolicyManager
13256                             .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) {
13257                         result = new Bundle();
13258                         result.putInt(Intent.EXTRA_USER_ID, userId);
13259                         result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
13260                                 admin.info.getComponent());
13261                         return result;
13262                     }
13263                 }
13264                 // For the camera, a device owner on a different user can disable it globally,
13265                 // so we need an additional check.
13266                 if (result == null
13267                         && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
13268                     final ActiveAdmin admin = getDeviceOwnerAdminLocked();
13269                     if (admin != null && admin.disableCamera) {
13270                         result = new Bundle();
13271                         result.putInt(Intent.EXTRA_USER_ID, mOwners.getDeviceOwnerUserId());
13272                         result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
13273                                 admin.info.getComponent());
13274                         return result;
13275                     }
13276                 }
13277             }
13278         } else {
13279             long ident = mInjector.binderClearCallingIdentity();
13280             try {
13281                 List<UserManager.EnforcingUser> sources = mUserManager
13282                         .getUserRestrictionSources(restriction, UserHandle.of(userId));
13283                 if (sources == null) {
13284                     // The restriction is not enforced.
13285                     return null;
13286                 }
13287                 int sizeBefore = sources.size();
13288                 if (sizeBefore > 1) {
13289                     Slogf.d(LOG_TAG, "getEnforcingAdminAndUserDetailsInternal(%d, %s): "
13290                             + "%d sources found, excluding those set by UserManager",
13291                             userId, restriction, sizeBefore);
13292                     sources = getDevicePolicySources(sources);
13293                 }
13294                 if (sources.isEmpty()) {
13295                     // The restriction is not enforced (or is just enforced by the system)
13296                     return null;
13297                 }
13298 
13299                 if (sources.size() > 1) {
13300                     // In this case, we'll show an admin support dialog that does not
13301                     // specify the admin.
13302                     // TODO(b/128928355): if this restriction is enforced by multiple DPCs, return
13303                     // the admin for the calling user.
13304                     Slogf.w(LOG_TAG, "getEnforcingAdminAndUserDetailsInternal(%d, %s): multiple "
13305                             + "sources for restriction %s on user %d", restriction, userId);
13306                     result = new Bundle();
13307                     result.putInt(Intent.EXTRA_USER_ID, userId);
13308                     return result;
13309                 }
13310                 final UserManager.EnforcingUser enforcingUser = sources.get(0);
13311                 final int sourceType = enforcingUser.getUserRestrictionSource();
13312                 final int enforcingUserId = enforcingUser.getUserHandle().getIdentifier();
13313                 if (sourceType == UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) {
13314                     // Restriction was enforced by PO
13315                     final ComponentName profileOwner = mOwners.getProfileOwnerComponent(
13316                             enforcingUserId);
13317                     if (profileOwner != null) {
13318                         result = new Bundle();
13319                         result.putInt(Intent.EXTRA_USER_ID, enforcingUserId);
13320                         result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
13321                                 profileOwner);
13322                         return result;
13323                     }
13324                 } else if (sourceType == UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) {
13325                     // Restriction was enforced by DO
13326                     final Pair<Integer, ComponentName> deviceOwner =
13327                             mOwners.getDeviceOwnerUserIdAndComponent();
13328                     if (deviceOwner != null) {
13329                         result = new Bundle();
13330                         result.putInt(Intent.EXTRA_USER_ID, deviceOwner.first);
13331                         result.putParcelable(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
13332                                 deviceOwner.second);
13333                         return result;
13334                     }
13335                 } else if (sourceType == UserManager.RESTRICTION_SOURCE_SYSTEM) {
13336                     /*
13337                      * In this case, the user restriction is enforced by the system.
13338                      * So we won't show an admin support intent, even if it is also
13339                      * enforced by a profile/device owner.
13340                      */
13341                     return null;
13342                 }
13343             } finally {
13344                 mInjector.binderRestoreCallingIdentity(ident);
13345             }
13346         }
13347         return null;
13348     }
13349 
13350     /**
13351      *  Excludes restrictions imposed by UserManager.
13352      */
13353     private List<UserManager.EnforcingUser> getDevicePolicySources(
13354             List<UserManager.EnforcingUser> sources) {
13355         int sizeBefore = sources.size();
13356         List<UserManager.EnforcingUser> realSources = new ArrayList<>(sizeBefore);
13357         for (int i = 0; i < sizeBefore; i++) {
13358             UserManager.EnforcingUser source = sources.get(i);
13359             int type = source.getUserRestrictionSource();
13360             if (type != UserManager.RESTRICTION_SOURCE_PROFILE_OWNER
13361                     && type != UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) {
13362                 // TODO(b/128928355): add unit test
13363                 Slogf.d(LOG_TAG, "excluding source of type %s at index %d",
13364                         userRestrictionSourceToString(type), i);
13365                 continue;
13366             }
13367             realSources.add(source);
13368         }
13369         return realSources;
13370     }
13371 
13372     private static String userRestrictionSourceToString(@UserRestrictionSource int source) {
13373         return DebugUtils.flagsToString(UserManager.class, "RESTRICTION_", source);
13374     }
13375 
13376     /**
13377      * @param restriction The restriction enforced by admin. It could be any user restriction or
13378      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
13379      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
13380      * @return Details of admin and user which enforced the restriction for the userId.
13381      */
13382     @Override
13383     public Bundle getEnforcingAdminAndUserDetails(int userId, String restriction) {
13384         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()));
13385         return getEnforcingAdminAndUserDetailsInternal(userId, restriction);
13386     }
13387 
13388     /**
13389      * @param restriction The restriction enforced by admin. It could be any user restriction or
13390      *                    policy like {@link DevicePolicyManager#POLICY_DISABLE_CAMERA} and
13391      *                    {@link DevicePolicyManager#POLICY_DISABLE_SCREEN_CAPTURE}.
13392      */
13393     @Override
13394     public Intent createAdminSupportIntent(String restriction) {
13395         Objects.requireNonNull(restriction);
13396         final CallerIdentity caller = getCallerIdentity();
13397         final int userId = caller.getUserId();
13398         Intent intent = null;
13399         if (getEnforcingAdminAndUserDetailsInternal(userId, restriction) != null) {
13400             intent = createShowAdminSupportIntent(userId);
13401             intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
13402         }
13403         return intent;
13404     }
13405 
13406     /**
13407      * Returns true if specified admin is allowed to limit passwords and has a
13408      * {@code mPasswordPolicy.quality} of at least {@code minPasswordQuality}
13409      */
13410     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
13411         if (admin.mPasswordPolicy.quality < minPasswordQuality) {
13412             return false;
13413         }
13414         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
13415     }
13416 
13417     @Override
13418     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
13419         if (policy != null) {
13420             // throws exception if policy type is invalid
13421             policy.validateType();
13422             // throws exception if freeze period is invalid
13423             policy.validateFreezePeriods();
13424             Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
13425             // throws exception if freeze period is incompatible with previous freeze period record
13426             policy.validateAgainstPreviousFreezePeriod(record.first, record.second,
13427                     LocalDate.now());
13428         }
13429         final CallerIdentity caller = getCallerIdentity(who);
13430 
13431         synchronized (getLockObject()) {
13432             Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller)
13433                     || isDeviceOwner(caller));
13434             checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_SYSTEM_UPDATE_POLICY);
13435 
13436             if (policy == null) {
13437                 mOwners.clearSystemUpdatePolicy();
13438             } else {
13439                 mOwners.setSystemUpdatePolicy(policy);
13440                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false);
13441             }
13442             mOwners.writeDeviceOwner();
13443         }
13444         mInjector.binderWithCleanCallingIdentity(() -> mContext.sendBroadcastAsUser(
13445                 new Intent(ACTION_SYSTEM_UPDATE_POLICY_CHANGED), UserHandle.SYSTEM));
13446         DevicePolicyEventLogger
13447                 .createEvent(DevicePolicyEnums.SET_SYSTEM_UPDATE_POLICY)
13448                 .setAdmin(who)
13449                 .setInt(policy != null ? policy.getPolicyType() : 0)
13450                 .write();
13451     }
13452 
13453     @Override
13454     public SystemUpdatePolicy getSystemUpdatePolicy() {
13455         synchronized (getLockObject()) {
13456             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
13457             if (policy != null && !policy.isValid()) {
13458                 Slogf.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
13459                 return null;
13460             }
13461             return policy;
13462         }
13463     }
13464 
13465     private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) {
13466         return (!date.isBefore(range.first) && !date.isAfter(range.second));
13467     }
13468 
13469     /**
13470      * keeps track of the last continuous period when the system is under OTA freeze.
13471      *
13472      * DPMS keeps track of the previous dates during which OTA was freezed as a result of an
13473      * system update policy with freeze periods in effect. This is needed to make robust
13474      * validation on new system update polices, for example to prevent the OTA from being
13475      * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period
13476      * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting
13477      * a new freeze period after a few days.
13478      *
13479      * @param saveIfChanged whether to persist the result on disk if freeze period record is
13480      *            updated. This should only be set to {@code false} if there is a guaranteed
13481      *            mOwners.writeDeviceOwner() later in the control flow to reduce the number of
13482      *            disk writes. Otherwise you risk inconsistent on-disk state.
13483      *
13484      * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod
13485      */
13486     private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) {
13487         Slogf.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord");
13488         synchronized (getLockObject()) {
13489             final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
13490             if (policy == null) {
13491                 return;
13492             }
13493             final LocalDate now = LocalDate.now();
13494             final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now);
13495             if (currentPeriod == null) {
13496                 return;
13497             }
13498             final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
13499             final LocalDate start = record.first;
13500             final LocalDate end = record.second;
13501             final boolean changed;
13502             if (end == null || start == null) {
13503                 // Start a new period if there is none at the moment
13504                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
13505             } else if (now.equals(end.plusDays(1))) {
13506                 // Extend the existing period
13507                 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
13508             } else if (now.isAfter(end.plusDays(1))) {
13509                 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) {
13510                     // The device might be off for some period. If the past freeze record
13511                     // is within range of the current freeze period, assume the device was off
13512                     // during the period [end, now] and extend the freeze record to [start, now].
13513                     changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
13514                 } else {
13515                     changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
13516                 }
13517             } else if (now.isBefore(start)) {
13518                 // Systm clock was adjusted backwards, restart record
13519                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
13520             } else /* start <= now <= end */ {
13521                 changed = false;
13522             }
13523             if (changed && saveIfChanged) {
13524                 mOwners.writeDeviceOwner();
13525             }
13526         }
13527     }
13528 
13529     @Override
13530     public void clearSystemUpdatePolicyFreezePeriodRecord() {
13531         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
13532                         || hasCallingOrSelfPermission(permission.CLEAR_FREEZE_PERIOD),
13533                 "Caller must be shell, or hold CLEAR_FREEZE_PERIOD permission to call "
13534                         + "clearSystemUpdatePolicyFreezePeriodRecord");
13535         synchronized (getLockObject()) {
13536             // Print out current record to help diagnosed CTS failures
13537             Slogf.i(LOG_TAG, "Clear freeze period record: "
13538                     + mOwners.getSystemUpdateFreezePeriodRecordAsString());
13539             if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) {
13540                 mOwners.writeDeviceOwner();
13541             }
13542         }
13543     }
13544 
13545     /**
13546      * Checks if any of the packages associated with the UID of the app provided is that
13547      * of the device owner.
13548      * @param appUid UID of the app to check.
13549      * @return {@code true} if any of the packages are the device owner, {@code false} otherwise.
13550      */
13551     private boolean isUidDeviceOwnerLocked(int appUid) {
13552         ensureLocked();
13553         final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
13554                 .getPackageName();
13555         try {
13556             String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(appUid);
13557             if (pkgs == null) {
13558                 return false;
13559             }
13560 
13561             for (String pkg : pkgs) {
13562                 if (deviceOwnerPackageName.equals(pkg)) {
13563                     return true;
13564                 }
13565             }
13566         } catch (RemoteException e) {
13567             return false;
13568         }
13569         return false;
13570     }
13571 
13572     @Override
13573     public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
13574         Preconditions.checkCallAuthorization(
13575                 hasCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE),
13576                 "Only the system update service can broadcast update information");
13577 
13578         if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
13579             Slogf.w(LOG_TAG, "Only the system update service in the system user can broadcast "
13580                     + "update information.");
13581             return;
13582         }
13583 
13584         if (!mOwners.saveSystemUpdateInfo(info)) {
13585             // Pending system update hasn't changed, don't send duplicate notification.
13586             return;
13587         }
13588 
13589         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
13590                 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
13591                         info == null ? -1 : info.getReceivedTime());
13592 
13593         mInjector.binderWithCleanCallingIdentity(() -> {
13594             synchronized (getLockObject()) {
13595                 // Broadcast to device owner first if there is one.
13596                 if (mOwners.hasDeviceOwner()) {
13597                     final UserHandle deviceOwnerUser =
13598                             UserHandle.of(mOwners.getDeviceOwnerUserId());
13599                     intent.setComponent(mOwners.getDeviceOwnerComponent());
13600                     mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
13601                 }
13602             }
13603             // Get running users.
13604             final int runningUserIds[];
13605             try {
13606                 runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
13607             } catch (RemoteException e) {
13608                 // Shouldn't happen.
13609                 Slogf.e(LOG_TAG, "Could not retrieve the list of running users", e);
13610                 return;
13611             }
13612             // Send broadcasts to corresponding profile owners if any.
13613             for (final int userId : runningUserIds) {
13614                 synchronized (getLockObject()) {
13615                     final ComponentName profileOwnerPackage =
13616                             mOwners.getProfileOwnerComponent(userId);
13617                     if (profileOwnerPackage != null) {
13618                         intent.setComponent(profileOwnerPackage);
13619                         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
13620                     }
13621                 }
13622             }
13623         });
13624     }
13625 
13626     @Override
13627     public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
13628         Objects.requireNonNull(admin, "ComponentName is null");
13629 
13630         final CallerIdentity caller = getCallerIdentity(admin);
13631         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
13632 
13633         return mOwners.getSystemUpdateInfo();
13634     }
13635 
13636     @Override
13637     public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) {
13638         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
13639         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13640                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
13641                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT)));
13642         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_POLICY);
13643 
13644         final int forUser = caller.getUserId();
13645         synchronized (getLockObject()) {
13646             DevicePolicyData userPolicy = getUserData(forUser);
13647             if (userPolicy.mPermissionPolicy != policy) {
13648                 userPolicy.mPermissionPolicy = policy;
13649                 mPolicyCache.setPermissionPolicy(forUser, policy);
13650                 saveSettingsLocked(forUser);
13651             }
13652         }
13653         DevicePolicyEventLogger
13654                 .createEvent(DevicePolicyEnums.SET_PERMISSION_POLICY)
13655                 .setAdmin(caller.getPackageName())
13656                 .setInt(policy)
13657                 .setBoolean(/* isDelegate */ admin == null)
13658                 .write();
13659     }
13660 
13661     private void updatePermissionPolicyCache(int userId) {
13662         synchronized (getLockObject()) {
13663             DevicePolicyData userPolicy = getUserData(userId);
13664             mPolicyCache.setPermissionPolicy(userId, userPolicy.mPermissionPolicy);
13665         }
13666     }
13667 
13668     @Override
13669     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
13670         int userId = UserHandle.getCallingUserId();
13671         return mPolicyCache.getPermissionPolicy(userId);
13672     }
13673 
13674     @Override
13675     public void setPermissionGrantState(ComponentName admin, String callerPackage,
13676             String packageName, String permission, int grantState, RemoteCallback callback)
13677             throws RemoteException {
13678         Objects.requireNonNull(callback);
13679 
13680         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
13681         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
13682                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
13683                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT)));
13684         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_PERMISSION_GRANT_STATE);
13685 
13686         synchronized (getLockObject()) {
13687             long ident = mInjector.binderClearCallingIdentity();
13688             try {
13689                 boolean isPostQAdmin = getTargetSdk(caller.getPackageName(), caller.getUserId())
13690                         >= android.os.Build.VERSION_CODES.Q;
13691                 if (!isPostQAdmin) {
13692                     // Legacy admins assume that they cannot control pre-M apps
13693                     if (getTargetSdk(packageName, caller.getUserId())
13694                             < android.os.Build.VERSION_CODES.M) {
13695                         callback.sendResult(null);
13696                         return;
13697                     }
13698                 }
13699                 try {
13700                     if (!isRuntimePermission(permission)) {
13701                         callback.sendResult(null);
13702                         return;
13703                     }
13704                 } catch (NameNotFoundException e) {
13705                     throw new RemoteException("Cannot check if " + permission
13706                             + "is a runtime permission", e, false, true);
13707                 }
13708 
13709                 if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
13710                         || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED
13711                         || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
13712                     AdminPermissionControlParams permissionParams =
13713                             new AdminPermissionControlParams(packageName, permission, grantState,
13714                                     canAdminGrantSensorsPermissionsForUser(caller.getUserId()));
13715                     mInjector.getPermissionControllerManager(caller.getUserHandle())
13716                             .setRuntimePermissionGrantStateByDeviceAdmin(caller.getPackageName(),
13717                                     permissionParams, mContext.getMainExecutor(),
13718                                     (permissionWasSet) -> {
13719                                         if (isPostQAdmin && !permissionWasSet) {
13720                                             callback.sendResult(null);
13721                                             return;
13722                                         }
13723 
13724                                         DevicePolicyEventLogger
13725                                                 .createEvent(DevicePolicyEnums
13726                                                         .SET_PERMISSION_GRANT_STATE)
13727                                                 .setAdmin(caller.getPackageName())
13728                                                 .setStrings(permission)
13729                                                 .setInt(grantState)
13730                                                 .setBoolean(/* isDelegate */ admin == null)
13731                                                 .write();
13732 
13733                                         callback.sendResult(Bundle.EMPTY);
13734                                     });
13735                 }
13736             } catch (SecurityException e) {
13737                 Slogf.e(LOG_TAG, "Could not set permission grant state", e);
13738 
13739                 callback.sendResult(null);
13740             } finally {
13741                 mInjector.binderRestoreCallingIdentity(ident);
13742             }
13743         }
13744     }
13745 
13746     @Override
13747     public int getPermissionGrantState(ComponentName admin, String callerPackage,
13748             String packageName, String permission) throws RemoteException {
13749         final CallerIdentity caller = getCallerIdentity(admin, callerPackage);
13750         Preconditions.checkCallAuthorization(isSystemUid(caller) || (caller.hasAdminComponent()
13751                 && (isProfileOwner(caller) || isDeviceOwner(caller)))
13752                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_PERMISSION_GRANT)));
13753 
13754         synchronized (getLockObject()) {
13755             return mInjector.binderWithCleanCallingIdentity(() -> {
13756                 int granted;
13757                 if (getTargetSdk(caller.getPackageName(), caller.getUserId())
13758                         < android.os.Build.VERSION_CODES.Q) {
13759                     // The per-Q behavior was to not check the app-ops state.
13760                     granted = mIPackageManager.checkPermission(permission, packageName,
13761                             caller.getUserId());
13762                 } else {
13763                     try {
13764                         int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
13765                                 caller.getUserId());
13766                         if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
13767                                 PermissionChecker.PID_UNKNOWN, uid, packageName)
13768                                         != PermissionChecker.PERMISSION_GRANTED) {
13769                             granted = PackageManager.PERMISSION_DENIED;
13770                         } else {
13771                             granted = PackageManager.PERMISSION_GRANTED;
13772                         }
13773                     } catch (NameNotFoundException e) {
13774                         throw new RemoteException("Cannot check if " + permission
13775                                 + "is a runtime permission", e, false, true);
13776                     }
13777                 }
13778                 int permFlags = mInjector.getPackageManager().getPermissionFlags(
13779                         permission, packageName, caller.getUserHandle());
13780                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
13781                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
13782                     // Not controlled by policy
13783                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
13784                 } else {
13785                     // Policy controlled so return result based on permission grant state
13786                     return granted == PackageManager.PERMISSION_GRANTED
13787                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
13788                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
13789                 }
13790             });
13791         }
13792     }
13793 
13794     boolean isPackageInstalledForUser(String packageName, int userHandle) {
13795         return mInjector.binderWithCleanCallingIdentity(() -> {
13796             try {
13797                 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
13798                         userHandle);
13799                 return (pi != null) && (pi.applicationInfo.flags != 0);
13800             } catch (RemoteException re) {
13801                 throw new RuntimeException("Package manager has died", re);
13802             }
13803         });
13804     }
13805 
13806     public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
13807         final PackageManager packageManager = mInjector.getPackageManager();
13808         PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
13809         return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
13810                 == PermissionInfo.PROTECTION_DANGEROUS;
13811     }
13812 
13813     @Override
13814     public boolean isProvisioningAllowed(String action, String packageName) {
13815         Objects.requireNonNull(packageName);
13816 
13817         final CallerIdentity caller = getCallerIdentity();
13818         final long ident = mInjector.binderClearCallingIdentity();
13819         try {
13820             final List<String> callerUidPackageNames = Arrays.asList(
13821                     mInjector.getPackageManager().getPackagesForUid(caller.getUid()));
13822             Preconditions.checkArgument(callerUidPackageNames.contains(packageName),
13823                     "Caller uid doesn't match the one for the provided package.");
13824         } finally {
13825             mInjector.binderRestoreCallingIdentity(ident);
13826         }
13827 
13828         return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
13829     }
13830 
13831     @Override
13832     public int checkProvisioningPreCondition(String action, String packageName) {
13833         Objects.requireNonNull(packageName, "packageName is null");
13834 
13835         Preconditions.checkCallAuthorization(
13836                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
13837 
13838         return checkProvisioningPreConditionSkipPermission(action, packageName);
13839     }
13840 
13841     private int checkProvisioningPreConditionSkipPermission(String action,
13842             String packageName) {
13843         if (!mHasFeature) {
13844             logMissingFeatureAction("Cannot check provisioning for action " + action);
13845             return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
13846         }
13847         if (!isProvisioningAllowed()) {
13848             return CODE_PROVISIONING_NOT_ALLOWED_FOR_NON_DEVELOPER_USERS;
13849         }
13850         final int code = checkProvisioningPreConditionSkipPermissionNoLog(action, packageName);
13851         if (code != CODE_OK) {
13852             Slogf.d(LOG_TAG, "checkProvisioningPreCondition(" + action + ", " + packageName
13853                     + ") failed: "
13854                     + computeProvisioningErrorString(code, mInjector.userHandleGetCallingUserId()));
13855         }
13856         return code;
13857     }
13858 
13859     /**
13860      *  Checks if provisioning is allowed during regular usage (non-developer/CTS). This could
13861      *  return {@code false} if the device has an overlaid config value set to false. If not set,
13862      *  the default is true.
13863      */
13864     private boolean isProvisioningAllowed() {
13865         boolean isDeveloperMode = isDeveloperMode(mContext);
13866         boolean isProvisioningAllowedForNormalUsers = SystemProperties.getBoolean(
13867                 ALLOW_USER_PROVISIONING_KEY, /* defValue= */ true);
13868 
13869         return isDeveloperMode || isProvisioningAllowedForNormalUsers;
13870     }
13871 
13872     private static boolean isDeveloperMode(Context context) {
13873         return Global.getInt(context.getContentResolver(), Global.ADB_ENABLED, 0) > 0;
13874     }
13875 
13876     private int checkProvisioningPreConditionSkipPermissionNoLog(String action,
13877             String packageName) {
13878         final int callingUserId = mInjector.userHandleGetCallingUserId();
13879         if (action != null) {
13880             switch (action) {
13881                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
13882                     return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
13883                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
13884                 case DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE:
13885                     return checkDeviceOwnerProvisioningPreCondition(callingUserId);
13886             }
13887         }
13888         throw new IllegalArgumentException("Unknown provisioning action " + action);
13889     }
13890 
13891     /**
13892      * The device owner can only be set before the setup phase of the primary user has completed,
13893      * except for adb command if no accounts or additional users are present on the device.
13894      */
13895     private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
13896             @UserIdInt int deviceOwnerUserId, @UserIdInt int callingUserId, boolean isAdb,
13897             boolean hasIncompatibleAccountsOrNonAdb) {
13898         if (mOwners.hasDeviceOwner()) {
13899             return CODE_HAS_DEVICE_OWNER;
13900         }
13901         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
13902             return CODE_USER_HAS_PROFILE_OWNER;
13903         }
13904 
13905         boolean isHeadlessSystemUserMode = mInjector.userManagerIsHeadlessSystemUserMode();
13906         // System user is always running in headless system user mode.
13907         if (!isHeadlessSystemUserMode
13908                 && !mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
13909             return CODE_USER_NOT_RUNNING;
13910         }
13911         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
13912             return CODE_HAS_PAIRED;
13913         }
13914 
13915         if (isHeadlessSystemUserMode) {
13916             if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
13917                 Slogf.e(LOG_TAG, "In headless system user mode, "
13918                         + "device owner can only be set on headless system user.");
13919                 return CODE_NOT_SYSTEM_USER;
13920             }
13921         }
13922 
13923         if (isAdb) {
13924             // If shell command runs after user setup completed check device status. Otherwise, OK.
13925             if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
13926                 // In non-headless system user mode, DO can be setup only if
13927                 // there's no non-system user.
13928                 // In headless system user mode, DO can be setup only if there are
13929                 // two users: the headless system user and the foreground user.
13930                 // If there could be multiple foreground users, this constraint should be modified.
13931 
13932                 int maxNumberOfExistingUsers = isHeadlessSystemUserMode ? 2 : 1;
13933                 if (mUserManager.getUserCount() > maxNumberOfExistingUsers) {
13934                     return CODE_NONSYSTEM_USER_EXISTS;
13935                 }
13936 
13937                 int currentForegroundUser = getCurrentForegroundUserId();
13938                 if (callingUserId != currentForegroundUser
13939                         && mInjector.userManagerIsHeadlessSystemUserMode()
13940                         && currentForegroundUser == UserHandle.USER_SYSTEM) {
13941                     Slogf.wtf(LOG_TAG, "In headless system user mode, "
13942                             + "current user cannot be system user when setting device owner");
13943                     return CODE_SYSTEM_USER;
13944                 }
13945                 if (hasIncompatibleAccountsOrNonAdb) {
13946                     return CODE_ACCOUNTS_NOT_EMPTY;
13947                 }
13948             }
13949             return CODE_OK;
13950         } else {
13951             // DO has to be user 0
13952             if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
13953                 return CODE_NOT_SYSTEM_USER;
13954             }
13955             // Only provision DO before setup wizard completes
13956             if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
13957                 return CODE_USER_SETUP_COMPLETED;
13958             }
13959             return CODE_OK;
13960         }
13961     }
13962 
13963     private int checkDeviceOwnerProvisioningPreCondition(@UserIdInt int callingUserId) {
13964         synchronized (getLockObject()) {
13965             final int deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode()
13966                     ? UserHandle.USER_SYSTEM
13967                     : callingUserId;
13968             Slogf.i(LOG_TAG, "Calling user %d, device owner will be set on user %d",
13969                     callingUserId, deviceOwnerUserId);
13970             // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
13971             return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
13972                     deviceOwnerUserId, callingUserId, /* isAdb= */ false,
13973                     /* hasIncompatibleAccountsOrNonAdb=*/ true);
13974         }
13975     }
13976 
13977     private int checkManagedProfileProvisioningPreCondition(String packageName,
13978             @UserIdInt int callingUserId) {
13979         if (!hasFeatureManagedUsers()) {
13980             return CODE_MANAGED_USERS_NOT_SUPPORTED;
13981         }
13982         if (getProfileOwnerAsUser(callingUserId) != null) {
13983             // Managed user cannot have a managed profile.
13984             return CODE_USER_HAS_PROFILE_OWNER;
13985         }
13986 
13987         final long ident = mInjector.binderClearCallingIdentity();
13988         try {
13989             final UserHandle callingUserHandle = UserHandle.of(callingUserId);
13990             final boolean hasDeviceOwner;
13991             synchronized (getLockObject()) {
13992                 hasDeviceOwner = getDeviceOwnerAdminLocked() != null;
13993             }
13994 
13995             final boolean addingProfileRestricted = mUserManager.hasUserRestriction(
13996                     UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserHandle);
13997 
13998             if (mUserManager.getUserInfo(callingUserId).isProfile()) {
13999                 Slogf.i(LOG_TAG, "Calling user %d is a profile, cannot add another.",
14000                         callingUserId);
14001                 // The check is called from inside a managed profile. A managed profile cannot
14002                 // be provisioned from within another managed profile.
14003                 return CODE_CANNOT_ADD_MANAGED_PROFILE;
14004             }
14005 
14006             // If there's a device owner, the restriction on adding a managed profile must be set.
14007             if (hasDeviceOwner && !addingProfileRestricted) {
14008                 Slogf.wtf(LOG_TAG, "Has a device owner but no restriction on adding a profile.");
14009             }
14010 
14011             // Do not allow adding a managed profile if there's a restriction.
14012             if (addingProfileRestricted) {
14013                 Slogf.i(LOG_TAG, "Adding a profile is restricted: User %s Has device owner? %b",
14014                         callingUserHandle, hasDeviceOwner);
14015                 return CODE_CANNOT_ADD_MANAGED_PROFILE;
14016             }
14017 
14018             // Bail out if we are trying to provision a work profile but one already exists.
14019             if (!mUserManager.canAddMoreManagedProfiles(
14020                     callingUserId, /* allowedToRemoveOne= */ false)) {
14021                 Slogf.i(LOG_TAG, "A work profile already exists.");
14022                 return CODE_CANNOT_ADD_MANAGED_PROFILE;
14023             }
14024         } finally {
14025             mInjector.binderRestoreCallingIdentity(ident);
14026         }
14027         return CODE_OK;
14028     }
14029 
14030     private void checkIsDeviceOwner(CallerIdentity caller) {
14031         Preconditions.checkCallAuthorization(isDeviceOwner(caller), caller.getUid()
14032                 + " is not device owner");
14033     }
14034 
14035     /**
14036      * Return device owner or profile owner set on a given user.
14037      */
14038     private @Nullable ComponentName getOwnerComponent(int userId) {
14039         synchronized (getLockObject()) {
14040             if (mOwners.getDeviceOwnerUserId() == userId) {
14041                 return mOwners.getDeviceOwnerComponent();
14042             }
14043             if (mOwners.hasProfileOwner(userId)) {
14044                 return mOwners.getProfileOwnerComponent(userId);
14045             }
14046         }
14047         return null;
14048     }
14049 
14050     private boolean hasFeatureManagedUsers() {
14051         try {
14052             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
14053         } catch (RemoteException e) {
14054             return false;
14055         }
14056     }
14057 
14058     @Override
14059     public String getWifiMacAddress(ComponentName admin) {
14060         Objects.requireNonNull(admin, "ComponentName is null");
14061 
14062         final CallerIdentity caller = getCallerIdentity(admin);
14063         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
14064                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
14065 
14066         return mInjector.binderWithCleanCallingIdentity(() -> {
14067             String[] macAddresses = mInjector.getWifiManager().getFactoryMacAddresses();
14068             if (macAddresses == null) {
14069                 return null;
14070             }
14071             DevicePolicyEventLogger
14072                     .createEvent(DevicePolicyEnums.GET_WIFI_MAC_ADDRESS)
14073                     .setAdmin(caller.getComponentName())
14074                     .write();
14075             return macAddresses.length > 0 ? macAddresses[0] : null;
14076         });
14077     }
14078 
14079     /**
14080      * Returns the target sdk version number that the given packageName was built for
14081      * in the given user.
14082      */
14083     private int getTargetSdk(String packageName, int userId) {
14084         final ApplicationInfo ai;
14085         try {
14086             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
14087             return ai == null ? 0 : ai.targetSdkVersion;
14088         } catch (RemoteException e) {
14089             // Shouldn't happen
14090             return 0;
14091         }
14092     }
14093 
14094     @Override
14095     public boolean isManagedProfile(ComponentName admin) {
14096         Objects.requireNonNull(admin, "ComponentName is null");
14097 
14098         final CallerIdentity caller = getCallerIdentity(admin);
14099         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
14100 
14101         return isManagedProfile(caller.getUserId());
14102     }
14103 
14104     @Override
14105     public void reboot(ComponentName admin) {
14106         Objects.requireNonNull(admin, "ComponentName is null");
14107         final CallerIdentity caller = getCallerIdentity(admin);
14108         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
14109         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_REBOOT);
14110         mInjector.binderWithCleanCallingIdentity(() -> {
14111             // Make sure there are no ongoing calls on the device.
14112             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
14113                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
14114             }
14115             DevicePolicyEventLogger
14116                     .createEvent(DevicePolicyEnums.REBOOT)
14117                     .setAdmin(admin)
14118                     .write();
14119             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
14120         });
14121     }
14122 
14123     @Override
14124     public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
14125         if (!mHasFeature) {
14126             return;
14127         }
14128         Objects.requireNonNull(who, "ComponentName is null");
14129         final CallerIdentity caller = getCallerIdentity(who);
14130         synchronized (getLockObject()) {
14131             ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
14132             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
14133                 admin.shortSupportMessage = message;
14134                 saveSettingsLocked(caller.getUserId());
14135             }
14136         }
14137         DevicePolicyEventLogger
14138                 .createEvent(DevicePolicyEnums.SET_SHORT_SUPPORT_MESSAGE)
14139                 .setAdmin(who)
14140                 .write();
14141     }
14142 
14143     @Override
14144     public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
14145         if (!mHasFeature) {
14146             return null;
14147         }
14148         Objects.requireNonNull(who, "ComponentName is null");
14149         final CallerIdentity caller = getCallerIdentity(who);
14150         synchronized (getLockObject()) {
14151             ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
14152             return admin.shortSupportMessage;
14153         }
14154     }
14155 
14156     @Override
14157     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
14158         if (!mHasFeature) {
14159             return;
14160         }
14161         Objects.requireNonNull(who, "ComponentName is null");
14162         final CallerIdentity caller = getCallerIdentity(who);
14163         synchronized (getLockObject()) {
14164             ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
14165             if (!TextUtils.equals(admin.longSupportMessage, message)) {
14166                 admin.longSupportMessage = message;
14167                 saveSettingsLocked(caller.getUserId());
14168             }
14169         }
14170         DevicePolicyEventLogger
14171                 .createEvent(DevicePolicyEnums.SET_LONG_SUPPORT_MESSAGE)
14172                 .setAdmin(who)
14173                 .write();
14174     }
14175 
14176     @Override
14177     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
14178         if (!mHasFeature) {
14179             return null;
14180         }
14181         Objects.requireNonNull(who, "ComponentName is null");
14182         final CallerIdentity caller = getCallerIdentity(who);
14183         synchronized (getLockObject()) {
14184             ActiveAdmin admin = getActiveAdminForUidLocked(who, caller.getUid());
14185             return admin.longSupportMessage;
14186         }
14187     }
14188 
14189     @Override
14190     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
14191         if (!mHasFeature) {
14192             return null;
14193         }
14194         Objects.requireNonNull(who, "ComponentName is null");
14195         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
14196                 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user"));
14197 
14198         synchronized (getLockObject()) {
14199             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
14200             if (admin != null) {
14201                 return admin.shortSupportMessage;
14202             }
14203         }
14204         return null;
14205     }
14206 
14207     @Override
14208     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
14209         if (!mHasFeature) {
14210             return null;
14211         }
14212         Objects.requireNonNull(who, "ComponentName is null");
14213         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
14214                 String.format(NOT_SYSTEM_CALLER_MSG, "query support message for user"));
14215 
14216         synchronized (getLockObject()) {
14217             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
14218             if (admin != null) {
14219                 return admin.longSupportMessage;
14220             }
14221         }
14222         return null;
14223     }
14224 
14225     @Override
14226     public void setOrganizationColor(@NonNull ComponentName who, int color) {
14227         if (!mHasFeature) {
14228             return;
14229         }
14230         Objects.requireNonNull(who, "ComponentName is null");
14231 
14232         final CallerIdentity caller = getCallerIdentity(who);
14233         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
14234 
14235         synchronized (getLockObject()) {
14236             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
14237             admin.organizationColor = color;
14238             saveSettingsLocked(caller.getUserId());
14239         }
14240         DevicePolicyEventLogger
14241                 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_COLOR)
14242                 .setAdmin(caller.getComponentName())
14243                 .write();
14244     }
14245 
14246     @Override
14247     public void setOrganizationColorForUser(int color, int userId) {
14248         if (!mHasFeature) {
14249             return;
14250         }
14251         Preconditions.checkArgumentNonnegative(userId, "Invalid userId");
14252 
14253         final CallerIdentity caller = getCallerIdentity();
14254         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userId));
14255         Preconditions.checkCallAuthorization(canManageUsers(caller));
14256         Preconditions.checkCallAuthorization(isManagedProfile(userId), "You can not "
14257                 + "set organization color outside a managed profile, userId = %d", userId);
14258 
14259         synchronized (getLockObject()) {
14260             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
14261             admin.organizationColor = color;
14262             saveSettingsLocked(userId);
14263         }
14264     }
14265 
14266     @Override
14267     public int getOrganizationColor(@NonNull ComponentName who) {
14268         if (!mHasFeature) {
14269             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
14270         }
14271         Objects.requireNonNull(who, "ComponentName is null");
14272 
14273         final CallerIdentity caller = getCallerIdentity(who);
14274         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
14275 
14276         synchronized (getLockObject()) {
14277             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
14278             return admin.organizationColor;
14279         }
14280     }
14281 
14282     @Override
14283     public int getOrganizationColorForUser(int userHandle) {
14284         if (!mHasFeature) {
14285             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
14286         }
14287         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
14288 
14289         final CallerIdentity caller = getCallerIdentity();
14290         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
14291         Preconditions.checkCallAuthorization(isManagedProfile(userHandle), "You can "
14292                 + "not get organization color outside a managed profile, userId = %d", userHandle);
14293 
14294         synchronized (getLockObject()) {
14295             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
14296             return (profileOwner != null)
14297                     ? profileOwner.organizationColor
14298                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
14299         }
14300     }
14301 
14302     @Override
14303     public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
14304         if (!mHasFeature) {
14305             return;
14306         }
14307         Objects.requireNonNull(who, "ComponentName is null");
14308         final CallerIdentity caller = getCallerIdentity(who);
14309 
14310         synchronized (getLockObject()) {
14311             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
14312             if (!TextUtils.equals(admin.organizationName, text)) {
14313                 admin.organizationName = (text == null || text.length() == 0)
14314                         ? null : text.toString();
14315                 saveSettingsLocked(caller.getUserId());
14316             }
14317         }
14318     }
14319 
14320     @Override
14321     public CharSequence getOrganizationName(@NonNull ComponentName who) {
14322         if (!mHasFeature) {
14323             return null;
14324         }
14325         Objects.requireNonNull(who, "ComponentName is null");
14326 
14327         final CallerIdentity caller = getCallerIdentity(who);
14328         Preconditions.checkCallingUser(isManagedProfile(caller.getUserId()));
14329 
14330         synchronized (getLockObject()) {
14331             ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
14332             return admin.organizationName;
14333         }
14334     }
14335 
14336     @Override
14337     public CharSequence getDeviceOwnerOrganizationName() {
14338         if (!mHasFeature) {
14339             return null;
14340         }
14341         final CallerIdentity caller = getCallerIdentity();
14342         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || canManageUsers(caller));
14343         synchronized (getLockObject()) {
14344             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
14345             return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
14346         }
14347     }
14348 
14349     @Override
14350     public CharSequence getOrganizationNameForUser(int userHandle) {
14351         if (!mHasFeature) {
14352             return null;
14353         }
14354         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
14355 
14356         final CallerIdentity caller = getCallerIdentity();
14357         Preconditions.checkCallAuthorization(hasFullCrossUsersPermission(caller, userHandle));
14358         Preconditions.checkCallAuthorization(canManageUsers(caller));
14359         Preconditions.checkCallAuthorization(isManagedProfile(userHandle),
14360                 "You can not get organization name outside a managed profile, userId = %d",
14361                 userHandle);
14362 
14363         synchronized (getLockObject()) {
14364             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
14365             return (profileOwner != null)
14366                     ? profileOwner.organizationName
14367                     : null;
14368         }
14369     }
14370 
14371     @Override
14372     public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) {
14373         Objects.requireNonNull(who);
14374         Objects.requireNonNull(packageNames);
14375         final CallerIdentity caller = getCallerIdentity(who);
14376         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller),
14377                 "Admin %s does not own the profile", caller.getComponentName());
14378 
14379         if (!mHasFeature) {
14380             return packageNames;
14381         }
14382         synchronized (getLockObject()) {
14383             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
14384             return mInjector.binderWithCleanCallingIdentity(() -> {
14385                 final List<String> excludedPkgs = removeInvalidPkgsForMeteredDataRestriction(
14386                         caller.getUserId(), packageNames);
14387                 admin.meteredDisabledPackages = packageNames;
14388                 pushMeteredDisabledPackagesLocked(caller.getUserId());
14389                 saveSettingsLocked(caller.getUserId());
14390                 return excludedPkgs;
14391             });
14392         }
14393     }
14394 
14395     private List<String> removeInvalidPkgsForMeteredDataRestriction(
14396             int userId, List<String> pkgNames) {
14397         final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId);
14398         final List<String> excludedPkgs = new ArrayList<>();
14399         for (int i = pkgNames.size() - 1; i >= 0; --i) {
14400             final String pkgName = pkgNames.get(i);
14401             // If the package is an active admin, don't restrict it.
14402             if (activeAdmins.contains(pkgName)) {
14403                 excludedPkgs.add(pkgName);
14404                 continue;
14405             }
14406             // If the package doesn't exist, don't restrict it.
14407             try {
14408                 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) {
14409                     excludedPkgs.add(pkgName);
14410                 }
14411             } catch (RemoteException e) {
14412                 // Should not happen
14413             }
14414         }
14415         pkgNames.removeAll(excludedPkgs);
14416         return excludedPkgs;
14417     }
14418 
14419     @Override
14420     public List<String> getMeteredDataDisabledPackages(ComponentName who) {
14421         Objects.requireNonNull(who);
14422 
14423         if (!mHasFeature) {
14424             return new ArrayList<>();
14425         }
14426         final CallerIdentity caller = getCallerIdentity(who);
14427         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller),
14428                 "Admin %s does not own the profile", caller.getComponentName());
14429 
14430         synchronized (getLockObject()) {
14431             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
14432             return admin.meteredDisabledPackages == null
14433                     ? new ArrayList<>() : admin.meteredDisabledPackages;
14434         }
14435     }
14436 
14437     @Override
14438     public boolean isMeteredDataDisabledPackageForUser(ComponentName who,
14439             String packageName, int userId) {
14440         Objects.requireNonNull(who);
14441 
14442         if (!mHasFeature) {
14443             return false;
14444         }
14445         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
14446                 String.format(NOT_SYSTEM_CALLER_MSG, "query restricted pkgs for a specific user"));
14447 
14448         synchronized (getLockObject()) {
14449             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
14450             if (admin != null && admin.meteredDisabledPackages != null) {
14451                 return admin.meteredDisabledPackages.contains(packageName);
14452             }
14453         }
14454         return false;
14455     }
14456 
14457     @Override
14458     public void markProfileOwnerOnOrganizationOwnedDevice(ComponentName who, int userId) {
14459         if (!mHasFeature) {
14460             return;
14461         }
14462         // As the caller is the system, it must specify the component name of the profile owner
14463         // as a safety check.
14464         Objects.requireNonNull(who);
14465 
14466         final CallerIdentity caller = getCallerIdentity();
14467         // Only adb or system apps with the right permission can mark a profile owner on
14468         // organization-owned device.
14469         if (!(isAdb(caller) || hasCallingPermission(permission.MARK_DEVICE_ORGANIZATION_OWNED)
14470                 || hasCallingPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS))) {
14471             throw new SecurityException(
14472                     "Only the system can mark a profile owner of organization-owned device.");
14473         }
14474 
14475         if (isAdb(caller)) {
14476             if (hasIncompatibleAccountsOrNonAdbNoLock(caller, userId, who)) {
14477                 throw new SecurityException(
14478                         "Can only be called from ADB if the device has no accounts.");
14479             }
14480         } else {
14481             if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
14482                 throw new IllegalStateException(
14483                         "Cannot mark profile owner as managing an organization-owned device after"
14484                                 + " set-up");
14485             }
14486         }
14487 
14488         // Grant access under lock.
14489         synchronized (getLockObject()) {
14490             markProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(who, userId);
14491         }
14492     }
14493 
14494     @GuardedBy("getLockObject()")
14495     private void markProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(
14496             ComponentName who, int userId) {
14497         // Make sure that the user has a profile owner and that the specified
14498         // component is the profile owner of that user.
14499         if (!isProfileOwner(who, userId)) {
14500             throw new IllegalArgumentException(String.format(
14501                     "Component %s is not a Profile Owner of user %d",
14502                     who.flattenToString(), userId));
14503         }
14504 
14505         Slogf.i(LOG_TAG, "Marking %s as profile owner on organization-owned device for user %d",
14506                 who.flattenToString(), userId);
14507 
14508         // First, set restriction on removing the profile.
14509         mInjector.binderWithCleanCallingIdentity(() -> {
14510             // Clear restriction as user.
14511             final UserHandle parentUser = mUserManager.getProfileParent(UserHandle.of(userId));
14512             if (parentUser == null) {
14513                 throw new IllegalStateException(String.format("User %d is not a profile", userId));
14514             }
14515             if (!parentUser.isSystem()) {
14516                 throw new IllegalStateException(
14517                         String.format("Only the profile owner of a managed profile on the"
14518                                 + " primary user can be granted access to device identifiers, not"
14519                                 + " on user %d", parentUser.getIdentifier()));
14520             }
14521 
14522             mUserManager.setUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, true,
14523                     parentUser);
14524             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, true,
14525                     parentUser);
14526         });
14527 
14528         // markProfileOwnerOfOrganizationOwnedDevice will trigger writing of the profile owner
14529         // data, no need to do it manually.
14530         mOwners.markProfileOwnerOfOrganizationOwnedDevice(userId);
14531     }
14532 
14533     private void pushMeteredDisabledPackagesLocked(int userId) {
14534         mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages(
14535                 getMeteredDisabledPackagesLocked(userId), userId);
14536     }
14537 
14538     private Set<String> getMeteredDisabledPackagesLocked(int userId) {
14539         final ComponentName who = getOwnerComponent(userId);
14540         final Set<String> restrictedPkgs = new ArraySet<>();
14541         if (who != null) {
14542             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
14543             if (admin != null && admin.meteredDisabledPackages != null) {
14544                 restrictedPkgs.addAll(admin.meteredDisabledPackages);
14545             }
14546         }
14547         return restrictedPkgs;
14548     }
14549 
14550     @Override
14551     public void setAffiliationIds(ComponentName admin, List<String> ids) {
14552         if (!mHasFeature) {
14553             return;
14554         }
14555         if (ids == null) {
14556             throw new IllegalArgumentException("ids must not be null");
14557         }
14558         for (String id : ids) {
14559             if (TextUtils.isEmpty(id)) {
14560                 throw new IllegalArgumentException("ids must not contain empty string");
14561             }
14562         }
14563 
14564         final Set<String> affiliationIds = new ArraySet<>(ids);
14565         final CallerIdentity caller = getCallerIdentity(admin);
14566         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
14567         final int callingUserId = caller.getUserId();
14568 
14569         synchronized (getLockObject()) {
14570             getUserData(callingUserId).mAffiliationIds = affiliationIds;
14571             saveSettingsLocked(callingUserId);
14572             if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
14573                 // Affiliation ids specified by the device owner are additionally stored in
14574                 // UserHandle.USER_SYSTEM's DevicePolicyData.
14575                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
14576                 saveSettingsLocked(UserHandle.USER_SYSTEM);
14577             }
14578 
14579             // Affiliation status for any user, not just the calling user, might have changed.
14580             // The device owner user will still be affiliated after changing its affiliation ids,
14581             // but as a result of that other users might become affiliated or un-affiliated.
14582             maybePauseDeviceWideLoggingLocked();
14583             maybeResumeDeviceWideLoggingLocked();
14584             maybeClearLockTaskPolicyLocked();
14585             updateAdminCanGrantSensorsPermissionCache(callingUserId);
14586         }
14587     }
14588 
14589     @Override
14590     public List<String> getAffiliationIds(ComponentName admin) {
14591         if (!mHasFeature) {
14592             return Collections.emptyList();
14593         }
14594 
14595         Objects.requireNonNull(admin);
14596         final CallerIdentity caller = getCallerIdentity(admin);
14597         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
14598 
14599         synchronized (getLockObject()) {
14600             return new ArrayList<String>(getUserData(caller.getUserId()).mAffiliationIds);
14601         }
14602     }
14603 
14604     @Override
14605     public boolean isCallingUserAffiliated() {
14606         if (!mHasFeature) {
14607             return false;
14608         }
14609 
14610         synchronized (getLockObject()) {
14611             return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
14612         }
14613     }
14614 
14615     @Override
14616     public boolean isAffiliatedUser(@UserIdInt int userId) {
14617         if (!mHasFeature) {
14618             return false;
14619         }
14620         final CallerIdentity caller = getCallerIdentity();
14621         Preconditions.checkCallAuthorization(hasCrossUsersPermission(caller, userId));
14622 
14623         return isUserAffiliatedWithDeviceLocked(userId);
14624     }
14625 
14626     private boolean isUserAffiliatedWithDeviceLocked(@UserIdInt int userId) {
14627         if (!mOwners.hasDeviceOwner()) {
14628             return false;
14629         }
14630         if (userId == UserHandle.USER_SYSTEM) {
14631             // The system user is always affiliated in a DO device,
14632             // even if in headless system user mode.
14633             return true;
14634         }
14635         if (userId == mOwners.getDeviceOwnerUserId()) {
14636             // The user that the DO is installed on is always affiliated with the device.
14637             return true;
14638         }
14639 
14640         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
14641         if (profileOwner == null) {
14642             return false;
14643         }
14644 
14645         final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
14646         final Set<String> deviceAffiliationIds =
14647                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
14648         for (String id : userAffiliationIds) {
14649             if (deviceAffiliationIds.contains(id)) {
14650                 return true;
14651             }
14652         }
14653         return false;
14654     }
14655 
14656     private boolean areAllUsersAffiliatedWithDeviceLocked() {
14657         return mInjector.binderWithCleanCallingIdentity(() -> {
14658             final List<UserInfo> userInfos = mUserManager.getAliveUsers();
14659             for (int i = 0; i < userInfos.size(); i++) {
14660                 int userId = userInfos.get(i).id;
14661                 if (!isUserAffiliatedWithDeviceLocked(userId)) {
14662                     Slogf.d(LOG_TAG, "User id " + userId + " not affiliated.");
14663                     return false;
14664                 }
14665             }
14666             return true;
14667         });
14668     }
14669 
14670     private @UserIdInt int getSecurityLoggingEnabledUser() {
14671         synchronized (getLockObject()) {
14672             if (mOwners.hasDeviceOwner()) {
14673                 return UserHandle.USER_ALL;
14674             }
14675         }
14676         return getOrganizationOwnedProfileUserId();
14677     }
14678 
14679     @Override
14680     public void setSecurityLoggingEnabled(ComponentName admin, String packageName,
14681             boolean enabled) {
14682         if (!mHasFeature) {
14683             return;
14684         }
14685         final CallerIdentity caller = getCallerIdentity(admin, packageName);
14686 
14687         synchronized (getLockObject()) {
14688             if (admin != null) {
14689                 Preconditions.checkCallAuthorization(
14690                         isProfileOwnerOfOrganizationOwnedDevice(caller)
14691                         || isDeviceOwner(caller));
14692             } else {
14693                 // A delegate app passes a null admin component, which is expected
14694                 Preconditions.checkCallAuthorization(
14695                         isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
14696             }
14697 
14698             if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
14699                 return;
14700             }
14701             mInjector.securityLogSetLoggingEnabledProperty(enabled);
14702             if (enabled) {
14703                 mSecurityLogMonitor.start(getSecurityLoggingEnabledUser());
14704                 maybePauseDeviceWideLoggingLocked();
14705             } else {
14706                 mSecurityLogMonitor.stop();
14707             }
14708         }
14709         DevicePolicyEventLogger
14710                 .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED)
14711                 .setAdmin(admin)
14712                 .setBoolean(enabled)
14713                 .write();
14714     }
14715 
14716     @Override
14717     public boolean isSecurityLoggingEnabled(ComponentName admin, String packageName) {
14718         if (!mHasFeature) {
14719             return false;
14720         }
14721 
14722         synchronized (getLockObject()) {
14723             if (!isSystemUid(getCallerIdentity())) {
14724                 final CallerIdentity caller = getCallerIdentity(admin, packageName);
14725                 if (admin != null) {
14726                     Preconditions.checkCallAuthorization(
14727                             isProfileOwnerOfOrganizationOwnedDevice(caller)
14728                             || isDeviceOwner(caller));
14729                 } else {
14730                     // A delegate app passes a null admin component, which is expected
14731                     Preconditions.checkCallAuthorization(
14732                             isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
14733                 }
14734             }
14735             return mInjector.securityLogGetLoggingEnabledProperty();
14736         }
14737     }
14738 
14739     private void recordSecurityLogRetrievalTime() {
14740         synchronized (getLockObject()) {
14741             final long currentTime = System.currentTimeMillis();
14742             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
14743             if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
14744                 policyData.mLastSecurityLogRetrievalTime = currentTime;
14745                 saveSettingsLocked(UserHandle.USER_SYSTEM);
14746             }
14747         }
14748     }
14749 
14750     @Override
14751     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin,
14752             String packageName) {
14753         if (!mHasFeature) {
14754             return null;
14755         }
14756 
14757         final CallerIdentity caller = getCallerIdentity(admin, packageName);
14758         if (admin != null) {
14759             Preconditions.checkCallAuthorization(
14760                     isProfileOwnerOfOrganizationOwnedDevice(caller)
14761                     || isDeviceOwner(caller));
14762         } else {
14763             // A delegate app passes a null admin component, which is expected
14764             Preconditions.checkCallAuthorization(
14765                     isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
14766         }
14767 
14768         Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
14769                 || areAllUsersAffiliatedWithDeviceLocked());
14770 
14771         DevicePolicyEventLogger
14772                 .createEvent(DevicePolicyEnums.RETRIEVE_PRE_REBOOT_SECURITY_LOGS)
14773                 .setAdmin(caller.getComponentName())
14774                 .write();
14775 
14776         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
14777                 || !mInjector.securityLogGetLoggingEnabledProperty()) {
14778             return null;
14779         }
14780 
14781         recordSecurityLogRetrievalTime();
14782         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
14783         try {
14784             SecurityLog.readPreviousEvents(output);
14785             int enabledUser = getSecurityLoggingEnabledUser();
14786             if (enabledUser != UserHandle.USER_ALL) {
14787                 SecurityLog.redactEvents(output, enabledUser);
14788             }
14789             return new ParceledListSlice<SecurityEvent>(output);
14790         } catch (IOException e) {
14791             Slogf.w(LOG_TAG, "Fail to read previous events" , e);
14792             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
14793         }
14794     }
14795 
14796     @Override
14797     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin,
14798             String packageName) {
14799         if (!mHasFeature) {
14800             return null;
14801         }
14802 
14803         final CallerIdentity caller = getCallerIdentity(admin, packageName);
14804         if (admin != null) {
14805             Preconditions.checkCallAuthorization(
14806                     isProfileOwnerOfOrganizationOwnedDevice(caller)
14807                     || isDeviceOwner(caller));
14808         } else {
14809             // A delegate app passes a null admin component, which is expected
14810             Preconditions.checkCallAuthorization(
14811                     isCallerDelegate(caller, DELEGATION_SECURITY_LOGGING));
14812         }
14813         Preconditions.checkCallAuthorization(isOrganizationOwnedDeviceWithManagedProfile()
14814                 || areAllUsersAffiliatedWithDeviceLocked());
14815 
14816         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
14817             return null;
14818         }
14819 
14820         recordSecurityLogRetrievalTime();
14821 
14822         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
14823         DevicePolicyEventLogger
14824                 .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS)
14825                 .setAdmin(caller.getComponentName())
14826                 .write();
14827         return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
14828     }
14829 
14830     @Override
14831     public long forceSecurityLogs() {
14832         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
14833                         || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS),
14834                 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call "
14835                         + "forceSecurityLogs");
14836         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
14837             throw new IllegalStateException("logging is not available");
14838         }
14839         return mSecurityLogMonitor.forceLogs();
14840     }
14841 
14842     @Override
14843     public boolean isUninstallInQueue(final String packageName) {
14844         final CallerIdentity caller = getCallerIdentity();
14845         Preconditions.checkCallAuthorization(
14846                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
14847 
14848         Pair<String, Integer> packageUserPair = new Pair<>(packageName, caller.getUserId());
14849         synchronized (getLockObject()) {
14850             return mPackagesToRemove.contains(packageUserPair);
14851         }
14852     }
14853 
14854     @Override
14855     public void uninstallPackageWithActiveAdmins(final String packageName) {
14856         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
14857 
14858         final CallerIdentity caller = getCallerIdentity();
14859         Preconditions.checkCallAuthorization(
14860                 hasCallingOrSelfPermission(permission.MANAGE_DEVICE_ADMINS));
14861 
14862         final int userId = caller.getUserId();
14863         enforceUserUnlocked(userId);
14864 
14865         final ComponentName profileOwner = getProfileOwnerAsUser(userId);
14866         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
14867             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
14868         }
14869 
14870         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
14871         if (getDeviceOwnerUserId() == userId && deviceOwner != null
14872                 && packageName.equals(deviceOwner.getPackageName())) {
14873             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
14874         }
14875 
14876         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
14877         synchronized (getLockObject()) {
14878             mPackagesToRemove.add(packageUserPair);
14879         }
14880 
14881         // All active admins on the user.
14882         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
14883 
14884         // Active admins in the target package.
14885         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
14886         if (allActiveAdmins != null) {
14887             for (ComponentName activeAdmin : allActiveAdmins) {
14888                 if (packageName.equals(activeAdmin.getPackageName())) {
14889                     packageActiveAdmins.add(activeAdmin);
14890                     removeActiveAdmin(activeAdmin, userId);
14891                 }
14892             }
14893         }
14894         if (packageActiveAdmins.size() == 0) {
14895             startUninstallIntent(packageName, userId);
14896         } else {
14897             mHandler.postDelayed(new Runnable() {
14898                 @Override
14899                 public void run() {
14900                     for (ComponentName activeAdmin : packageActiveAdmins) {
14901                         removeAdminArtifacts(activeAdmin, userId);
14902                     }
14903                     startUninstallIntent(packageName, userId);
14904                 }
14905             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
14906         }
14907     }
14908 
14909     @Override
14910     public boolean isDeviceProvisioned() {
14911         final CallerIdentity caller = getCallerIdentity();
14912         Preconditions.checkCallAuthorization(canManageUsers(caller));
14913 
14914         synchronized (getLockObject()) {
14915             return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
14916         }
14917     }
14918 
14919     private boolean isCurrentUserDemo() {
14920         if (UserManager.isDeviceInDemoMode(mContext)) {
14921             final int userId = mInjector.userHandleGetCallingUserId();
14922             return mInjector.binderWithCleanCallingIdentity(
14923                     () -> mUserManager.getUserInfo(userId).isDemo());
14924         }
14925         return false;
14926     }
14927 
14928     private void removePackageIfRequired(final String packageName, final int userId) {
14929         if (!packageHasActiveAdmins(packageName, userId)) {
14930             // Will not do anything if uninstall was not requested or was already started.
14931             startUninstallIntent(packageName, userId);
14932         }
14933     }
14934 
14935     private void startUninstallIntent(final String packageName, final int userId) {
14936         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
14937         synchronized (getLockObject()) {
14938             if (!mPackagesToRemove.contains(packageUserPair)) {
14939                 // Do nothing if uninstall was not requested or was already started.
14940                 return;
14941             }
14942             mPackagesToRemove.remove(packageUserPair);
14943         }
14944         if (!isPackageInstalledForUser(packageName, userId)) {
14945             // Package does not exist. Nothing to do.
14946             return;
14947         }
14948 
14949         try { // force stop the package before uninstalling
14950             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
14951         } catch (RemoteException re) {
14952             Slogf.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
14953         }
14954         final Uri packageURI = Uri.parse("package:" + packageName);
14955         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
14956         uninstallIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
14957         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
14958     }
14959 
14960     /**
14961      * Removes the admin from the policy. Ideally called after the admin's
14962      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
14963      *
14964      * @param adminReceiver The admin to remove
14965      * @param userHandle The user for which this admin has to be removed.
14966      */
14967     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
14968         synchronized (getLockObject()) {
14969             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
14970             if (admin == null) {
14971                 return;
14972             }
14973             final DevicePolicyData policy = getUserData(userHandle);
14974             final boolean doProxyCleanup = admin.info.usesPolicy(
14975                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
14976             policy.mAdminList.remove(admin);
14977             policy.mAdminMap.remove(adminReceiver);
14978             policy.validatePasswordOwner();
14979             if (doProxyCleanup) {
14980                 resetGlobalProxyLocked(policy);
14981             }
14982             pushActiveAdminPackagesLocked(userHandle);
14983             pushMeteredDisabledPackagesLocked(userHandle);
14984             saveSettingsLocked(userHandle);
14985             updateMaximumTimeToLockLocked(userHandle);
14986             policy.mRemovingAdmins.remove(adminReceiver);
14987 
14988             Slogf.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
14989         }
14990         // The removed admin might have disabled camera, so update user
14991         // restrictions.
14992         pushUserRestrictions(userHandle);
14993     }
14994 
14995     @Override
14996     public void setDeviceProvisioningConfigApplied() {
14997         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
14998 
14999         synchronized (getLockObject()) {
15000             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
15001             policy.mDeviceProvisioningConfigApplied = true;
15002             saveSettingsLocked(UserHandle.USER_SYSTEM);
15003         }
15004     }
15005 
15006     @Override
15007     public boolean isDeviceProvisioningConfigApplied() {
15008         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
15009 
15010         synchronized (getLockObject()) {
15011             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
15012             return policy.mDeviceProvisioningConfigApplied;
15013         }
15014     }
15015 
15016     /**
15017      * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
15018      *
15019      * It's added for testing only. Please use this API carefully if it's used by other system app
15020      * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
15021      * apps.
15022      */
15023     @Override
15024     public void forceUpdateUserSetupComplete(@UserIdInt int userId) {
15025         Preconditions.checkCallAuthorization(
15026                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
15027 
15028         boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
15029                 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
15030         DevicePolicyData policy = getUserData(userId);
15031         policy.mUserSetupComplete = isUserCompleted;
15032         mStateCache.setDeviceProvisioned(isUserCompleted);
15033         synchronized (getLockObject()) {
15034             saveSettingsLocked(userId);
15035         }
15036     }
15037 
15038     @Override
15039     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
15040         if (!mHasFeature) {
15041             return;
15042         }
15043         Objects.requireNonNull(admin, "ComponentName is null");
15044 
15045         final CallerIdentity caller = getCallerIdentity(admin);
15046         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
15047 
15048         toggleBackupServiceActive(caller.getUserId(), enabled);
15049     }
15050 
15051     @Override
15052     public boolean isBackupServiceEnabled(ComponentName admin) {
15053         if (!mHasFeature) {
15054             return true;
15055         }
15056         Objects.requireNonNull(admin, "ComponentName is null");
15057 
15058         final CallerIdentity caller = getCallerIdentity(admin);
15059         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
15060 
15061         return mInjector.binderWithCleanCallingIdentity(() -> {
15062             synchronized (getLockObject()) {
15063                 try {
15064                     IBackupManager ibm = mInjector.getIBackupManager();
15065                     return ibm != null && ibm.isBackupServiceActive(caller.getUserId());
15066                 } catch (RemoteException e) {
15067                     throw new IllegalStateException("Failed requesting backup service state.", e);
15068                 }
15069             }
15070         });
15071     }
15072 
15073     @Override
15074     public boolean bindDeviceAdminServiceAsUser(
15075             @NonNull ComponentName admin, @NonNull IApplicationThread caller,
15076             @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
15077             @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
15078         if (!mHasFeature) {
15079             return false;
15080         }
15081         Objects.requireNonNull(admin);
15082         Objects.requireNonNull(caller);
15083         Objects.requireNonNull(serviceIntent);
15084         Preconditions.checkArgument(
15085                 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
15086                 "Service intent must be explicit (with a package name or component): "
15087                         + serviceIntent);
15088         Objects.requireNonNull(connection);
15089         Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
15090                 "target user id must be different from the calling user id");
15091 
15092         if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
15093             throw new SecurityException("Not allowed to bind to target user id");
15094         }
15095 
15096         final String targetPackage;
15097         synchronized (getLockObject()) {
15098             targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
15099         }
15100 
15101         final long callingIdentity = mInjector.binderClearCallingIdentity();
15102         try {
15103             // Validate and sanitize the incoming service intent.
15104             final Intent sanitizedIntent =
15105                     createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
15106             if (sanitizedIntent == null) {
15107                 // Fail, cannot lookup the target service.
15108                 return false;
15109             }
15110             // Ask ActivityManager to bind it. Notice that we are binding the service with the
15111             // caller app instead of DevicePolicyManagerService.
15112             return mInjector.getIActivityManager().bindService(
15113                     caller, activtiyToken, serviceIntent,
15114                     serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
15115                     connection, flags, mContext.getOpPackageName(),
15116                     targetUserId) != 0;
15117         } catch (RemoteException ex) {
15118             // Same process, should not happen.
15119         } finally {
15120             mInjector.binderRestoreCallingIdentity(callingIdentity);
15121         }
15122 
15123         // Failed to bind.
15124         return false;
15125     }
15126 
15127     @Override
15128     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
15129         if (!mHasFeature) {
15130             return Collections.emptyList();
15131         }
15132         Objects.requireNonNull(admin);
15133         final CallerIdentity caller = getCallerIdentity(admin);
15134         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
15135 
15136         synchronized (getLockObject()) {
15137             final int callingUserId = caller.getUserId();
15138             return mInjector.binderWithCleanCallingIdentity(() -> {
15139                 ArrayList<UserHandle> targetUsers = new ArrayList<>();
15140                 if (!isDeviceOwner(admin, callingUserId)) {
15141                     // Profile owners can only bind to the device owner.
15142                     if (canUserBindToDeviceOwnerLocked(callingUserId)) {
15143                         targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
15144                     }
15145                 } else {
15146                     // Caller is the device owner: Look for profile owners that it can bind to.
15147                     final List<UserInfo> userInfos = mUserManager.getAliveUsers();
15148                     for (int i = 0; i < userInfos.size(); i++) {
15149                         final int userId = userInfos.get(i).id;
15150                         if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
15151                             targetUsers.add(UserHandle.of(userId));
15152                         }
15153                     }
15154                 }
15155 
15156                 return targetUsers;
15157             });
15158         }
15159     }
15160 
15161     private boolean canUserBindToDeviceOwnerLocked(int userId) {
15162         // There has to be a device owner, under another user id.
15163         if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
15164             return false;
15165         }
15166 
15167         // The user must have a profile owner that belongs to the same package as the device owner.
15168         if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
15169                 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
15170             return false;
15171         }
15172 
15173         // The user must be affiliated.
15174         return isUserAffiliatedWithDeviceLocked(userId);
15175     }
15176 
15177     /**
15178      * Return true if a given user has any accounts that'll prevent installing a device or profile
15179      * owner {@code owner}.
15180      * - If the user has no accounts, then return false.
15181      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
15182      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
15183      *   ..._DISALLOWED, return true.
15184      * - Otherwise return false.
15185      *
15186      * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
15187      * when the caller is not ADB.
15188      *
15189      * DO NOT CALL IT WITH THE DPMS LOCK HELD.
15190      */
15191     private boolean hasIncompatibleAccountsOrNonAdbNoLock(CallerIdentity caller,
15192             int userId, @Nullable ComponentName owner) {
15193         if (!isAdb(caller)) {
15194             return true;
15195         }
15196         wtfIfInLock();
15197 
15198         return mInjector.binderWithCleanCallingIdentity(() -> {
15199             final AccountManager am = AccountManager.get(mContext);
15200             final Account accounts[] = am.getAccountsAsUser(userId);
15201             if (accounts.length == 0) {
15202                 return false;
15203             }
15204             synchronized (getLockObject()) {
15205                 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
15206                     Slogf.w(LOG_TAG,
15207                             "Non test-only owner can't be installed with existing accounts.");
15208                     return true;
15209                 }
15210             }
15211 
15212             final String[] feature_allow =
15213                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
15214             final String[] feature_disallow =
15215                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
15216 
15217             boolean compatible = true;
15218             for (Account account : accounts) {
15219                 if (hasAccountFeatures(am, account, feature_disallow)) {
15220                     Slogf.e(LOG_TAG, "%s has %s", account, feature_disallow[0]);
15221                     compatible = false;
15222                     break;
15223                 }
15224                 if (!hasAccountFeatures(am, account, feature_allow)) {
15225                     Slogf.e(LOG_TAG, "%s doesn't have %s", account, feature_allow[0]);
15226                     compatible = false;
15227                     break;
15228                 }
15229             }
15230             if (compatible) {
15231                 Slogf.w(LOG_TAG, "All accounts are compatible");
15232             } else {
15233                 Slogf.e(LOG_TAG, "Found incompatible accounts");
15234             }
15235             return !compatible;
15236         });
15237     }
15238 
15239     private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
15240         try {
15241             return am.hasFeatures(account, features, null, null).getResult();
15242         } catch (Exception e) {
15243             Slogf.w(LOG_TAG, "Failed to get account feature", e);
15244             return false;
15245         }
15246     }
15247 
15248     private boolean isAdb(CallerIdentity caller) {
15249         return isShellUid(caller) || isRootUid(caller);
15250     }
15251 
15252     @Override
15253     public void setNetworkLoggingEnabled(@Nullable ComponentName admin,
15254             @NonNull String packageName, boolean enabled) {
15255         if (!mHasFeature) {
15256             return;
15257         }
15258         final CallerIdentity caller = getCallerIdentity(admin, packageName);
15259         final boolean isManagedProfileOwner = isProfileOwner(caller)
15260                 && isManagedProfile(caller.getUserId());
15261         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
15262                 && (isDeviceOwner(caller) || isManagedProfileOwner))
15263                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)));
15264 
15265         synchronized (getLockObject()) {
15266             if (enabled == isNetworkLoggingEnabledInternalLocked()) {
15267                 // already in the requested state
15268                 return;
15269             }
15270             final ActiveAdmin activeAdmin = getDeviceOrProfileOwnerAdminLocked(caller.getUserId());
15271             activeAdmin.isNetworkLoggingEnabled = enabled;
15272             if (!enabled) {
15273                 activeAdmin.numNetworkLoggingNotifications = 0;
15274                 activeAdmin.lastNetworkLoggingNotificationTimeMs = 0;
15275             }
15276             saveSettingsLocked(caller.getUserId());
15277             setNetworkLoggingActiveInternal(enabled);
15278 
15279             DevicePolicyEventLogger
15280                     .createEvent(DevicePolicyEnums.SET_NETWORK_LOGGING_ENABLED)
15281                     .setAdmin(caller.getPackageName())
15282                     .setBoolean(/* isDelegate */ admin == null)
15283                     .setInt(enabled ? 1 : 0)
15284                     .setStrings(isManagedProfileOwner
15285                             ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER)
15286                     .write();
15287         }
15288     }
15289 
15290     private void setNetworkLoggingActiveInternal(boolean active) {
15291         mInjector.binderWithCleanCallingIdentity(() -> {
15292             boolean shouldSendNotification = false;
15293             synchronized (getLockObject()) {
15294                 if (active) {
15295                     if (mNetworkLogger == null) {
15296                         final int affectedUserId = getNetworkLoggingAffectedUser();
15297                         mNetworkLogger = new NetworkLogger(this,
15298                                 mInjector.getPackageManagerInternal(),
15299                                 affectedUserId == UserHandle.USER_SYSTEM
15300                                         ? UserHandle.USER_ALL : affectedUserId);
15301                     }
15302                     if (!mNetworkLogger.startNetworkLogging()) {
15303                         mNetworkLogger = null;
15304                         Slogf.wtf(LOG_TAG, "Network logging could not be started due to the logging"
15305                                 + " service not being available yet.");
15306                     }
15307                     maybePauseDeviceWideLoggingLocked();
15308                     shouldSendNotification = shouldSendNetworkLoggingNotificationLocked();
15309                 } else {
15310                     if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
15311                         Slogf.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
15312                                 + " service not being available yet.");
15313                     }
15314                     mNetworkLogger = null;
15315                 }
15316             }
15317             if (active) {
15318                 if (shouldSendNotification) {
15319                     mHandler.post(() -> handleSendNetworkLoggingNotification());
15320                 }
15321             } else {
15322                 mHandler.post(() -> handleCancelNetworkLoggingNotification());
15323             }
15324         });
15325     }
15326 
15327     private @UserIdInt int getNetworkLoggingAffectedUser() {
15328         synchronized (getLockObject()) {
15329             if (mOwners.hasDeviceOwner()) {
15330                 return mOwners.getDeviceOwnerUserId();
15331             } else {
15332                 return mInjector.binderWithCleanCallingIdentity(
15333                         () -> getManagedUserId(UserHandle.USER_SYSTEM));
15334             }
15335         }
15336     }
15337 
15338     private ActiveAdmin getNetworkLoggingControllingAdminLocked() {
15339         int affectedUserId = getNetworkLoggingAffectedUser();
15340         if (affectedUserId < 0) {
15341             return null;
15342         }
15343         return getDeviceOrProfileOwnerAdminLocked(affectedUserId);
15344     }
15345 
15346     @Override
15347     public long forceNetworkLogs() {
15348         Preconditions.checkCallAuthorization(isAdb(getCallerIdentity())
15349                 || hasCallingOrSelfPermission(permission.FORCE_DEVICE_POLICY_MANAGER_LOGS),
15350                 "Caller must be shell or hold FORCE_DEVICE_POLICY_MANAGER_LOGS to call "
15351                         + "forceNetworkLogs");
15352         synchronized (getLockObject()) {
15353             if (!isNetworkLoggingEnabledInternalLocked()) {
15354                 throw new IllegalStateException("logging is not available");
15355             }
15356             if (mNetworkLogger != null) {
15357                 return mInjector.binderWithCleanCallingIdentity(
15358                         () -> mNetworkLogger.forceBatchFinalization());
15359             }
15360             return 0;
15361         }
15362     }
15363 
15364     /** Pauses security and network logging if there are unaffiliated users on the device */
15365     @GuardedBy("getLockObject()")
15366     private void maybePauseDeviceWideLoggingLocked() {
15367         if (!areAllUsersAffiliatedWithDeviceLocked()) {
15368             if (mOwners.hasDeviceOwner()) {
15369                 Slogf.i(LOG_TAG, "There are unaffiliated users, network logging will be "
15370                         + "paused if enabled.");
15371                 if (mNetworkLogger != null) {
15372                     mNetworkLogger.pause();
15373                 }
15374             }
15375             if (!isOrganizationOwnedDeviceWithManagedProfile()) {
15376                 Slogf.i(LOG_TAG, "Not org-owned managed profile device, security logging will be "
15377                         + "paused if enabled.");
15378                 mSecurityLogMonitor.pause();
15379             }
15380         }
15381     }
15382 
15383     /** Resumes security and network logging (if they are enabled) if all users are affiliated */
15384     @GuardedBy("getLockObject()")
15385     private void maybeResumeDeviceWideLoggingLocked() {
15386         boolean allUsersAffiliated = areAllUsersAffiliatedWithDeviceLocked();
15387         boolean orgOwnedProfileDevice = isOrganizationOwnedDeviceWithManagedProfile();
15388         mInjector.binderWithCleanCallingIdentity(() -> {
15389             if (allUsersAffiliated || orgOwnedProfileDevice) {
15390                 mSecurityLogMonitor.resume();
15391             }
15392             // If there is no device owner, then per-user network logging may be enabled for the
15393             // managed profile. In which case, all users do not need to be affiliated.
15394             if (allUsersAffiliated || !mOwners.hasDeviceOwner()) {
15395                 if (mNetworkLogger != null) {
15396                     mNetworkLogger.resume();
15397                 }
15398             }
15399         });
15400     }
15401 
15402     /** Deletes any security and network logs that might have been collected so far */
15403     @GuardedBy("getLockObject()")
15404     private void discardDeviceWideLogsLocked() {
15405         mSecurityLogMonitor.discardLogs();
15406         if (mNetworkLogger != null) {
15407             mNetworkLogger.discardLogs();
15408         }
15409         // TODO: We should discard pre-boot security logs here too, as otherwise those
15410         // logs (which might contain data from the user just removed) will be
15411         // available after next boot.
15412     }
15413 
15414     @Override
15415     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin,
15416             @NonNull String packageName) {
15417         if (!mHasFeature) {
15418             return false;
15419         }
15420         final CallerIdentity caller = getCallerIdentity(admin, packageName);
15421         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
15422                 &&  (isDeviceOwner(caller)
15423                 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))))
15424                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING))
15425                 || hasCallingOrSelfPermission(permission.MANAGE_USERS));
15426 
15427         synchronized (getLockObject()) {
15428             return isNetworkLoggingEnabledInternalLocked();
15429         }
15430     }
15431 
15432     private boolean isNetworkLoggingEnabledInternalLocked() {
15433         ActiveAdmin activeAdmin = getNetworkLoggingControllingAdminLocked();
15434         return (activeAdmin != null) && activeAdmin.isNetworkLoggingEnabled;
15435     }
15436 
15437     /*
15438      * A maximum of 1200 events are returned, and the total marshalled size is in the order of
15439      * 100kB, so returning a List instead of ParceledListSlice is acceptable.
15440      * Ideally this would be done with ParceledList, however it only supports homogeneous types.
15441      *
15442      * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
15443      */
15444     @Override
15445     public List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
15446             @NonNull String packageName, long batchToken) {
15447         if (!mHasFeature) {
15448             return null;
15449         }
15450         final CallerIdentity caller = getCallerIdentity(admin, packageName);
15451         final boolean isManagedProfileOwner = isProfileOwner(caller)
15452                 && isManagedProfile(caller.getUserId());
15453         Preconditions.checkCallAuthorization((caller.hasAdminComponent()
15454                 &&  (isDeviceOwner(caller) || isManagedProfileOwner))
15455                 || (caller.hasPackage() && isCallerDelegate(caller, DELEGATION_NETWORK_LOGGING)));
15456         if (mOwners.hasDeviceOwner()) {
15457             checkAllUsersAreAffiliatedWithDevice();
15458         }
15459 
15460         synchronized (getLockObject()) {
15461             if (mNetworkLogger == null || !isNetworkLoggingEnabledInternalLocked()) {
15462                 return null;
15463             }
15464             DevicePolicyEventLogger
15465                     .createEvent(DevicePolicyEnums.RETRIEVE_NETWORK_LOGS)
15466                     .setAdmin(caller.getPackageName())
15467                     .setBoolean(/* isDelegate */ admin == null)
15468                     .setStrings(isManagedProfileOwner
15469                             ? LOG_TAG_PROFILE_OWNER : LOG_TAG_DEVICE_OWNER)
15470                     .write();
15471 
15472             final long currentTime = System.currentTimeMillis();
15473             DevicePolicyData policyData = getUserData(caller.getUserId());
15474             if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
15475                 policyData.mLastNetworkLogsRetrievalTime = currentTime;
15476                 saveSettingsLocked(caller.getUserId());
15477             }
15478             return mNetworkLogger.retrieveLogs(batchToken);
15479         }
15480     }
15481 
15482     /**
15483      * Returns whether it's time to post another network logging notification. When returning true,
15484      * this method has the side-effect of updating the recorded last network logging notification
15485      * time to now.
15486      */
15487     private boolean shouldSendNetworkLoggingNotificationLocked() {
15488         ensureLocked();
15489         // Send a network logging notification if the admin is a device owner, not profile owner.
15490         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
15491         if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
15492             return false;
15493         }
15494         if (deviceOwner.numNetworkLoggingNotifications
15495                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
15496             return false;
15497         }
15498         final long now = System.currentTimeMillis();
15499         if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
15500             return false;
15501         }
15502         deviceOwner.numNetworkLoggingNotifications++;
15503         if (deviceOwner.numNetworkLoggingNotifications
15504                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
15505             deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
15506         } else {
15507             deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
15508         }
15509         saveSettingsLocked(deviceOwner.getUserHandle().getIdentifier());
15510         return true;
15511     }
15512 
15513     private void handleSendNetworkLoggingNotification() {
15514         final PackageManagerInternal pm = mInjector.getPackageManagerInternal();
15515         final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
15516         intent.setPackage(pm.getSystemUiServiceComponent().getPackageName());
15517         mNetworkLoggingNotificationUserId = getCurrentForegroundUserId();
15518         // Simple notification clicks are immutable
15519         final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent,
15520                 PendingIntent.FLAG_IMMUTABLE, UserHandle.CURRENT);
15521         Notification notification =
15522                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
15523                 .setSmallIcon(R.drawable.ic_info_outline)
15524                 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
15525                 .setContentText(mContext.getString(R.string.network_logging_notification_text))
15526                 .setTicker(mContext.getString(R.string.network_logging_notification_title))
15527                 .setShowWhen(true)
15528                 .setContentIntent(pendingIntent)
15529                 .setStyle(new Notification.BigTextStyle()
15530                         .bigText(mContext.getString(R.string.network_logging_notification_text)))
15531                 .build();
15532         Slogf.i(LOG_TAG, "Sending network logging notification to user %d",
15533                 mNetworkLoggingNotificationUserId);
15534         mInjector.getNotificationManager().notifyAsUser(/* tag= */ null,
15535                 SystemMessage.NOTE_NETWORK_LOGGING, notification,
15536                 UserHandle.of(mNetworkLoggingNotificationUserId));
15537     }
15538 
15539     private void handleCancelNetworkLoggingNotification() {
15540         if (mNetworkLoggingNotificationUserId == UserHandle.USER_NULL) {
15541             // Happens when setNetworkLoggingActive(false) is called before called with true
15542             Slogf.d(LOG_TAG, "Not cancelling network logging notification for USER_NULL");
15543             return;
15544         }
15545 
15546         Slogf.i(LOG_TAG, "Cancelling network logging notification for user %d",
15547                 mNetworkLoggingNotificationUserId);
15548         mInjector.getNotificationManager().cancelAsUser(/* tag= */ null,
15549                 SystemMessage.NOTE_NETWORK_LOGGING,
15550                 UserHandle.of(mNetworkLoggingNotificationUserId));
15551         mNetworkLoggingNotificationUserId = UserHandle.USER_NULL;
15552     }
15553 
15554     /**
15555      * Return the package name of owner in a given user.
15556      */
15557     private String getOwnerPackageNameForUserLocked(int userId) {
15558         return mOwners.getDeviceOwnerUserId() == userId
15559                 ? mOwners.getDeviceOwnerPackageName()
15560                 : mOwners.getProfileOwnerPackage(userId);
15561     }
15562 
15563     /**
15564      * @param rawIntent Original service intent specified by caller. It must be explicit.
15565      * @param expectedPackageName The expected package name of the resolved service.
15566      * @return Intent that have component explicitly set. {@code null} if no service is resolved
15567      *     with the given intent.
15568      * @throws SecurityException if the intent is resolved to an invalid service.
15569      */
15570     private Intent createCrossUserServiceIntent(
15571             @NonNull Intent rawIntent, @NonNull String expectedPackageName,
15572             @UserIdInt int targetUserId) throws RemoteException, SecurityException {
15573         ResolveInfo info = mIPackageManager.resolveService(
15574                 rawIntent,
15575                 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
15576                 0,  // flags
15577                 targetUserId);
15578         if (info == null || info.serviceInfo == null) {
15579             Slogf.e(LOG_TAG, "Fail to look up the service: %s or user %d is not running", rawIntent,
15580                     targetUserId);
15581             return null;
15582         }
15583         if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
15584             throw new SecurityException("Only allow to bind service in " + expectedPackageName);
15585         }
15586         // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
15587         if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
15588             throw new SecurityException(
15589                     "Service must be protected by BIND_DEVICE_ADMIN permission");
15590         }
15591         // It is the system server to bind the service, it would be extremely dangerous if it
15592         // can be exploited to bind any service. Set the component explicitly to make sure we
15593         // do not bind anything accidentally.
15594         rawIntent.setComponent(info.serviceInfo.getComponentName());
15595         return rawIntent;
15596     }
15597 
15598     @Override
getLastSecurityLogRetrievalTime()15599     public long getLastSecurityLogRetrievalTime() {
15600         final CallerIdentity caller = getCallerIdentity();
15601         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || canManageUsers(caller));
15602         return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
15603      }
15604 
15605     @Override
getLastBugReportRequestTime()15606     public long getLastBugReportRequestTime() {
15607         final CallerIdentity caller = getCallerIdentity();
15608         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || canManageUsers(caller));
15609         return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
15610      }
15611 
15612     @Override
getLastNetworkLogRetrievalTime()15613     public long getLastNetworkLogRetrievalTime() {
15614         final CallerIdentity caller = getCallerIdentity();
15615 
15616         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
15617                 || (isProfileOwner(caller) && isManagedProfile(caller.getUserId()))
15618                 || canManageUsers(caller));
15619         final int affectedUserId = getNetworkLoggingAffectedUser();
15620         return affectedUserId >= 0 ? getUserData(affectedUserId).mLastNetworkLogsRetrievalTime : -1;
15621     }
15622 
15623     @Override
setResetPasswordToken(ComponentName admin, byte[] token)15624     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
15625         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
15626             return false;
15627         }
15628         if (token == null || token.length < 32) {
15629             throw new IllegalArgumentException("token must be at least 32-byte long");
15630         }
15631         final CallerIdentity caller = getCallerIdentity(admin);
15632         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
15633 
15634         synchronized (getLockObject()) {
15635             final int userHandle = caller.getUserId();
15636 
15637             DevicePolicyData policy = getUserData(userHandle);
15638             return mInjector.binderWithCleanCallingIdentity(() -> {
15639                 if (policy.mPasswordTokenHandle != 0) {
15640                     mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
15641                 }
15642                 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token,
15643                         userHandle, /*EscrowTokenStateChangeCallback*/ null);
15644                 saveSettingsLocked(userHandle);
15645                 return policy.mPasswordTokenHandle != 0;
15646             });
15647         }
15648     }
15649 
15650     @Override
15651     public boolean clearResetPasswordToken(ComponentName admin) {
15652         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
15653             return false;
15654         }
15655         final CallerIdentity caller = getCallerIdentity(admin);
15656         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
15657 
15658         synchronized (getLockObject()) {
15659             final int userHandle = caller.getUserId();
15660 
15661             DevicePolicyData policy = getUserData(userHandle);
15662             if (policy.mPasswordTokenHandle != 0) {
15663                 return mInjector.binderWithCleanCallingIdentity(() -> {
15664                     boolean result = mLockPatternUtils.removeEscrowToken(
15665                             policy.mPasswordTokenHandle, userHandle);
15666                     policy.mPasswordTokenHandle = 0;
15667                     saveSettingsLocked(userHandle);
15668                     return result;
15669                 });
15670             }
15671         }
15672         return false;
15673     }
15674 
15675     @Override
15676     public boolean isResetPasswordTokenActive(ComponentName admin) {
15677         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
15678             return false;
15679         }
15680         final CallerIdentity caller = getCallerIdentity(admin);
15681         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
15682 
15683         synchronized (getLockObject()) {
15684             return isResetPasswordTokenActiveForUserLocked(caller.getUserId());
15685         }
15686     }
15687 
15688     private boolean isResetPasswordTokenActiveForUserLocked(int userHandle) {
15689         DevicePolicyData policy = getUserData(userHandle);
15690         if (policy.mPasswordTokenHandle != 0) {
15691             return mInjector.binderWithCleanCallingIdentity(() ->
15692                     mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle, userHandle));
15693         }
15694         return false;
15695     }
15696 
15697     @Override
15698     public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
15699             int flags) {
15700         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
15701             return false;
15702         }
15703         Objects.requireNonNull(token);
15704 
15705         final CallerIdentity caller = getCallerIdentity(admin);
15706         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
15707 
15708         synchronized (getLockObject()) {
15709             DevicePolicyData policy = getUserData(caller.getUserId());
15710             if (policy.mPasswordTokenHandle != 0) {
15711                 final String password = passwordOrNull != null ? passwordOrNull : "";
15712                 final boolean result = resetPasswordInternal(password, policy.mPasswordTokenHandle,
15713                         token, flags, caller);
15714                 if (result) {
15715                     DevicePolicyEventLogger
15716                             .createEvent(DevicePolicyEnums.RESET_PASSWORD_WITH_TOKEN)
15717                             .setAdmin(caller.getComponentName())
15718                             .write();
15719                 }
15720                 return result;
15721             } else {
15722                 Slogf.w(LOG_TAG, "No saved token handle");
15723             }
15724         }
15725         return false;
15726     }
15727 
15728     @Override
15729     public boolean isCurrentInputMethodSetByOwner() {
15730         final CallerIdentity caller = getCallerIdentity();
15731         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
15732                 || isProfileOwner(caller) || isSystemUid(caller),
15733                 "Only profile owner, device owner and system may call this method.");
15734         return getUserData(caller.getUserId()).mCurrentInputMethodSet;
15735     }
15736 
15737     @Override
15738     public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
15739         final int userId = user.getIdentifier();
15740         final CallerIdentity caller = getCallerIdentity();
15741         Preconditions.checkCallAuthorization((userId == caller.getUserId())
15742                 || isProfileOwner(caller) || isDeviceOwner(caller)
15743                 || hasFullCrossUsersPermission(caller, userId));
15744 
15745         synchronized (getLockObject()) {
15746             return new StringParceledListSlice(
15747                     new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
15748         }
15749     }
15750 
15751     @Override
15752     public void clearApplicationUserData(ComponentName admin, String packageName,
15753             IPackageDataObserver callback) {
15754         Objects.requireNonNull(admin, "ComponentName is null");
15755         Objects.requireNonNull(packageName, "packageName is null");
15756         Objects.requireNonNull(callback, "callback is null");
15757 
15758         final CallerIdentity caller = getCallerIdentity(admin);
15759         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
15760         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_CLEAR_APPLICATION_USER_DATA);
15761 
15762         long ident = mInjector.binderClearCallingIdentity();
15763         try {
15764             ActivityManager.getService().clearApplicationUserData(packageName, false, callback,
15765                     caller.getUserId());
15766         } catch(RemoteException re) {
15767             // Same process, should not happen.
15768         } catch (SecurityException se) {
15769             // This can happen e.g. for device admin packages, do not throw out the exception,
15770             // because callers have no means to know beforehand for which packages this might
15771             // happen. If so, we send back that removal failed.
15772             Slogf.w(LOG_TAG, "Not allowed to clear application user data for package "
15773                     + packageName, se);
15774             try {
15775                 callback.onRemoveCompleted(packageName, false);
15776             } catch (RemoteException re) {
15777                 // Caller is no longer available, ignore
15778             }
15779         } finally {
15780             mInjector.binderRestoreCallingIdentity(ident);
15781         }
15782     }
15783 
15784     @Override
15785     public void setLogoutEnabled(ComponentName admin, boolean enabled) {
15786         if (!mHasFeature) {
15787             return;
15788         }
15789         Objects.requireNonNull(admin, "ComponentName is null");
15790         final CallerIdentity caller = getCallerIdentity(admin);
15791         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
15792         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_LOGOUT_ENABLED);
15793 
15794         synchronized (getLockObject()) {
15795             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
15796             if (deviceOwner.isLogoutEnabled == enabled) {
15797                 // already in the requested state
15798                 return;
15799             }
15800             deviceOwner.isLogoutEnabled = enabled;
15801             saveSettingsLocked(caller.getUserId());
15802         }
15803     }
15804 
15805     @Override
15806     public boolean isLogoutEnabled() {
15807         if (!mHasFeature) {
15808             return false;
15809         }
15810         synchronized (getLockObject()) {
15811             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
15812             return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
15813         }
15814     }
15815 
15816     @Override
15817     public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
15818             String provisioningAction) throws RemoteException {
15819         Preconditions.checkCallAuthorization(
15820                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
15821 
15822         return new ArrayList<>(
15823                 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
15824     }
15825 
15826     @Override
15827     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
15828             @Nullable PersistableBundle bundle) {
15829         if (!mHasFeature) {
15830             return;
15831         }
15832         Objects.requireNonNull(admin, "ComponentName is null");
15833         Objects.requireNonNull(target, "Target cannot be null.");
15834         Preconditions.checkArgument(!admin.equals(target),
15835                 "Provided administrator and target are the same object.");
15836         Preconditions.checkArgument(!admin.getPackageName().equals(target.getPackageName()),
15837                 "Provided administrator and target have the same package name.");
15838 
15839         final CallerIdentity caller = getCallerIdentity(admin);
15840         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller));
15841 
15842         final int callingUserId = caller.getUserId();
15843         final DevicePolicyData policy = getUserData(callingUserId);
15844         final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId,
15845                 /* throwForMissingPermission= */ true);
15846         checkActiveAdminPrecondition(target, incomingDeviceInfo, policy);
15847         Preconditions.checkArgument(incomingDeviceInfo.supportsTransferOwnership(),
15848                 "Provided target does not support ownership transfer.");
15849 
15850         final long id = mInjector.binderClearCallingIdentity();
15851         String ownerType = null;
15852         try {
15853             synchronized (getLockObject()) {
15854                 /*
15855                 * We must ensure the whole process is atomic to prevent the device from ending up
15856                 * in an invalid state (e.g. no active admin). This could happen if the device
15857                 * is rebooted or work mode is turned off mid-transfer.
15858                 * In order to guarantee atomicity, we:
15859                 *
15860                 * 1. Save an atomic journal file describing the transfer process
15861                 * 2. Perform the transfer itself
15862                 * 3. Delete the journal file
15863                 *
15864                 * That way if the journal file exists on device boot, we know that the transfer
15865                 * must be reverted back to the original administrator. This logic is implemented in
15866                 * revertTransferOwnershipIfNecessaryLocked.
15867                 * */
15868                 if (bundle == null) {
15869                     bundle = new PersistableBundle();
15870                 }
15871                 if (isProfileOwner(caller)) {
15872                     ownerType = ADMIN_TYPE_PROFILE_OWNER;
15873                     prepareTransfer(admin, target, bundle, callingUserId,
15874                             ADMIN_TYPE_PROFILE_OWNER);
15875                     transferProfileOwnershipLocked(admin, target, callingUserId);
15876                     sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
15877                             getTransferOwnershipAdminExtras(bundle), callingUserId);
15878                     postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId);
15879                     if (isUserAffiliatedWithDeviceLocked(callingUserId)) {
15880                         notifyAffiliatedProfileTransferOwnershipComplete(callingUserId);
15881                     }
15882                 } else if (isDeviceOwner(caller)) {
15883                     ownerType = ADMIN_TYPE_DEVICE_OWNER;
15884                     prepareTransfer(admin, target, bundle, callingUserId,
15885                             ADMIN_TYPE_DEVICE_OWNER);
15886                     transferDeviceOwnershipLocked(admin, target, callingUserId);
15887                     sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
15888                             getTransferOwnershipAdminExtras(bundle));
15889                     postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId);
15890                 }
15891             }
15892         } finally {
15893             mInjector.binderRestoreCallingIdentity(id);
15894         }
15895         DevicePolicyEventLogger
15896                 .createEvent(DevicePolicyEnums.TRANSFER_OWNERSHIP)
15897                 .setAdmin(admin)
15898                 .setStrings(target.getPackageName(), ownerType)
15899                 .write();
15900     }
15901 
15902     private void prepareTransfer(ComponentName admin, ComponentName target,
15903             PersistableBundle bundle, int callingUserId, String adminType) {
15904         saveTransferOwnershipBundleLocked(bundle, callingUserId);
15905         mTransferOwnershipMetadataManager.saveMetadataFile(
15906                 new TransferOwnershipMetadataManager.Metadata(admin, target,
15907                         callingUserId, adminType));
15908     }
15909 
15910     private void postTransfer(String broadcast, int callingUserId) {
15911         deleteTransferOwnershipMetadataFileLocked();
15912         sendOwnerChangedBroadcast(broadcast, callingUserId);
15913     }
15914 
15915     private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) {
15916         final Bundle extras = new Bundle();
15917         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId));
15918         sendDeviceOwnerCommand(
15919                 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras);
15920     }
15921 
15922     /**
15923      * Transfers the profile owner for user with id profileOwnerUserId from admin to target.
15924      */
15925     private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target,
15926             int profileOwnerUserId) {
15927         transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId);
15928         mOwners.transferProfileOwner(target, profileOwnerUserId);
15929         Slogf.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId);
15930         mOwners.writeProfileOwner(profileOwnerUserId);
15931         mDeviceAdminServiceController.startServiceForOwner(
15932                 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner");
15933     }
15934 
15935     /**
15936      * Transfers the device owner for user with id userId from admin to target.
15937      */
15938     private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) {
15939         transferActiveAdminUncheckedLocked(target, admin, userId);
15940         mOwners.transferDeviceOwnership(target);
15941         Slogf.i(LOG_TAG, "Device owner set: " + target + " on user " + userId);
15942         mOwners.writeDeviceOwner();
15943         mDeviceAdminServiceController.startServiceForOwner(
15944                 target.getPackageName(), userId, "transfer-device-owner");
15945     }
15946 
15947     private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) {
15948         Bundle extras = new Bundle();
15949         if (bundle != null) {
15950             extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle);
15951         }
15952         return extras;
15953     }
15954 
15955     @Override
15956     public void setStartUserSessionMessage(
15957             ComponentName admin, CharSequence startUserSessionMessage) {
15958         if (!mHasFeature) {
15959             return;
15960         }
15961         Objects.requireNonNull(admin, "ComponentName is null");
15962         final CallerIdentity caller = getCallerIdentity(admin);
15963         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
15964 
15965         final String startUserSessionMessageString =
15966                 startUserSessionMessage != null ? startUserSessionMessage.toString() : null;
15967 
15968         synchronized (getLockObject()) {
15969             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
15970             if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) {
15971                 return;
15972             }
15973             deviceOwner.startUserSessionMessage = startUserSessionMessageString;
15974             saveSettingsLocked(caller.getUserId());
15975         }
15976 
15977         mInjector.getActivityManagerInternal()
15978                 .setSwitchingFromSystemUserMessage(startUserSessionMessageString);
15979     }
15980 
15981     @Override
15982     public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) {
15983         if (!mHasFeature) {
15984             return;
15985         }
15986         Objects.requireNonNull(admin, "ComponentName is null");
15987         final CallerIdentity caller = getCallerIdentity(admin);
15988         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
15989 
15990         final String endUserSessionMessageString =
15991                 endUserSessionMessage != null ? endUserSessionMessage.toString() : null;
15992 
15993         synchronized (getLockObject()) {
15994             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
15995             if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) {
15996                 return;
15997             }
15998             deviceOwner.endUserSessionMessage = endUserSessionMessageString;
15999             saveSettingsLocked(caller.getUserId());
16000         }
16001 
16002         mInjector.getActivityManagerInternal()
16003                 .setSwitchingToSystemUserMessage(endUserSessionMessageString);
16004     }
16005 
16006     @Override
16007     public String getStartUserSessionMessage(ComponentName admin) {
16008         if (!mHasFeature) {
16009             return null;
16010         }
16011         Objects.requireNonNull(admin, "ComponentName is null");
16012         final CallerIdentity caller = getCallerIdentity(admin);
16013         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16014 
16015         synchronized (getLockObject()) {
16016             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
16017             return deviceOwner.startUserSessionMessage;
16018         }
16019     }
16020 
16021     @Override
16022     public String getEndUserSessionMessage(ComponentName admin) {
16023         if (!mHasFeature) {
16024             return null;
16025         }
16026         Objects.requireNonNull(admin, "ComponentName is null");
16027         final CallerIdentity caller = getCallerIdentity(admin);
16028         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16029 
16030         synchronized (getLockObject()) {
16031             final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
16032             return deviceOwner.endUserSessionMessage;
16033         }
16034     }
16035 
16036     private void deleteTransferOwnershipMetadataFileLocked() {
16037         mTransferOwnershipMetadataManager.deleteMetadataFile();
16038     }
16039 
16040     @Override
16041     @Nullable
16042     public PersistableBundle getTransferOwnershipBundle() {
16043         final CallerIdentity caller = getCallerIdentity();
16044         Preconditions.checkCallAuthorization(isProfileOwner(caller) || isDeviceOwner(caller));
16045 
16046         synchronized (getLockObject()) {
16047             final int callingUserId = caller.getUserId();
16048             final File bundleFile = new File(
16049                     mInjector.environmentGetUserSystemDirectory(callingUserId),
16050                     TRANSFER_OWNERSHIP_PARAMETERS_XML);
16051             if (!bundleFile.exists()) {
16052                 return null;
16053             }
16054             try (FileInputStream stream = new FileInputStream(bundleFile)) {
16055                 TypedXmlPullParser parser = Xml.resolvePullParser(stream);
16056                 parser.next();
16057                 return PersistableBundle.restoreFromXml(parser);
16058             } catch (IOException | XmlPullParserException | IllegalArgumentException e) {
16059                 Slogf.e(LOG_TAG, "Caught exception while trying to load the "
16060                         + "owner transfer parameters from file " + bundleFile, e);
16061                 return null;
16062             }
16063         }
16064     }
16065 
16066     @Override
16067     public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) {
16068         if (!mHasFeature || !mHasTelephonyFeature) {
16069             return -1;
16070         }
16071         Objects.requireNonNull(who, "ComponentName is null");
16072         Objects.requireNonNull(apnSetting, "ApnSetting is null in addOverrideApn");
16073         final CallerIdentity caller = getCallerIdentity(who);
16074         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16075 
16076         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
16077         if (tm != null) {
16078             return mInjector.binderWithCleanCallingIdentity(
16079                     () -> tm.addDevicePolicyOverrideApn(mContext, apnSetting));
16080         } else {
16081             Slogf.w(LOG_TAG, "TelephonyManager is null when trying to add override apn");
16082             return Telephony.Carriers.INVALID_APN_ID;
16083         }
16084     }
16085 
16086     @Override
16087     public boolean updateOverrideApn(@NonNull ComponentName who, int apnId,
16088             @NonNull ApnSetting apnSetting) {
16089         if (!mHasFeature || !mHasTelephonyFeature) {
16090             return false;
16091         }
16092         Objects.requireNonNull(who, "ComponentName is null");
16093         Objects.requireNonNull(apnSetting, "ApnSetting is null in updateOverrideApn");
16094         final CallerIdentity caller = getCallerIdentity(who);
16095         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16096 
16097         if (apnId < 0) {
16098             return false;
16099         }
16100         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
16101         if (tm != null) {
16102             return mInjector.binderWithCleanCallingIdentity(
16103                     () -> tm.modifyDevicePolicyOverrideApn(mContext, apnId, apnSetting));
16104         } else {
16105             Slogf.w(LOG_TAG, "TelephonyManager is null when trying to modify override apn");
16106             return false;
16107         }
16108     }
16109 
16110     @Override
16111     public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) {
16112         if (!mHasFeature || !mHasTelephonyFeature) {
16113             return false;
16114         }
16115         Objects.requireNonNull(who, "ComponentName is null");
16116         final CallerIdentity caller = getCallerIdentity(who);
16117         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16118         return removeOverrideApnUnchecked(apnId);
16119     }
16120 
16121     private boolean removeOverrideApnUnchecked(int apnId) {
16122         if(apnId < 0) {
16123             return false;
16124         }
16125         int numDeleted = mInjector.binderWithCleanCallingIdentity(
16126                 () -> mContext.getContentResolver().delete(
16127                         Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null));
16128         return numDeleted > 0;
16129     }
16130 
16131     @Override
16132     public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) {
16133         if (!mHasFeature || !mHasTelephonyFeature) {
16134             return Collections.emptyList();
16135         }
16136         Objects.requireNonNull(who, "ComponentName is null");
16137         final CallerIdentity caller = getCallerIdentity(who);
16138         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16139         return getOverrideApnsUnchecked();
16140     }
16141 
16142     private List<ApnSetting> getOverrideApnsUnchecked() {
16143         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
16144         if (tm != null) {
16145             return mInjector.binderWithCleanCallingIdentity(
16146                     () -> tm.getDevicePolicyOverrideApns(mContext));
16147         }
16148         Slogf.w(LOG_TAG, "TelephonyManager is null when trying to get override apns");
16149         return Collections.emptyList();
16150     }
16151 
16152     @Override
16153     public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) {
16154         if (!mHasFeature || !mHasTelephonyFeature) {
16155             return;
16156         }
16157         Objects.requireNonNull(who, "ComponentName is null");
16158         final CallerIdentity caller = getCallerIdentity(who);
16159         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16160         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_OVERRIDE_APNS_ENABLED);
16161 
16162         setOverrideApnsEnabledUnchecked(enabled);
16163     }
16164 
16165     private void setOverrideApnsEnabledUnchecked(boolean enabled) {
16166         ContentValues value = new ContentValues();
16167         value.put(ENFORCE_KEY, enabled);
16168         mInjector.binderWithCleanCallingIdentity(() -> mContext.getContentResolver().update(
16169                     ENFORCE_MANAGED_URI, value, null, null));
16170     }
16171 
16172     @Override
16173     public boolean isOverrideApnEnabled(@NonNull ComponentName who) {
16174         if (!mHasFeature || !mHasTelephonyFeature) {
16175             return false;
16176         }
16177         Objects.requireNonNull(who, "ComponentName is null");
16178         final CallerIdentity caller = getCallerIdentity(who);
16179         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16180 
16181         Cursor enforceCursor = mInjector.binderWithCleanCallingIdentity(
16182                 () -> mContext.getContentResolver().query(
16183                         ENFORCE_MANAGED_URI, null, null, null, null));
16184 
16185         if (enforceCursor == null) {
16186             return false;
16187         }
16188         try {
16189             if (enforceCursor.moveToFirst()) {
16190                 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1;
16191             }
16192         } catch (IllegalArgumentException e) {
16193             Slogf.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain "
16194                     + "correct info.", e);
16195         } finally {
16196             enforceCursor.close();
16197         }
16198         return false;
16199     }
16200 
16201     @VisibleForTesting
16202     void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) {
16203         final File parametersFile = new File(
16204                 mInjector.environmentGetUserSystemDirectory(userId),
16205                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
16206         final AtomicFile atomicFile = new AtomicFile(parametersFile);
16207         FileOutputStream stream = null;
16208         try {
16209             stream = atomicFile.startWrite();
16210             final TypedXmlSerializer serializer = Xml.resolveSerializer(stream);
16211             serializer.startDocument(null, true);
16212             serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
16213             bundle.saveToXml(serializer);
16214             serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
16215             serializer.endDocument();
16216             atomicFile.finishWrite(stream);
16217         } catch (IOException | XmlPullParserException e) {
16218             Slogf.e(LOG_TAG, "Caught exception while trying to save the "
16219                     + "owner transfer parameters to file " + parametersFile, e);
16220             parametersFile.delete();
16221             atomicFile.failWrite(stream);
16222         }
16223     }
16224 
16225     void deleteTransferOwnershipBundleLocked(int userId) {
16226         final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId),
16227                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
16228         parametersFile.delete();
16229     }
16230 
16231     private void logPasswordQualitySetIfSecurityLogEnabled(ComponentName who, int userId,
16232             boolean parent, PasswordPolicy passwordPolicy) {
16233         if (SecurityLog.isLoggingEnabled()) {
16234             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
16235             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(),
16236                     userId, affectedUserId, passwordPolicy.length, passwordPolicy.quality,
16237                     passwordPolicy.letters, passwordPolicy.nonLetter, passwordPolicy.numeric,
16238                     passwordPolicy.upperCase, passwordPolicy.lowerCase, passwordPolicy.symbols);
16239         }
16240     }
16241 
16242     private static String getManagedProvisioningPackage(Context context) {
16243         return context.getResources().getString(R.string.config_managed_provisioning_package);
16244     }
16245 
16246     private void putPrivateDnsSettings(int mode, @Nullable String host) {
16247         // Set Private DNS settings using system permissions, as apps cannot write
16248         // to global settings.
16249         mInjector.binderWithCleanCallingIdentity(() -> {
16250             ConnectivitySettingsManager.setPrivateDnsMode(mContext, mode);
16251             ConnectivitySettingsManager.setPrivateDnsHostname(mContext, host);
16252         });
16253     }
16254 
16255     @Override
16256     public int setGlobalPrivateDns(@NonNull ComponentName who, int mode, String privateDnsHost) {
16257         if (!mHasFeature) {
16258             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
16259         }
16260         Objects.requireNonNull(who, "ComponentName is null");
16261         final CallerIdentity caller = getCallerIdentity(who);
16262         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16263         checkAllUsersAreAffiliatedWithDevice();
16264         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_SET_GLOBAL_PRIVATE_DNS);
16265 
16266         switch (mode) {
16267             case PRIVATE_DNS_MODE_OPPORTUNISTIC:
16268                 if (!TextUtils.isEmpty(privateDnsHost)) {
16269                     throw new IllegalArgumentException(
16270                             "Host provided for opportunistic mode, but is not needed.");
16271                 }
16272                 putPrivateDnsSettings(ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC,
16273                         null);
16274                 return PRIVATE_DNS_SET_NO_ERROR;
16275             case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
16276                 if (TextUtils.isEmpty(privateDnsHost)
16277                         || !NetworkUtilsInternal.isWeaklyValidatedHostname(privateDnsHost)) {
16278                     throw new IllegalArgumentException(
16279                             String.format("Provided hostname %s is not valid", privateDnsHost));
16280                 }
16281 
16282                 // Connectivity check will have been performed in the DevicePolicyManager before
16283                 // the call here.
16284                 putPrivateDnsSettings(
16285                         ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
16286                         privateDnsHost);
16287                 return PRIVATE_DNS_SET_NO_ERROR;
16288             default:
16289                 throw new IllegalArgumentException(
16290                         String.format("Provided mode, %d, is not a valid mode.", mode));
16291         }
16292     }
16293 
16294     @Override
16295     public int getGlobalPrivateDnsMode(@NonNull ComponentName who) {
16296         if (!mHasFeature) {
16297             return PRIVATE_DNS_MODE_UNKNOWN;
16298         }
16299         Objects.requireNonNull(who, "ComponentName is null");
16300         final CallerIdentity caller = getCallerIdentity(who);
16301         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16302 
16303         final int currentMode = ConnectivitySettingsManager.getPrivateDnsMode(mContext);
16304         switch (currentMode) {
16305             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OFF:
16306                 return PRIVATE_DNS_MODE_OFF;
16307             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC:
16308                 return PRIVATE_DNS_MODE_OPPORTUNISTIC;
16309             case ConnectivitySettingsManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
16310                 return PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
16311         }
16312 
16313         return PRIVATE_DNS_MODE_UNKNOWN;
16314     }
16315 
16316     @Override
16317     public String getGlobalPrivateDnsHost(@NonNull ComponentName who) {
16318         if (!mHasFeature) {
16319             return null;
16320         }
16321         Objects.requireNonNull(who, "ComponentName is null");
16322         final CallerIdentity caller = getCallerIdentity(who);
16323         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16324         return mInjector.settingsGlobalGetString(PRIVATE_DNS_SPECIFIER);
16325     }
16326 
16327     @Override
16328     public void installUpdateFromFile(ComponentName admin,
16329             ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback) {
16330         Objects.requireNonNull(admin, "ComponentName is null");
16331 
16332         final CallerIdentity caller = getCallerIdentity(admin);
16333         Preconditions.checkCallAuthorization(isDeviceOwner(caller)
16334                 || isProfileOwnerOfOrganizationOwnedDevice(caller));
16335         checkCanExecuteOrThrowUnsafe(DevicePolicyManager.OPERATION_INSTALL_SYSTEM_UPDATE);
16336 
16337         DevicePolicyEventLogger
16338                 .createEvent(DevicePolicyEnums.INSTALL_SYSTEM_UPDATE)
16339                 .setAdmin(caller.getComponentName())
16340                 .setBoolean(isDeviceAB())
16341                 .write();
16342 
16343         mInjector.binderWithCleanCallingIdentity(() -> {
16344             UpdateInstaller updateInstaller;
16345             if (isDeviceAB()) {
16346                 updateInstaller = new AbUpdateInstaller(
16347                         mContext, updateFileDescriptor, callback, mInjector, mConstants);
16348             } else {
16349                 updateInstaller = new NonAbUpdateInstaller(
16350                         mContext, updateFileDescriptor, callback, mInjector, mConstants);
16351             }
16352             updateInstaller.startInstallUpdate();
16353         });
16354     }
16355 
16356     private boolean isDeviceAB() {
16357         return "true".equalsIgnoreCase(android.os.SystemProperties
16358                 .get(AB_DEVICE_KEY, ""));
16359     }
16360 
16361     @Override
16362     public void setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames) {
16363         if (!mHasFeature) {
16364             return;
16365         }
16366         Objects.requireNonNull(who, "ComponentName is null");
16367         final CallerIdentity caller = getCallerIdentity(who);
16368 
16369         synchronized (getLockObject()) {
16370             final ActiveAdmin admin = getProfileOwnerLocked(caller);
16371             admin.mCrossProfileCalendarPackages = packageNames;
16372             saveSettingsLocked(caller.getUserId());
16373         }
16374         DevicePolicyEventLogger
16375                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALENDAR_PACKAGES)
16376                 .setAdmin(who)
16377                 .setStrings(packageNames == null ? null
16378                         : packageNames.toArray(new String[packageNames.size()]))
16379                 .write();
16380     }
16381 
16382     @Override
16383     public List<String> getCrossProfileCalendarPackages(ComponentName who) {
16384         if (!mHasFeature) {
16385             return Collections.emptyList();
16386         }
16387         Objects.requireNonNull(who, "ComponentName is null");
16388         final CallerIdentity caller = getCallerIdentity(who);
16389 
16390         synchronized (getLockObject()) {
16391             final ActiveAdmin admin = getProfileOwnerLocked(caller);
16392             return admin.mCrossProfileCalendarPackages;
16393         }
16394     }
16395 
16396     @Override
16397     public boolean isPackageAllowedToAccessCalendarForUser(String packageName,
16398             int userHandle) {
16399         if (!mHasFeature) {
16400             return false;
16401         }
16402         Preconditions.checkStringNotEmpty(packageName, "Package name is null or empty");
16403         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
16404 
16405         final CallerIdentity caller = getCallerIdentity();
16406         final int packageUid = mInjector.binderWithCleanCallingIdentity(() -> {
16407             try {
16408                 return mInjector.getPackageManager().getPackageUidAsUser(packageName, userHandle);
16409             } catch (NameNotFoundException e) {
16410                 Slogf.w(LOG_TAG, e,
16411                         "Couldn't find package %s in user %d", packageName, userHandle);
16412                 return -1;
16413             }
16414         });
16415         if (caller.getUid() != packageUid) {
16416             Preconditions.checkCallAuthorization(
16417                     hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)
16418                             || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL));
16419         }
16420 
16421         synchronized (getLockObject()) {
16422             if (mInjector.settingsSecureGetIntForUser(
16423                     Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userHandle) == 0) {
16424                 return false;
16425             }
16426             final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
16427             if (admin != null) {
16428                 if (admin.mCrossProfileCalendarPackages == null) {
16429                     return true;
16430                 }
16431                 return admin.mCrossProfileCalendarPackages.contains(packageName);
16432             }
16433         }
16434         return false;
16435     }
16436 
16437     @Override
16438     public List<String> getCrossProfileCalendarPackagesForUser(int userHandle) {
16439         if (!mHasFeature) {
16440             return Collections.emptyList();
16441         }
16442         Preconditions.checkArgumentNonnegative(userHandle, "Invalid userId");
16443         Preconditions.checkCallAuthorization(
16444                 hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS)
16445                         || hasCallingOrSelfPermission(permission.INTERACT_ACROSS_USERS_FULL));
16446 
16447         synchronized (getLockObject()) {
16448             final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
16449             if (admin != null) {
16450                 return admin.mCrossProfileCalendarPackages;
16451             }
16452         }
16453         return Collections.emptyList();
16454     }
16455 
16456     @Override
16457     public void setCrossProfilePackages(ComponentName who, List<String> packageNames) {
16458         if (!mHasFeature) {
16459             return;
16460         }
16461         Objects.requireNonNull(who, "ComponentName is null");
16462         Objects.requireNonNull(packageNames, "Package names is null");
16463         final CallerIdentity caller = getCallerIdentity(who);
16464 
16465         final List<String> previousCrossProfilePackages;
16466         synchronized (getLockObject()) {
16467             final ActiveAdmin admin = getProfileOwnerLocked(caller);
16468             previousCrossProfilePackages = admin.mCrossProfilePackages;
16469             if (packageNames.equals(previousCrossProfilePackages)) {
16470                 return;
16471             }
16472             admin.mCrossProfilePackages = packageNames;
16473             saveSettingsLocked(caller.getUserId());
16474         }
16475         logSetCrossProfilePackages(who, packageNames);
16476         final CrossProfileApps crossProfileApps = mContext.getSystemService(CrossProfileApps.class);
16477         mInjector.binderWithCleanCallingIdentity(
16478                 () -> crossProfileApps.resetInteractAcrossProfilesAppOps(
16479                         previousCrossProfilePackages, new HashSet<>(packageNames)));
16480     }
16481 
16482     private void logSetCrossProfilePackages(ComponentName who, List<String> packageNames) {
16483         DevicePolicyEventLogger
16484                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_PACKAGES)
16485                 .setAdmin(who)
16486                 .setStrings(packageNames.toArray(new String[packageNames.size()]))
16487                 .write();
16488     }
16489 
16490     @Override
16491     public List<String> getCrossProfilePackages(ComponentName who) {
16492         if (!mHasFeature) {
16493             return Collections.emptyList();
16494         }
16495         Objects.requireNonNull(who, "ComponentName is null");
16496         final CallerIdentity caller = getCallerIdentity(who);
16497 
16498         synchronized (getLockObject()) {
16499             final ActiveAdmin admin = getProfileOwnerLocked(caller);
16500             return admin.mCrossProfilePackages;
16501         }
16502     }
16503 
16504     @Override
16505     public List<String> getAllCrossProfilePackages() {
16506         if (!mHasFeature) {
16507             return Collections.emptyList();
16508         }
16509         final CallerIdentity caller = getCallerIdentity();
16510         Preconditions.checkCallAuthorization(
16511                 isSystemUid(caller) || isRootUid(caller) || hasCallingPermission(
16512                         permission.INTERACT_ACROSS_USERS) || hasCallingPermission(
16513                         permission.INTERACT_ACROSS_USERS_FULL) || hasPermissionForPreflight(
16514                         caller, permission.INTERACT_ACROSS_PROFILES));
16515 
16516         synchronized (getLockObject()) {
16517             final List<ActiveAdmin> admins = getProfileOwnerAdminsForCurrentProfileGroup();
16518             final List<String> packages = getCrossProfilePackagesForAdmins(admins);
16519 
16520             packages.addAll(getDefaultCrossProfilePackages());
16521 
16522             return packages;
16523         }
16524     }
16525 
16526     private List<String> getCrossProfilePackagesForAdmins(List<ActiveAdmin> admins) {
16527         final List<String> packages = new ArrayList<>();
16528         for (int i = 0; i < admins.size(); i++) {
16529             packages.addAll(admins.get(i).mCrossProfilePackages);
16530         }
16531         return packages;
16532     }
16533 
16534     @Override
16535     public List<String> getDefaultCrossProfilePackages() {
16536         Set<String> crossProfilePackages = new HashSet<>();
16537 
16538         Collections.addAll(crossProfilePackages, mContext.getResources()
16539                 .getStringArray(R.array.cross_profile_apps));
16540         Collections.addAll(crossProfilePackages, mContext.getResources()
16541                 .getStringArray(R.array.vendor_cross_profile_apps));
16542 
16543         return new ArrayList<>(crossProfilePackages);
16544     }
16545 
16546     private List<ActiveAdmin> getProfileOwnerAdminsForCurrentProfileGroup() {
16547         synchronized (getLockObject()) {
16548             final List<ActiveAdmin> admins = new ArrayList<>();
16549             int[] users = mUserManager.getProfileIdsWithDisabled(
16550                     mInjector.userHandleGetCallingUserId());
16551             for (int i = 0; i < users.length; i++) {
16552                 final ComponentName componentName = getProfileOwnerAsUser(users[i]);
16553                 if (componentName != null) {
16554                     ActiveAdmin admin = getActiveAdminUncheckedLocked(componentName, users[i]);
16555                     if (admin != null) {
16556                         admins.add(admin);
16557                     }
16558                 }
16559             }
16560             return admins;
16561         }
16562     }
16563 
16564     @Override
16565     public boolean isManagedKiosk() {
16566         if (!mHasFeature) {
16567             return false;
16568         }
16569         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
16570 
16571         long id = mInjector.binderClearCallingIdentity();
16572         try {
16573             return isManagedKioskInternal();
16574         } catch (RemoteException e) {
16575             throw new IllegalStateException(e);
16576         } finally {
16577             mInjector.binderRestoreCallingIdentity(id);
16578         }
16579     }
16580 
16581     private boolean isUnattendedManagedKioskUnchecked() {
16582         try {
16583             return isManagedKioskInternal()
16584                     && getPowerManagerInternal().wasDeviceIdleFor(UNATTENDED_MANAGED_KIOSK_MS);
16585         } catch (RemoteException e) {
16586             throw new IllegalStateException(e);
16587         }
16588     }
16589 
16590     @Override
16591     public boolean isUnattendedManagedKiosk() {
16592         if (!mHasFeature) {
16593             return false;
16594         }
16595         Preconditions.checkCallAuthorization(canManageUsers(getCallerIdentity()));
16596 
16597         return mInjector.binderWithCleanCallingIdentity(() -> isUnattendedManagedKioskUnchecked());
16598     }
16599 
16600     /**
16601      * Returns whether the device is currently being used as a publicly-accessible dedicated device.
16602      * Assumes that feature checks and permission checks have already been performed, and that the
16603      * calling identity has been cleared.
16604      */
16605     private boolean isManagedKioskInternal() throws RemoteException {
16606         return mOwners.hasDeviceOwner()
16607                 && mInjector.getIActivityManager().getLockTaskModeState()
16608                         == ActivityManager.LOCK_TASK_MODE_LOCKED
16609                 && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO)
16610                 && !deviceHasKeyguard()
16611                 && !inEphemeralUserSession();
16612     }
16613 
16614     private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException {
16615         //TODO(b/175285301): Explicitly get the user's identity to check.
16616         int lockTaskFeatures =
16617                 getUserData(getCurrentForegroundUserId()).mLockTaskFeatures;
16618         return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature;
16619     }
16620 
16621     private boolean deviceHasKeyguard() {
16622         for (UserInfo userInfo : mUserManager.getUsers()) {
16623             if (mLockPatternUtils.isSecure(userInfo.id)) {
16624                 return true;
16625             }
16626         }
16627         return false;
16628     }
16629 
16630     private boolean inEphemeralUserSession() {
16631         for (UserInfo userInfo : mUserManager.getUsers()) {
16632             if (mInjector.getUserManager().isUserEphemeral(userInfo.id)) {
16633                 return true;
16634             }
16635         }
16636         return false;
16637     }
16638 
16639     private PowerManagerInternal getPowerManagerInternal() {
16640         return mInjector.getPowerManagerInternal();
16641     }
16642 
16643     @Override
16644     public boolean startViewCalendarEventInManagedProfile(String packageName, long eventId,
16645             long start, long end, boolean allDay, int flags) {
16646         if (!mHasFeature) {
16647             return false;
16648         }
16649         Preconditions.checkStringNotEmpty(packageName, "Package name is empty");
16650 
16651         final CallerIdentity caller = getCallerIdentity();
16652         if (!isCallingFromPackage(packageName, caller.getUid())) {
16653             throw new SecurityException("Input package name doesn't align with actual "
16654                     + "calling package.");
16655         }
16656         return mInjector.binderWithCleanCallingIdentity(() -> {
16657             final int workProfileUserId = getManagedUserId(caller.getUserId());
16658             if (workProfileUserId < 0) {
16659                 return false;
16660             }
16661             if (!isPackageAllowedToAccessCalendarForUser(packageName, workProfileUserId)) {
16662                 Slogf.d(LOG_TAG, "Package %s is not allowed to access cross-profile calendar APIs",
16663                         packageName);
16664                 return false;
16665             }
16666             final Intent intent = new Intent(
16667                     CalendarContract.ACTION_VIEW_MANAGED_PROFILE_CALENDAR_EVENT);
16668             intent.setPackage(packageName);
16669             intent.putExtra(CalendarContract.EXTRA_EVENT_ID, eventId);
16670             intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start);
16671             intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
16672             intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay);
16673             intent.setFlags(flags);
16674             try {
16675                 mContext.startActivityAsUser(intent, UserHandle.of(workProfileUserId));
16676             } catch (ActivityNotFoundException e) {
16677                 Slogf.e(LOG_TAG, "View event activity not found", e);
16678                 return false;
16679             }
16680             return true;
16681         });
16682     }
16683 
16684     private boolean isCallingFromPackage(String packageName, int callingUid) {
16685         return mInjector.binderWithCleanCallingIdentity(() -> {
16686             try {
16687                 final int packageUid = mInjector.getPackageManager().getPackageUidAsUser(
16688                         packageName, UserHandle.getUserId(callingUid));
16689                 return packageUid == callingUid;
16690             } catch (NameNotFoundException e) {
16691                 Slogf.d(LOG_TAG, "Calling package not found", e);
16692                 return false;
16693             }
16694         });
16695     }
16696 
16697     private DevicePolicyConstants loadConstants() {
16698         return DevicePolicyConstants.loadFromString(
16699                 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
16700     }
16701 
16702     @Override
16703     public void setUserControlDisabledPackages(ComponentName who, List<String> packages) {
16704         Objects.requireNonNull(who, "ComponentName is null");
16705         Objects.requireNonNull(packages, "packages is null");
16706         final CallerIdentity caller = getCallerIdentity(who);
16707         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16708         checkCanExecuteOrThrowUnsafe(
16709                 DevicePolicyManager.OPERATION_SET_USER_CONTROL_DISABLED_PACKAGES);
16710 
16711         synchronized (getLockObject()) {
16712             mOwners.setDeviceOwnerProtectedPackages(who.getPackageName(), packages);
16713             DevicePolicyEventLogger
16714                     .createEvent(DevicePolicyEnums.SET_USER_CONTROL_DISABLED_PACKAGES)
16715                     .setAdmin(who)
16716                     .setStrings(packages.toArray(new String[packages.size()]))
16717                     .write();
16718         }
16719     }
16720 
16721     @Override
16722     public List<String> getUserControlDisabledPackages(ComponentName who) {
16723         Objects.requireNonNull(who, "ComponentName is null");
16724 
16725         final CallerIdentity caller = getCallerIdentity(who);
16726         Preconditions.checkCallAuthorization(isDeviceOwner(caller));
16727 
16728         synchronized (getLockObject()) {
16729             return mOwners.getDeviceOwnerProtectedPackages(who.getPackageName());
16730         }
16731     }
16732 
16733     @Override
16734     public void setCommonCriteriaModeEnabled(ComponentName who, boolean enabled) {
16735         Objects.requireNonNull(who, "Admin component name must be provided");
16736         final CallerIdentity caller = getCallerIdentity(who);
16737         Preconditions.checkCallAuthorization(
16738                 isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
16739                 "Common Criteria mode can only be controlled by a device owner or "
16740                         + "a profile owner on an organization-owned device.");
16741         synchronized (getLockObject()) {
16742             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
16743             admin.mCommonCriteriaMode = enabled;
16744             saveSettingsLocked(caller.getUserId());
16745         }
16746         DevicePolicyEventLogger
16747                 .createEvent(DevicePolicyEnums.SET_COMMON_CRITERIA_MODE)
16748                 .setAdmin(who)
16749                 .setBoolean(enabled)
16750                 .write();
16751     }
16752 
16753     @Override
16754     public boolean isCommonCriteriaModeEnabled(ComponentName who) {
16755         if (who != null) {
16756             final CallerIdentity caller = getCallerIdentity(who);
16757             Preconditions.checkCallAuthorization(
16758                     isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
16759                     "Common Criteria mode can only be controlled by a device owner or "
16760                             + "a profile owner on an organization-owned device.");
16761 
16762             synchronized (getLockObject()) {
16763                 final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
16764                 return admin.mCommonCriteriaMode;
16765             }
16766         }
16767         // Return aggregated state if caller is not admin (who == null).
16768         synchronized (getLockObject()) {
16769             // Only DO or COPE PO can turn on CC mode, so take a shortcut here and only look at
16770             // their ActiveAdmin, instead of iterating through all admins.
16771             final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
16772                     UserHandle.USER_SYSTEM);
16773             return admin != null ? admin.mCommonCriteriaMode : false;
16774         }
16775     }
16776 
16777     @Override
16778     public @PersonalAppsSuspensionReason int getPersonalAppsSuspendedReasons(ComponentName who) {
16779         Objects.requireNonNull(who, "ComponentName is null");
16780 
16781         final CallerIdentity caller = getCallerIdentity(who);
16782         // DO shouldn't be able to use this method.
16783         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
16784 
16785         synchronized (getLockObject()) {
16786             final ActiveAdmin admin = getProfileOwnerLocked(caller);
16787             final long deadline = admin.mProfileOffDeadline;
16788             final int result = makeSuspensionReasons(admin.mSuspendPersonalApps,
16789                     deadline != 0 && mInjector.systemCurrentTimeMillis() > deadline);
16790             Slogf.d(LOG_TAG, "getPersonalAppsSuspendedReasons user: %d; result: %d",
16791                     mInjector.userHandleGetCallingUserId(), result);
16792             return result;
16793         }
16794     }
16795 
16796     private @PersonalAppsSuspensionReason int makeSuspensionReasons(
16797             boolean explicit, boolean timeout) {
16798         int result = PERSONAL_APPS_NOT_SUSPENDED;
16799         if (explicit) {
16800             result |= PERSONAL_APPS_SUSPENDED_EXPLICITLY;
16801         }
16802         if (timeout) {
16803             result |= PERSONAL_APPS_SUSPENDED_PROFILE_TIMEOUT;
16804         }
16805         return result;
16806     }
16807 
16808     @Override
16809     public void setPersonalAppsSuspended(ComponentName who, boolean suspended) {
16810         Objects.requireNonNull(who, "ComponentName is null");
16811 
16812         final CallerIdentity caller = getCallerIdentity(who);
16813         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
16814         Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller));
16815 
16816         final int callingUserId = caller.getUserId();
16817         synchronized (getLockObject()) {
16818             final ActiveAdmin admin = getProfileOwnerLocked(caller);
16819             boolean shouldSaveSettings = false;
16820             if (admin.mSuspendPersonalApps != suspended) {
16821                 admin.mSuspendPersonalApps = suspended;
16822                 shouldSaveSettings = true;
16823             }
16824             if (admin.mProfileOffDeadline != 0) {
16825                 admin.mProfileOffDeadline = 0;
16826                 shouldSaveSettings = true;
16827             }
16828             if (shouldSaveSettings) {
16829                 saveSettingsLocked(callingUserId);
16830             }
16831         }
16832 
16833         mInjector.binderWithCleanCallingIdentity(() -> updatePersonalAppsSuspension(
16834                 callingUserId, mUserManager.isUserUnlocked(callingUserId)));
16835 
16836         DevicePolicyEventLogger
16837                 .createEvent(DevicePolicyEnums.SET_PERSONAL_APPS_SUSPENDED)
16838                 .setAdmin(caller.getComponentName())
16839                 .setBoolean(suspended)
16840                 .write();
16841     }
16842 
16843     /** Starts an activity to check policy compliance or request compliance acknowledgement. */
16844     private void triggerPolicyComplianceCheckIfNeeded(int profileUserId, boolean suspended) {
16845         synchronized (getLockObject()) {
16846             final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
16847             if (profileOwner == null) {
16848                 Slogf.wtf(LOG_TAG, "Profile owner not found for compliance check");
16849                 return;
16850             }
16851             if (suspended) {
16852                 // If suspended, DPC will need to show an activity.
16853                 final Intent intent = new Intent(ACTION_CHECK_POLICY_COMPLIANCE);
16854                 intent.setPackage(profileOwner.info.getPackageName());
16855                 mContext.startActivityAsUser(intent, UserHandle.of(profileUserId));
16856             } else if (profileOwner.mProfileOffDeadline > 0) {
16857                 // If not suspended, but deadline set, DPC needs to acknowledge compliance so that
16858                 // the deadline can be reset.
16859                 sendAdminCommandLocked(profileOwner, ACTION_COMPLIANCE_ACKNOWLEDGEMENT_REQUIRED,
16860                         /* adminExtras= */ null, /* receiver= */ null, /* inForeground = */ true);
16861             }
16862         }
16863     }
16864 
16865     /**
16866      * Checks whether personal apps should be suspended according to the policy and applies the
16867      * change if needed.
16868      *
16869      * @param unlocked whether the profile is currently running unlocked.
16870      */
16871     private boolean updatePersonalAppsSuspension(int profileUserId, boolean unlocked) {
16872         final boolean shouldSuspend;
16873         synchronized (getLockObject()) {
16874             final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(profileUserId);
16875             if (profileOwner != null) {
16876                 final int notificationState =
16877                         updateProfileOffDeadlineLocked(profileUserId, profileOwner, unlocked);
16878                 final boolean suspendedExplicitly = profileOwner.mSuspendPersonalApps;
16879                 final boolean suspendedByTimeout = profileOwner.mProfileOffDeadline == -1;
16880                 Slogf.d(LOG_TAG,
16881                         "Personal apps suspended explicitly: %b, by timeout: %b, notification: %d",
16882                         suspendedExplicitly, suspendedByTimeout, notificationState);
16883                 updateProfileOffDeadlineNotificationLocked(
16884                         profileUserId, profileOwner, notificationState);
16885                 shouldSuspend = suspendedExplicitly || suspendedByTimeout;
16886             } else {
16887                 shouldSuspend = false;
16888             }
16889         }
16890 
16891         final int parentUserId = getProfileParentId(profileUserId);
16892         suspendPersonalAppsInternal(parentUserId, shouldSuspend);
16893         return shouldSuspend;
16894     }
16895 
16896     /**
16897      * Checks work profile time off policy, scheduling personal apps suspension via alarm if
16898      * necessary.
16899      * @return notification state
16900      */
16901     private int updateProfileOffDeadlineLocked(
16902             int profileUserId, ActiveAdmin profileOwner, boolean unlocked) {
16903         final long now = mInjector.systemCurrentTimeMillis();
16904         if (profileOwner.mProfileOffDeadline != 0 && now > profileOwner.mProfileOffDeadline) {
16905             Slogf.i(LOG_TAG, "Profile off deadline has been reached, unlocked: " + unlocked);
16906             if (profileOwner.mProfileOffDeadline != -1) {
16907                 // Move the deadline far to the past so that it cannot be rolled back by TZ change.
16908                 profileOwner.mProfileOffDeadline = -1;
16909                 saveSettingsLocked(profileUserId);
16910             }
16911             return unlocked ? PROFILE_OFF_NOTIFICATION_NONE : PROFILE_OFF_NOTIFICATION_SUSPENDED;
16912         }
16913         boolean shouldSaveSettings = false;
16914         if (profileOwner.mSuspendPersonalApps) {
16915             // When explicit suspension is active, deadline shouldn't be set.
16916             if (profileOwner.mProfileOffDeadline != 0) {
16917                 profileOwner.mProfileOffDeadline = 0;
16918                 shouldSaveSettings = true;
16919             }
16920         } else if (profileOwner.mProfileOffDeadline != 0
16921                 && (profileOwner.mProfileMaximumTimeOffMillis == 0)) {
16922             // There is a deadline but either there is no policy -> clear
16923             // the deadline.
16924             Slogf.i(LOG_TAG, "Profile off deadline is reset to zero");
16925             profileOwner.mProfileOffDeadline = 0;
16926             shouldSaveSettings = true;
16927         } else if (profileOwner.mProfileOffDeadline == 0
16928                 && (profileOwner.mProfileMaximumTimeOffMillis != 0 && !unlocked)) {
16929             // There profile is locked and there is a policy, but the deadline is not set -> set the
16930             // deadline.
16931             Slogf.i(LOG_TAG, "Profile off deadline is set.");
16932             profileOwner.mProfileOffDeadline = now + profileOwner.mProfileMaximumTimeOffMillis;
16933             shouldSaveSettings = true;
16934         }
16935 
16936         if (shouldSaveSettings) {
16937             saveSettingsLocked(profileUserId);
16938         }
16939 
16940         final long alarmTime;
16941         final int notificationState;
16942         if (unlocked || profileOwner.mProfileOffDeadline == 0) {
16943             alarmTime = 0;
16944             notificationState = PROFILE_OFF_NOTIFICATION_NONE;
16945         } else if (profileOwner.mProfileOffDeadline - now < MANAGED_PROFILE_OFF_WARNING_PERIOD) {
16946             // The deadline is close, upon the alarm personal apps should be suspended.
16947             alarmTime = profileOwner.mProfileOffDeadline;
16948             notificationState = PROFILE_OFF_NOTIFICATION_WARNING;
16949         } else {
16950             // The deadline is quite far, upon the alarm we should warn the user first, so the
16951             // alarm is scheduled earlier than the actual deadline.
16952             alarmTime = profileOwner.mProfileOffDeadline - MANAGED_PROFILE_OFF_WARNING_PERIOD;
16953             notificationState = PROFILE_OFF_NOTIFICATION_NONE;
16954         }
16955 
16956         final AlarmManager am = mInjector.getAlarmManager();
16957         final Intent intent = new Intent(ACTION_PROFILE_OFF_DEADLINE);
16958         intent.setPackage(mContext.getPackageName());
16959         // Broadcast alarms sent by system are immutable
16960         final PendingIntent pi = mInjector.pendingIntentGetBroadcast(
16961                 mContext, REQUEST_PROFILE_OFF_DEADLINE, intent,
16962                 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT
16963                         | PendingIntent.FLAG_IMMUTABLE);
16964 
16965         if (alarmTime == 0) {
16966             Slogf.i(LOG_TAG, "Profile off deadline alarm is removed.");
16967             am.cancel(pi);
16968         } else {
16969             Slogf.i(LOG_TAG, "Profile off deadline alarm is set.");
16970             am.set(AlarmManager.RTC, alarmTime, pi);
16971         }
16972 
16973         return notificationState;
16974     }
16975 
16976     private void suspendPersonalAppsInternal(int userId, boolean suspended) {
16977         if (getUserData(userId).mAppsSuspended == suspended) {
16978             return;
16979         }
16980         Slogf.i(LOG_TAG, "%s personal apps for user %d", suspended ? "Suspending" : "Unsuspending",
16981                 userId);
16982 
16983         if (suspended) {
16984             suspendPersonalAppsInPackageManager(userId);
16985         } else {
16986             mInjector.getPackageManagerInternal().unsuspendForSuspendingPackage(
16987                     PLATFORM_PACKAGE_NAME, userId);
16988         }
16989 
16990         synchronized (getLockObject()) {
16991             getUserData(userId).mAppsSuspended = suspended;
16992             saveSettingsLocked(userId);
16993         }
16994     }
16995 
16996     private void suspendPersonalAppsInPackageManager(int userId) {
16997         mInjector.binderWithCleanCallingIdentity(() -> {
16998             try {
16999                 final String[] appsToSuspend = mInjector.getPersonalAppsForSuspension(userId);
17000                 final String[] failedApps = mIPackageManager.setPackagesSuspendedAsUser(
17001                         appsToSuspend, true, null, null, null, PLATFORM_PACKAGE_NAME, userId);
17002                 if (!ArrayUtils.isEmpty(failedApps)) {
17003                     Slogf.wtf(LOG_TAG, "Failed to suspend apps: " + String.join(",", failedApps));
17004                 }
17005             } catch (RemoteException re) {
17006                 // Shouldn't happen.
17007                 Slogf.e(LOG_TAG, "Failed talking to the package manager", re);
17008             }
17009         });
17010     }
17011 
17012     @GuardedBy("getLockObject()")
17013     private void updateProfileOffDeadlineNotificationLocked(
17014             int profileUserId, ActiveAdmin profileOwner, int notificationState) {
17015         if (notificationState == PROFILE_OFF_NOTIFICATION_NONE) {
17016             mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED);
17017             return;
17018         }
17019 
17020         final Intent intent = new Intent(ACTION_TURN_PROFILE_ON_NOTIFICATION);
17021         intent.setPackage(mContext.getPackageName());
17022         intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
17023 
17024         // Simple notification action button clicks are immutable
17025         final PendingIntent pendingIntent = mInjector.pendingIntentGetBroadcast(mContext,
17026                 0 /* requestCode */, intent,
17027                 PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
17028 
17029         final String buttonText =
17030                 mContext.getString(R.string.personal_apps_suspended_turn_profile_on);
17031         final Notification.Action turnProfileOnButton =
17032                 new Notification.Action.Builder(null /* icon */, buttonText, pendingIntent).build();
17033 
17034         final String text;
17035         final boolean ongoing;
17036         if (notificationState == PROFILE_OFF_NOTIFICATION_WARNING) {
17037             // Round to the closest integer number of days.
17038             final int maxDays = (int)
17039                     ((profileOwner.mProfileMaximumTimeOffMillis + MS_PER_DAY / 2) / MS_PER_DAY);
17040             final String date = DateUtils.formatDateTime(
17041                     mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_DATE);
17042             final String time = DateUtils.formatDateTime(
17043                     mContext, profileOwner.mProfileOffDeadline, DateUtils.FORMAT_SHOW_TIME);
17044             text = mContext.getString(
17045                     R.string.personal_apps_suspension_soon_text, date, time, maxDays);
17046             ongoing = false;
17047         } else {
17048             text = mContext.getString(R.string.personal_apps_suspension_text);
17049             ongoing = true;
17050         }
17051         final int color = mContext.getColor(R.color.personal_apps_suspension_notification_color);
17052         final Bundle extras = new Bundle();
17053         // TODO: Create a separate string for this.
17054         extras.putString(Notification.EXTRA_SUBSTITUTE_APP_NAME,
17055                 mContext.getString(R.string.notification_work_profile_content_description));
17056 
17057         final Notification notification =
17058                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
17059                         .setSmallIcon(R.drawable.ic_corp_badge_no_background)
17060                         .setOngoing(ongoing)
17061                         .setAutoCancel(false)
17062                         .setContentTitle(mContext.getString(
17063                                 R.string.personal_apps_suspension_title))
17064                         .setContentText(text)
17065                         .setStyle(new Notification.BigTextStyle().bigText(text))
17066                         .setColor(color)
17067                         .addAction(turnProfileOnButton)
17068                         .addExtras(extras)
17069                         .build();
17070         mInjector.getNotificationManager().notify(
17071                 SystemMessage.NOTE_PERSONAL_APPS_SUSPENDED, notification);
17072     }
17073 
17074     @Override
17075     public void setManagedProfileMaximumTimeOff(ComponentName who, long timeoutMillis) {
17076         Objects.requireNonNull(who, "ComponentName is null");
17077         Preconditions.checkArgumentNonnegative(timeoutMillis, "Timeout must be non-negative.");
17078 
17079         final CallerIdentity caller = getCallerIdentity(who);
17080         // DO shouldn't be able to use this method.
17081         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
17082         Preconditions.checkState(canHandleCheckPolicyComplianceIntent(caller));
17083 
17084         final int userId = caller.getUserId();
17085         synchronized (getLockObject()) {
17086             final ActiveAdmin admin = getProfileOwnerLocked(caller);
17087 
17088             // Ensure the timeout is long enough to avoid having bad user experience.
17089             if (timeoutMillis > 0 && timeoutMillis < MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD
17090                     && !isAdminTestOnlyLocked(who, userId)) {
17091                 timeoutMillis = MANAGED_PROFILE_MAXIMUM_TIME_OFF_THRESHOLD;
17092             }
17093             if (admin.mProfileMaximumTimeOffMillis == timeoutMillis) {
17094                 return;
17095             }
17096             admin.mProfileMaximumTimeOffMillis = timeoutMillis;
17097             saveSettingsLocked(userId);
17098         }
17099 
17100         mInjector.binderWithCleanCallingIdentity(
17101                 () -> updatePersonalAppsSuspension(userId, mUserManager.isUserUnlocked()));
17102 
17103         DevicePolicyEventLogger
17104                 .createEvent(DevicePolicyEnums.SET_MANAGED_PROFILE_MAXIMUM_TIME_OFF)
17105                 .setAdmin(caller.getComponentName())
17106                 .setTimePeriod(timeoutMillis)
17107                 .write();
17108     }
17109 
17110     private boolean canHandleCheckPolicyComplianceIntent(CallerIdentity caller) {
17111         mInjector.binderWithCleanCallingIdentity(() -> {
17112             final Intent intent = new Intent(DevicePolicyManager.ACTION_CHECK_POLICY_COMPLIANCE);
17113             intent.setPackage(caller.getPackageName());
17114             final List<ResolveInfo> handlers =
17115                     mInjector.getPackageManager().queryIntentActivitiesAsUser(intent, /* flags= */
17116                             0, caller.getUserId());
17117             return !handlers.isEmpty();
17118         });
17119         return true;
17120     }
17121 
17122     @Override
17123     public long getManagedProfileMaximumTimeOff(ComponentName who) {
17124         Objects.requireNonNull(who, "ComponentName is null");
17125 
17126         final CallerIdentity caller = getCallerIdentity(who);
17127         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
17128 
17129         synchronized (getLockObject()) {
17130             final ActiveAdmin admin = getProfileOwnerLocked(caller);
17131             return admin.mProfileMaximumTimeOffMillis;
17132         }
17133     }
17134 
17135     @Override
17136     public void acknowledgeDeviceCompliant() {
17137         final CallerIdentity caller = getCallerIdentity();
17138         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
17139         enforceUserUnlocked(caller.getUserId());
17140 
17141         synchronized (getLockObject()) {
17142             final ActiveAdmin admin = getProfileOwnerLocked(caller);
17143             if (admin.mProfileOffDeadline > 0) {
17144                 admin.mProfileOffDeadline = 0;
17145                 saveSettingsLocked(caller.getUserId());
17146             }
17147         }
17148     }
17149 
17150     @Override
17151     public boolean isComplianceAcknowledgementRequired() {
17152         final CallerIdentity caller = getCallerIdentity();
17153         Preconditions.checkCallAuthorization(isProfileOwnerOfOrganizationOwnedDevice(caller));
17154         enforceUserUnlocked(caller.getUserId());
17155 
17156         synchronized (getLockObject()) {
17157             final ActiveAdmin admin = getProfileOwnerLocked(caller);
17158             return admin.mProfileOffDeadline != 0;
17159         }
17160     }
17161 
17162     @Override
17163     public boolean canProfileOwnerResetPasswordWhenLocked(int userId) {
17164         Preconditions.checkCallAuthorization(isSystemUid(getCallerIdentity()),
17165                 String.format(NOT_SYSTEM_CALLER_MSG,
17166                         "call canProfileOwnerResetPasswordWhenLocked"));
17167         synchronized (getLockObject()) {
17168             final ActiveAdmin poAdmin = getProfileOwnerAdminLocked(userId);
17169             if (poAdmin == null
17170                     || getEncryptionStatus() != ENCRYPTION_STATUS_ACTIVE_PER_USER
17171                     || !isResetPasswordTokenActiveForUserLocked(userId)) {
17172                 return false;
17173             }
17174             final ApplicationInfo poAppInfo;
17175             try {
17176                 poAppInfo = mIPackageManager.getApplicationInfo(
17177                         poAdmin.info.getPackageName(), 0 /* flags */, userId);
17178             } catch (RemoteException e) {
17179                 Slogf.e(LOG_TAG, "Failed to query PO app info", e);
17180                 return false;
17181             }
17182             if (poAppInfo == null) {
17183                 Slogf.wtf(LOG_TAG, "Cannot find AppInfo for profile owner");
17184                 return false;
17185             }
17186             if (!poAppInfo.isEncryptionAware()) {
17187                 return false;
17188             }
17189             Slogf.d(LOG_TAG, "PO should be able to reset password from direct boot");
17190             return true;
17191         }
17192     }
17193 
17194     @Override
17195     public String getEnrollmentSpecificId(String callerPackage) {
17196         if (!mHasFeature) {
17197             return "";
17198         }
17199 
17200         final CallerIdentity caller = getCallerIdentity(callerPackage);
17201         Preconditions.checkCallAuthorization(
17202                 isDeviceOwner(caller) || isProfileOwner(caller)
17203                         || isCallerDelegate(caller, DELEGATION_CERT_INSTALL));
17204 
17205         synchronized (getLockObject()) {
17206             final ActiveAdmin requiredAdmin = getDeviceOrProfileOwnerAdminLocked(
17207                     caller.getUserId());
17208             final String esid = requiredAdmin.mEnrollmentSpecificId;
17209             return esid != null ? esid : "";
17210         }
17211     }
17212 
17213     @Override
17214     public void setOrganizationIdForUser(
17215             @NonNull String callerPackage, @NonNull String organizationId, int userId) {
17216         if (!mHasFeature) {
17217             return;
17218         }
17219         Objects.requireNonNull(callerPackage);
17220 
17221         final CallerIdentity caller = getCallerIdentity(callerPackage);
17222         // Only the DPC can set this ID.
17223         Preconditions.checkCallAuthorization(isDeviceOwner(caller) || isProfileOwner(caller),
17224                 "Only a Device Owner or Profile Owner may set the Enterprise ID.");
17225         // Empty enterprise ID must not be provided in calls to this method.
17226         Preconditions.checkArgument(!TextUtils.isEmpty(organizationId),
17227                 "Enterprise ID may not be empty.");
17228 
17229         Slogf.i(LOG_TAG, "Setting Enterprise ID to %s for user %d", organizationId, userId);
17230 
17231         final String ownerPackage;
17232         synchronized (getLockObject()) {
17233             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
17234             // As the caller is the system, it must specify the component name of the profile owner
17235             // as a safety check.
17236             Preconditions.checkCallAuthorization(
17237                     owner != null && owner.getUserHandle().getIdentifier() == userId,
17238                     String.format("The Profile Owner or Device Owner may only set the Enterprise ID"
17239                             + " on its own user, called on user %d but owner user is %d", userId,
17240                             owner.getUserHandle().getIdentifier()));
17241             ownerPackage = owner.info.getPackageName();
17242             Preconditions.checkState(
17243                     TextUtils.isEmpty(owner.mOrganizationId) || owner.mOrganizationId.equals(
17244                             organizationId),
17245                     "The organization ID has been previously set to a different value and cannot "
17246                             + "be changed");
17247             final String dpcPackage = owner.info.getPackageName();
17248             mInjector.binderWithCleanCallingIdentity(() -> {
17249                 EnterpriseSpecificIdCalculator esidCalculator =
17250                         new EnterpriseSpecificIdCalculator(mContext);
17251 
17252                 final String esid = esidCalculator.calculateEnterpriseId(dpcPackage,
17253                         organizationId);
17254                 owner.mOrganizationId = organizationId;
17255                 owner.mEnrollmentSpecificId = esid;
17256                 saveSettingsLocked(userId);
17257             });
17258         }
17259 
17260         DevicePolicyEventLogger
17261                 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_ID)
17262                 .setAdmin(ownerPackage)
17263                 .setBoolean(isManagedProfile(userId))
17264                 .write();
17265     }
17266 
17267     @Override
17268     public void clearOrganizationIdForUser(int userHandle) {
17269         Preconditions.checkCallAuthorization(
17270                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
17271 
17272         synchronized (getLockObject()) {
17273             final ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userHandle);
17274             owner.mOrganizationId = null;
17275             owner.mEnrollmentSpecificId = null;
17276             saveSettingsLocked(userHandle);
17277         }
17278     }
17279 
17280     @Override
17281     public UserHandle createAndProvisionManagedProfile(
17282             @NonNull ManagedProfileProvisioningParams provisioningParams,
17283             @NonNull String callerPackage) {
17284         Objects.requireNonNull(provisioningParams, "provisioningParams is null");
17285         Objects.requireNonNull(callerPackage, "callerPackage is null");
17286 
17287         final ComponentName admin = provisioningParams.getProfileAdminComponentName();
17288         Objects.requireNonNull(admin, "admin is null");
17289 
17290         final CallerIdentity caller = getCallerIdentity(callerPackage);
17291         Preconditions.checkCallAuthorization(
17292                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
17293 
17294         provisioningParams.logParams(callerPackage);
17295 
17296         UserInfo userInfo = null;
17297         final long identity = Binder.clearCallingIdentity();
17298         try {
17299             final int result = checkProvisioningPreConditionSkipPermission(
17300                     ACTION_PROVISION_MANAGED_PROFILE, admin.getPackageName());
17301             if (result != CODE_OK) {
17302                 throw new ServiceSpecificException(
17303                         PROVISIONING_RESULT_PRE_CONDITION_FAILED,
17304                         "Provisioning preconditions failed with result: " + result);
17305             }
17306 
17307             final long startTime = SystemClock.elapsedRealtime();
17308             final Set<String> nonRequiredApps = provisioningParams.isLeaveAllSystemAppsEnabled()
17309                     ? Collections.emptySet()
17310                     : mOverlayPackagesProvider.getNonRequiredApps(
17311                             admin, caller.getUserId(), ACTION_PROVISION_MANAGED_PROFILE);
17312             userInfo = mUserManager.createProfileForUserEvenWhenDisallowed(
17313                     provisioningParams.getProfileName(),
17314                     UserManager.USER_TYPE_PROFILE_MANAGED,
17315                     UserInfo.FLAG_DISABLED,
17316                     caller.getUserId(),
17317                     nonRequiredApps.toArray(new String[nonRequiredApps.size()]));
17318             if (userInfo == null) {
17319                 throw new ServiceSpecificException(
17320                         PROVISIONING_RESULT_PROFILE_CREATION_FAILED,
17321                         "Error creating profile, createProfileForUserEvenWhenDisallowed "
17322                                 + "returned null.");
17323             }
17324             resetInteractAcrossProfilesAppOps();
17325             logEventDuration(
17326                     DevicePolicyEnums.PLATFORM_PROVISIONING_CREATE_PROFILE_MS,
17327                     startTime,
17328                     callerPackage);
17329 
17330             installExistingAdminPackage(userInfo.id, admin.getPackageName());
17331             if (!enableAdminAndSetProfileOwner(
17332                     userInfo.id, caller.getUserId(), admin, provisioningParams.getOwnerName())) {
17333                 throw new ServiceSpecificException(
17334                         PROVISIONING_RESULT_SETTING_PROFILE_OWNER_FAILED,
17335                         "Error setting profile owner.");
17336             }
17337             setUserSetupComplete(userInfo.id);
17338 
17339             startUser(userInfo.id, callerPackage);
17340             maybeMigrateAccount(
17341                     userInfo.id, caller.getUserId(), provisioningParams.getAccountToMigrate(),
17342                     provisioningParams.isKeepAccountMigrated(), callerPackage);
17343 
17344             if (provisioningParams.isOrganizationOwnedProvisioning()) {
17345                 synchronized (getLockObject()) {
17346                     markProfileOwnerOnOrganizationOwnedDeviceUncheckedLocked(admin, userInfo.id);
17347                 }
17348             }
17349 
17350             return userInfo.getUserHandle();
17351         } catch (Exception e) {
17352             DevicePolicyEventLogger
17353                     .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
17354                     .setStrings(callerPackage)
17355                     .write();
17356             // In case of any errors during provisioning, remove the newly created profile.
17357             if (userInfo != null) {
17358                 mUserManager.removeUserEvenWhenDisallowed(userInfo.id);
17359             }
17360             throw e;
17361         } finally {
17362             Binder.restoreCallingIdentity(identity);
17363         }
17364     }
17365 
17366     private void resetInteractAcrossProfilesAppOps() {
17367         mInjector.getCrossProfileApps().clearInteractAcrossProfilesAppOps();
17368         pregrantDefaultInteractAcrossProfilesAppOps();
17369     }
17370 
17371     private void pregrantDefaultInteractAcrossProfilesAppOps() {
17372         final String op =
17373                 AppOpsManager.permissionToOp(Manifest.permission.INTERACT_ACROSS_PROFILES);
17374         for (String packageName : getConfigurableDefaultCrossProfilePackages()) {
17375             if (appOpIsChangedFromDefault(op, packageName)) {
17376                 continue;
17377             }
17378             mInjector.getCrossProfileApps().setInteractAcrossProfilesAppOp(
17379                     packageName, MODE_ALLOWED);
17380         }
17381     }
17382 
17383     private Set<String> getConfigurableDefaultCrossProfilePackages() {
17384         List<String> defaultPackages = getDefaultCrossProfilePackages();
17385         return defaultPackages.stream().filter(
17386                 mInjector.getCrossProfileApps()::canConfigureInteractAcrossProfiles).collect(
17387                 Collectors.toSet());
17388     }
17389 
17390     private boolean appOpIsChangedFromDefault(String op, String packageName) {
17391         try {
17392             final int uid = mContext.getPackageManager().getPackageUid(
17393                     packageName, /* flags= */ 0);
17394             return mInjector.getAppOpsManager().unsafeCheckOpNoThrow(
17395                     op, uid, packageName)
17396                     != AppOpsManager.MODE_DEFAULT;
17397         } catch (NameNotFoundException e) {
17398             return false;
17399         }
17400     }
17401 
17402     private void installExistingAdminPackage(int userId, String packageName) {
17403         try {
17404             final int status = mContext.getPackageManager().installExistingPackageAsUser(
17405                     packageName,
17406                     userId);
17407             if (status != PackageManager.INSTALL_SUCCEEDED) {
17408                 throw new ServiceSpecificException(
17409                         PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED,
17410                         String.format("Failed to install existing package %s for user %d with "
17411                                         + "result code %d",
17412                                 packageName, userId, status));
17413             }
17414         } catch (NameNotFoundException e) {
17415             throw new ServiceSpecificException(
17416                     PROVISIONING_RESULT_ADMIN_PACKAGE_INSTALLATION_FAILED,
17417                     String.format("Failed to install existing package %s for user %d: %s",
17418                             packageName, userId, e.getMessage()));
17419         }
17420     }
17421 
17422     private boolean enableAdminAndSetProfileOwner(
17423             @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent,
17424             String ownerName) {
17425         enableAndSetActiveAdmin(userId, callingUserId, adminComponent);
17426         return setProfileOwner(adminComponent, ownerName, userId);
17427     }
17428 
17429     private void enableAndSetActiveAdmin(
17430             @UserIdInt int userId, @UserIdInt int callingUserId, ComponentName adminComponent) {
17431         final String adminPackage = adminComponent.getPackageName();
17432         enablePackage(adminPackage, callingUserId);
17433         setActiveAdmin(adminComponent, /* refreshing= */ true, userId);
17434     }
17435 
17436     private void enablePackage(String packageName, @UserIdInt int userId) {
17437         try {
17438             final int enabledSetting = mIPackageManager.getApplicationEnabledSetting(
17439                     packageName, userId);
17440             if (enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17441                     && enabledSetting != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17442                 mIPackageManager.setApplicationEnabledSetting(
17443                         packageName,
17444                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
17445                         // Device policy app may have launched ManagedProvisioning, play nice and
17446                         // don't kill it as a side-effect of this call.
17447                         PackageManager.DONT_KILL_APP,
17448                         userId,
17449                         mContext.getOpPackageName());
17450             }
17451         } catch (RemoteException e) {
17452             // Shouldn't happen.
17453         }
17454     }
17455 
17456     private void setUserSetupComplete(@UserIdInt int userId) {
17457         Settings.Secure.putIntForUser(
17458                 mContext.getContentResolver(), USER_SETUP_COMPLETE, 1, userId);
17459     }
17460 
17461     private void startUser(@UserIdInt int userId, String callerPackage)
17462             throws IllegalStateException {
17463         final long startTime = SystemClock.elapsedRealtime();
17464         final UserUnlockedBlockingReceiver unlockedReceiver = new UserUnlockedBlockingReceiver(
17465                 userId);
17466         mContext.registerReceiverAsUser(
17467                 unlockedReceiver,
17468                 new UserHandle(userId),
17469                 new IntentFilter(Intent.ACTION_USER_UNLOCKED),
17470                 /* broadcastPermission = */ null,
17471                 /* scheduler= */ null);
17472         try {
17473             if (!mInjector.getIActivityManager().startUserInBackground(userId)) {
17474                 throw new ServiceSpecificException(PROVISIONING_RESULT_STARTING_PROFILE_FAILED,
17475                         String.format("Unable to start user %d in background", userId));
17476             }
17477 
17478             if (!unlockedReceiver.waitForUserUnlocked()) {
17479                 throw new ServiceSpecificException(PROVISIONING_RESULT_STARTING_PROFILE_FAILED,
17480                         String.format("Timeout whilst waiting for unlock of user %d.", userId));
17481             }
17482             logEventDuration(
17483                     DevicePolicyEnums.PLATFORM_PROVISIONING_START_PROFILE_MS,
17484                     startTime,
17485                     callerPackage);
17486         } catch (RemoteException e) {
17487             // Shouldn't happen.
17488         } finally {
17489             mContext.unregisterReceiver(unlockedReceiver);
17490         }
17491     }
17492 
17493     private void maybeMigrateAccount(
17494             @UserIdInt int targetUserId, @UserIdInt int sourceUserId, Account accountToMigrate,
17495             boolean keepAccountMigrated, String callerPackage) {
17496         final UserHandle sourceUser = UserHandle.of(sourceUserId);
17497         final UserHandle targetUser = UserHandle.of(targetUserId);
17498         if (accountToMigrate == null) {
17499             Slogf.d(LOG_TAG, "No account to migrate.");
17500             return;
17501         }
17502         if (sourceUser.equals(targetUser)) {
17503             Slogf.w(LOG_TAG, "sourceUser and targetUser are the same, won't migrate account.");
17504             return;
17505         }
17506         copyAccount(targetUser, sourceUser, accountToMigrate, callerPackage);
17507         if (!keepAccountMigrated) {
17508             removeAccount(accountToMigrate);
17509         }
17510     }
17511 
17512     private void copyAccount(
17513             UserHandle targetUser, UserHandle sourceUser, Account accountToMigrate,
17514             String callerPackage) {
17515         final long startTime = SystemClock.elapsedRealtime();
17516         try {
17517             final AccountManager accountManager = mContext.getSystemService(AccountManager.class);
17518             final boolean copySucceeded = accountManager.copyAccountToUser(
17519                     accountToMigrate,
17520                     sourceUser,
17521                     targetUser,
17522                     /* callback= */ null, /* handler= */ null)
17523                     .getResult(60 * 3, TimeUnit.SECONDS);
17524             if (copySucceeded) {
17525                 logCopyAccountStatus(COPY_ACCOUNT_SUCCEEDED, callerPackage);
17526                 logEventDuration(
17527                         DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_MS,
17528                         startTime,
17529                         callerPackage);
17530             } else {
17531                 logCopyAccountStatus(COPY_ACCOUNT_FAILED, callerPackage);
17532                 Slogf.e(LOG_TAG, "Failed to copy account to " + targetUser);
17533             }
17534         } catch (OperationCanceledException e) {
17535             // Account migration is not considered a critical operation.
17536             logCopyAccountStatus(COPY_ACCOUNT_TIMED_OUT, callerPackage);
17537             Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e);
17538         } catch (AuthenticatorException | IOException e) {
17539             logCopyAccountStatus(COPY_ACCOUNT_EXCEPTION, callerPackage);
17540             Slogf.e(LOG_TAG, "Exception copying account to " + targetUser, e);
17541         }
17542     }
17543 
17544     private static void logCopyAccountStatus(@CopyAccountStatus int status, String callerPackage) {
17545         DevicePolicyEventLogger
17546                 .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_COPY_ACCOUNT_STATUS)
17547                 .setInt(status)
17548                 .setStrings(callerPackage)
17549                 .write();
17550     }
17551 
17552     private void removeAccount(Account account) {
17553         final AccountManager accountManager =
17554                 mContext.getSystemService(AccountManager.class);
17555         final AccountManagerFuture<Bundle> bundle = accountManager.removeAccount(account,
17556                 null, null /* callback */, null /* handler */);
17557         try {
17558             final Bundle result = bundle.getResult();
17559             if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, /* default */ false)) {
17560                 Slogf.i(LOG_TAG, "Account removed from the primary user.");
17561             } else {
17562                 // TODO(174768447): Revisit start activity logic.
17563                 final Intent removeIntent = result.getParcelable(AccountManager.KEY_INTENT);
17564                 removeIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
17565                 if (removeIntent != null) {
17566                     Slogf.i(LOG_TAG, "Starting activity to remove account");
17567                     new Handler(Looper.getMainLooper()).post(() -> {
17568                         mContext.startActivity(removeIntent);
17569                     });
17570                 } else {
17571                     Slogf.e(LOG_TAG, "Could not remove account from the primary user.");
17572                 }
17573             }
17574         } catch (OperationCanceledException | AuthenticatorException | IOException e) {
17575             Slogf.e(LOG_TAG, "Exception removing account from the primary user.", e);
17576         }
17577     }
17578 
17579     @Override
17580     public void provisionFullyManagedDevice(
17581             @NonNull FullyManagedDeviceProvisioningParams provisioningParams,
17582             @NonNull String callerPackage) {
17583         Objects.requireNonNull(provisioningParams, "provisioningParams is null.");
17584         Objects.requireNonNull(callerPackage, "callerPackage is null.");
17585 
17586         ComponentName deviceAdmin = provisioningParams.getDeviceAdminComponentName();
17587         Objects.requireNonNull(deviceAdmin, "admin is null.");
17588         Objects.requireNonNull(provisioningParams.getOwnerName(), "owner name is null.");
17589 
17590         final CallerIdentity caller = getCallerIdentity();
17591         Preconditions.checkCallAuthorization(
17592                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
17593 
17594         provisioningParams.logParams(callerPackage);
17595 
17596         final long identity = Binder.clearCallingIdentity();
17597         try {
17598             int result = checkProvisioningPreConditionSkipPermission(
17599                     ACTION_PROVISION_MANAGED_DEVICE, deviceAdmin.getPackageName());
17600             if (result != CODE_OK) {
17601                 throw new ServiceSpecificException(
17602                         PROVISIONING_RESULT_PRE_CONDITION_FAILED,
17603                         "Provisioning preconditions failed with result: " + result);
17604             }
17605             setTimeAndTimezone(provisioningParams.getTimeZone(), provisioningParams.getLocalTime());
17606             setLocale(provisioningParams.getLocale());
17607 
17608             final int deviceOwnerUserId = mInjector.userManagerIsHeadlessSystemUserMode()
17609                     ? UserHandle.USER_SYSTEM : caller.getUserId();
17610             if (!removeNonRequiredAppsForManagedDevice(
17611                     deviceOwnerUserId,
17612                     provisioningParams.isLeaveAllSystemAppsEnabled(),
17613                     deviceAdmin)) {
17614                 throw new ServiceSpecificException(
17615                         PROVISIONING_RESULT_REMOVE_NON_REQUIRED_APPS_FAILED,
17616                         "PackageManager failed to remove non required apps.");
17617             }
17618 
17619 
17620             if (!setActiveAdminAndDeviceOwner(
17621                     deviceOwnerUserId, deviceAdmin, provisioningParams.getOwnerName())) {
17622                 throw new ServiceSpecificException(
17623                         PROVISIONING_RESULT_SET_DEVICE_OWNER_FAILED,
17624                         "Failed to set device owner.");
17625             }
17626 
17627             disallowAddUser();
17628             setAdminCanGrantSensorsPermissionForUserUnchecked(deviceOwnerUserId,
17629                     provisioningParams.canDeviceOwnerGrantSensorsPermissions());
17630         } catch (Exception e) {
17631             DevicePolicyEventLogger
17632                     .createEvent(DevicePolicyEnums.PLATFORM_PROVISIONING_ERROR)
17633                     .setStrings(callerPackage)
17634                     .write();
17635             throw e;
17636         } finally {
17637             Binder.restoreCallingIdentity(identity);
17638         }
17639     }
17640 
17641     private void setTimeAndTimezone(String timeZone, long localTime) {
17642         try {
17643             final AlarmManager alarmManager = mContext.getSystemService(AlarmManager.class);
17644             if (timeZone != null) {
17645                 alarmManager.setTimeZone(timeZone);
17646             }
17647             if (localTime > 0) {
17648                 alarmManager.setTime(localTime);
17649             }
17650         } catch (Exception e) {
17651             // Do not stop provisioning and ignore this error.
17652             Slogf.e(LOG_TAG, "Alarm manager failed to set the system time/timezone.", e);
17653         }
17654     }
17655 
17656     private void setLocale(Locale locale) {
17657         if (locale == null || locale.equals(Locale.getDefault())) {
17658             return;
17659         }
17660         try {
17661             // If locale is different from current locale this results in a configuration change,
17662             // which will trigger the restarting of the activity.
17663             LocalePicker.updateLocale(locale);
17664         } catch (Exception e) {
17665             // Do not stop provisioning and ignore this error.
17666             Slogf.e(LOG_TAG, "Failed to set the system locale.", e);
17667         }
17668     }
17669 
17670     private boolean removeNonRequiredAppsForManagedDevice(
17671             @UserIdInt int userId, boolean leaveAllSystemAppsEnabled, ComponentName admin) {
17672         Set<String> packagesToDelete = leaveAllSystemAppsEnabled
17673                 ? Collections.emptySet()
17674                 : mOverlayPackagesProvider.getNonRequiredApps(
17675                         admin, userId, ACTION_PROVISION_MANAGED_DEVICE);
17676 
17677         removeNonInstalledPackages(packagesToDelete, userId);
17678         if (packagesToDelete.isEmpty()) {
17679             Slogf.i(LOG_TAG, "No packages to delete on user " + userId);
17680             return true;
17681         }
17682 
17683         NonRequiredPackageDeleteObserver packageDeleteObserver =
17684                 new NonRequiredPackageDeleteObserver(packagesToDelete.size());
17685         for (String packageName : packagesToDelete) {
17686             Slogf.i(LOG_TAG, "Deleting package [" + packageName + "] as user " + userId);
17687             mContext.getPackageManager().deletePackageAsUser(
17688                     packageName,
17689                     packageDeleteObserver,
17690                     PackageManager.DELETE_SYSTEM_APP,
17691                     userId);
17692         }
17693         Slogf.i(LOG_TAG, "Waiting for non required apps to be deleted");
17694         return packageDeleteObserver.awaitPackagesDeletion();
17695     }
17696 
17697     private void removeNonInstalledPackages(Set<String> packages, @UserIdInt int userId) {
17698         final Set<String> toBeRemoved = new HashSet<>();
17699         for (String packageName : packages) {
17700             if (!isPackageInstalledForUser(packageName, userId)) {
17701                 toBeRemoved.add(packageName);
17702             }
17703         }
17704         packages.removeAll(toBeRemoved);
17705     }
17706 
17707     private void disallowAddUser() {
17708         if (mInjector.userManagerIsHeadlessSystemUserMode()) {
17709             Slogf.i(LOG_TAG, "Not setting DISALLOW_ADD_USER on headless system user mode.");
17710             return;
17711         }
17712         for (UserInfo userInfo : mUserManager.getUsers()) {
17713             UserHandle userHandle = userInfo.getUserHandle();
17714             if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
17715                 mUserManager.setUserRestriction(
17716                         UserManager.DISALLOW_ADD_USER, /* value= */ true, userHandle);
17717             }
17718         }
17719     }
17720 
17721     private boolean setActiveAdminAndDeviceOwner(
17722             @UserIdInt int userId, ComponentName adminComponent, String name) {
17723         enableAndSetActiveAdmin(userId, userId, adminComponent);
17724         // TODO(b/178187130): Directly set DO and remove the check once silent provisioning is no
17725         //  longer used.
17726         if (getDeviceOwnerComponent(/* callingUserOnly= */ true) == null) {
17727             return setDeviceOwner(adminComponent, name, userId,
17728                     /* setProfileOwnerOnCurrentUserIfNecessary= */ true);
17729         }
17730         return true;
17731     }
17732 
17733     private static void logEventDuration(int eventId, long startTime, String callerPackage) {
17734         final long duration = SystemClock.elapsedRealtime() - startTime;
17735         DevicePolicyEventLogger
17736                 .createEvent(eventId)
17737                 .setTimePeriod(duration)
17738                 .setStrings(callerPackage)
17739                 .write();
17740     }
17741 
17742     @Override
17743     public void resetDefaultCrossProfileIntentFilters(@UserIdInt int userId) {
17744         Preconditions.checkCallAuthorization(
17745                 hasCallingOrSelfPermission(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
17746 
17747         mInjector.binderWithCleanCallingIdentity(() -> {
17748             try {
17749                 final List<UserInfo> profiles = mUserManager.getProfiles(userId);
17750                 final int numOfProfiles = profiles.size();
17751                 if (numOfProfiles <= 1) {
17752                     return;
17753                 }
17754 
17755                 final String managedProvisioningPackageName = getManagedProvisioningPackage(
17756                         mContext);
17757                 // Removes cross profile intent filters from the parent to all the profiles.
17758                 mIPackageManager.clearCrossProfileIntentFilters(
17759                         userId, mContext.getOpPackageName());
17760                 // Setting and resetting default cross profile intent filters was previously handled
17761                 // by Managed Provisioning. For backwards compatibility, clear any intent filters
17762                 // that were set by ManagedProvisioning.
17763                 mIPackageManager.clearCrossProfileIntentFilters(
17764                         userId, managedProvisioningPackageName);
17765 
17766                 // For each profile reset cross profile intent filters
17767                 for (int i = 0; i < numOfProfiles; i++) {
17768                     UserInfo profile = profiles.get(i);
17769                     mIPackageManager.clearCrossProfileIntentFilters(
17770                             profile.id, mContext.getOpPackageName());
17771                     // Clear any intent filters that were set by ManagedProvisioning.
17772                     mIPackageManager.clearCrossProfileIntentFilters(
17773                             profile.id, managedProvisioningPackageName);
17774 
17775                     mUserManagerInternal.setDefaultCrossProfileIntentFilters(userId, profile.id);
17776                 }
17777             } catch (RemoteException e) {
17778                 // Shouldn't happen.
17779             }
17780         });
17781     }
17782 
17783     private void setAdminCanGrantSensorsPermissionForUserUnchecked(@UserIdInt int userId,
17784             boolean canGrant) {
17785         Slogf.d(LOG_TAG, "setAdminCanGrantSensorsPermissionForUserUnchecked(%d, %b)",
17786                 userId, canGrant);
17787         synchronized (getLockObject()) {
17788             ActiveAdmin owner = getDeviceOrProfileOwnerAdminLocked(userId);
17789 
17790             Preconditions.checkState(
17791                     isDeviceOwner(owner) && owner.getUserHandle().getIdentifier() == userId,
17792                     "May only be set on a the user of a device owner.");
17793 
17794             owner.mAdminCanGrantSensorsPermissions = canGrant;
17795             mPolicyCache.setAdminCanGrantSensorsPermissions(userId, canGrant);
17796             saveSettingsLocked(userId);
17797         }
17798     }
17799 
17800     private void updateAdminCanGrantSensorsPermissionCache(@UserIdInt int userId) {
17801         synchronized (getLockObject()) {
17802 
17803             ActiveAdmin owner;
17804             // If the user is affiliated the device (either a DO itself, or an affiliated PO),
17805             // use mAdminCanGrantSensorsPermissions from the DO
17806             if (isUserAffiliatedWithDeviceLocked(userId)) {
17807                 owner = getDeviceOwnerAdminLocked();
17808             } else {
17809                 owner = getDeviceOrProfileOwnerAdminLocked(userId);
17810             }
17811             boolean canGrant = owner != null ? owner.mAdminCanGrantSensorsPermissions : false;
17812             mPolicyCache.setAdminCanGrantSensorsPermissions(userId, canGrant);
17813         }
17814     }
17815 
17816     private void updateNetworkPreferenceForUser(int userId,
17817             boolean preferentialNetworkServiceEnabled) {
17818         if (!isManagedProfile(userId)) {
17819             return;
17820         }
17821         int networkPreference = preferentialNetworkServiceEnabled
17822                 ? PROFILE_NETWORK_PREFERENCE_ENTERPRISE : PROFILE_NETWORK_PREFERENCE_DEFAULT;
17823         mInjector.binderWithCleanCallingIdentity(() ->
17824                 mInjector.getConnectivityManager().setProfileNetworkPreference(
17825                         UserHandle.of(userId),
17826                         networkPreference,
17827                         null /* executor */, null /* listener */));
17828     }
17829 
17830     @Override
17831     public boolean canAdminGrantSensorsPermissionsForUser(int userId) {
17832         if (!mHasFeature) {
17833             return false;
17834         }
17835 
17836         return mPolicyCache.canAdminGrantSensorsPermissionsForUser(userId);
17837     }
17838 
17839     @Override
17840     public void setDeviceOwnerType(@NonNull ComponentName admin,
17841             @DeviceOwnerType int deviceOwnerType) {
17842         Preconditions.checkCallAuthorization(hasCallingOrSelfPermission(
17843                 permission.MANAGE_PROFILE_AND_DEVICE_OWNERS));
17844         verifyDeviceOwnerTypePreconditions(admin);
17845 
17846         final String packageName = admin.getPackageName();
17847         Preconditions.checkState(!mOwners.isDeviceOwnerTypeSetForDeviceOwner(packageName),
17848                 "The device owner type has already been set for " + packageName);
17849 
17850         synchronized (getLockObject()) {
17851             mOwners.setDeviceOwnerType(packageName, deviceOwnerType);
17852         }
17853     }
17854 
17855     @Override
17856     @DeviceOwnerType
17857     public int getDeviceOwnerType(@NonNull ComponentName admin) {
17858         verifyDeviceOwnerTypePreconditions(admin);
17859         synchronized (getLockObject()) {
17860             return mOwners.getDeviceOwnerType(admin.getPackageName());
17861         }
17862     }
17863 
17864     private void verifyDeviceOwnerTypePreconditions(@NonNull ComponentName admin) {
17865         Preconditions.checkState(mOwners.hasDeviceOwner(), "there is no device owner");
17866         Preconditions.checkState(mOwners.getDeviceOwnerComponent().equals(admin),
17867                 "admin is not the device owner");
17868     }
17869 
17870     @Override
17871     public void setUsbDataSignalingEnabled(String packageName, boolean enabled) {
17872         Objects.requireNonNull(packageName, "Admin package name must be provided");
17873         final CallerIdentity caller = getCallerIdentity(packageName);
17874         Preconditions.checkCallAuthorization(
17875                 isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller),
17876                 "USB data signaling can only be controlled by a device owner or "
17877                         + "a profile owner on an organization-owned device.");
17878         Preconditions.checkState(canUsbDataSignalingBeDisabled(),
17879                 "USB data signaling cannot be disabled.");
17880 
17881         synchronized (getLockObject()) {
17882             final ActiveAdmin admin = getProfileOwnerOrDeviceOwnerLocked(caller);
17883             if (admin.mUsbDataSignalingEnabled != enabled) {
17884                 admin.mUsbDataSignalingEnabled = enabled;
17885                 saveSettingsLocked(caller.getUserId());
17886                 updateUsbDataSignal();
17887             }
17888         }
17889         DevicePolicyEventLogger
17890                 .createEvent(DevicePolicyEnums.SET_USB_DATA_SIGNALING)
17891                 .setAdmin(packageName)
17892                 .setBoolean(enabled)
17893                 .write();
17894     }
17895 
17896     private void updateUsbDataSignal() {
17897         if (!canUsbDataSignalingBeDisabled()) {
17898             return;
17899         }
17900         final boolean usbEnabled;
17901         synchronized (getLockObject()) {
17902             usbEnabled = isUsbDataSignalingEnabledInternalLocked();
17903         }
17904         if (!mInjector.binderWithCleanCallingIdentity(
17905                 () -> mInjector.getUsbManager().enableUsbDataSignal(usbEnabled))) {
17906             Slogf.w(LOG_TAG, "Failed to set usb data signaling state");
17907         }
17908     }
17909 
17910     @Override
17911     public boolean isUsbDataSignalingEnabled(String packageName) {
17912         final CallerIdentity caller = getCallerIdentity(packageName);
17913         synchronized (getLockObject()) {
17914             // If the caller is an admin, return the policy set by itself. Otherwise
17915             // return the device-wide policy.
17916             if (isDeviceOwner(caller) || isProfileOwnerOfOrganizationOwnedDevice(caller)) {
17917                 return getProfileOwnerOrDeviceOwnerLocked(caller).mUsbDataSignalingEnabled;
17918             } else {
17919                 return isUsbDataSignalingEnabledInternalLocked();
17920             }
17921         }
17922     }
17923 
17924     @Override
17925     public boolean isUsbDataSignalingEnabledForUser(int userId) {
17926         final CallerIdentity caller = getCallerIdentity();
17927         Preconditions.checkCallAuthorization(isSystemUid(caller));
17928 
17929         synchronized (getLockObject()) {
17930             return isUsbDataSignalingEnabledInternalLocked();
17931         }
17932     }
17933 
17934     private boolean isUsbDataSignalingEnabledInternalLocked() {
17935         final ActiveAdmin admin = getDeviceOwnerOrProfileOwnerOfOrganizationOwnedDeviceLocked(
17936                 UserHandle.USER_SYSTEM);
17937         return admin == null || admin.mUsbDataSignalingEnabled;
17938     }
17939 
17940     @Override
17941     public boolean canUsbDataSignalingBeDisabled() {
17942         return mInjector.binderWithCleanCallingIdentity(() ->
17943                 mInjector.getUsbManager() != null
17944                         && mInjector.getUsbManager().getUsbHalVersion() >= UsbManager.USB_HAL_V1_3
17945         );
17946     }
17947 }
17948