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.app.ActivityManager.LOCK_TASK_MODE_NONE;
23 import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE;
24 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
25 import static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY;
26 import static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED;
27 import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE;
28 import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED;
29 import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER;
30 import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED;
31 import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED;
32 import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS;
33 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER;
34 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT;
35 import static android.app.admin.DevicePolicyManager.CODE_OK;
36 import static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
37 import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER;
38 import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER;
39 import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING;
40 import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED;
41 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
42 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
43 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
44 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_SELECTION;
45 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
46 import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE;
47 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
48 import static android.app.admin.DevicePolicyManager.DELEGATION_NETWORK_LOGGING;
49 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
50 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
51 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
52 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
53 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
54 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
55 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
56 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME;
57 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS;
58 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
59 import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
60 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
61 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
62 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK;
63 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
64 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_MANAGED;
65 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
66 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
67 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
68 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
69 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OFF;
70 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
71 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
72 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_MODE_UNKNOWN;
73 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
74 import static android.app.admin.DevicePolicyManager.PRIVATE_DNS_SET_NO_ERROR;
75 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
76 import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
77 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
78 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
79 import static android.app.admin.DevicePolicyManager.WIPE_SILENTLY;
80 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
81 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
82 import static android.provider.Settings.Global.PRIVATE_DNS_MODE;
83 import static android.provider.Settings.Global.PRIVATE_DNS_SPECIFIER;
84 import static android.provider.Telephony.Carriers.DPC_URI;
85 import static android.provider.Telephony.Carriers.ENFORCE_KEY;
86 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI;
87 
88 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
89 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
90 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER;
91 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER;
92 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
93 
94 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
95 import static org.xmlpull.v1.XmlPullParser.END_TAG;
96 import static org.xmlpull.v1.XmlPullParser.TEXT;
97 
98 import android.Manifest.permission;
99 import android.accessibilityservice.AccessibilityServiceInfo;
100 import android.accounts.Account;
101 import android.accounts.AccountManager;
102 import android.annotation.NonNull;
103 import android.annotation.Nullable;
104 import android.annotation.UserIdInt;
105 import android.app.Activity;
106 import android.app.ActivityManager;
107 import android.app.ActivityManagerInternal;
108 import android.app.ActivityTaskManager;
109 import android.app.ActivityThread;
110 import android.app.AlarmManager;
111 import android.app.AppGlobals;
112 import android.app.AppOpsManager;
113 import android.app.BroadcastOptions;
114 import android.app.IActivityManager;
115 import android.app.IActivityTaskManager;
116 import android.app.IApplicationThread;
117 import android.app.IServiceConnection;
118 import android.app.Notification;
119 import android.app.NotificationManager;
120 import android.app.PendingIntent;
121 import android.app.StatusBarManager;
122 import android.app.admin.DeviceAdminInfo;
123 import android.app.admin.DeviceAdminReceiver;
124 import android.app.admin.DevicePolicyCache;
125 import android.app.admin.DevicePolicyEventLogger;
126 import android.app.admin.DevicePolicyManager;
127 import android.app.admin.DevicePolicyManager.PasswordComplexity;
128 import android.app.admin.DevicePolicyManagerInternal;
129 import android.app.admin.NetworkEvent;
130 import android.app.admin.PasswordMetrics;
131 import android.app.admin.SecurityLog;
132 import android.app.admin.SecurityLog.SecurityEvent;
133 import android.app.admin.StartInstallingUpdateCallback;
134 import android.app.admin.SystemUpdateInfo;
135 import android.app.admin.SystemUpdatePolicy;
136 import android.app.backup.IBackupManager;
137 import android.app.trust.TrustManager;
138 import android.app.usage.UsageStatsManagerInternal;
139 import android.content.ActivityNotFoundException;
140 import android.content.BroadcastReceiver;
141 import android.content.ComponentName;
142 import android.content.ContentValues;
143 import android.content.Context;
144 import android.content.Intent;
145 import android.content.IntentFilter;
146 import android.content.PermissionChecker;
147 import android.content.pm.ActivityInfo;
148 import android.content.pm.ApplicationInfo;
149 import android.content.pm.IPackageDataObserver;
150 import android.content.pm.IPackageManager;
151 import android.content.pm.PackageInfo;
152 import android.content.pm.PackageManager;
153 import android.content.pm.PackageManager.NameNotFoundException;
154 import android.content.pm.PackageManagerInternal;
155 import android.content.pm.ParceledListSlice;
156 import android.content.pm.PermissionInfo;
157 import android.content.pm.ResolveInfo;
158 import android.content.pm.ServiceInfo;
159 import android.content.pm.StringParceledListSlice;
160 import android.content.pm.UserInfo;
161 import android.content.res.Resources;
162 import android.database.ContentObserver;
163 import android.database.Cursor;
164 import android.graphics.Bitmap;
165 import android.graphics.Color;
166 import android.media.AudioManager;
167 import android.media.IAudioService;
168 import android.net.ConnectivityManager;
169 import android.net.IIpConnectivityMetrics;
170 import android.net.NetworkUtils;
171 import android.net.ProxyInfo;
172 import android.net.Uri;
173 import android.net.metrics.IpConnectivityLog;
174 import android.net.wifi.WifiManager;
175 import android.os.Binder;
176 import android.os.Build;
177 import android.os.Bundle;
178 import android.os.Environment;
179 import android.os.FileUtils;
180 import android.os.Handler;
181 import android.os.IBinder;
182 import android.os.Looper;
183 import android.os.ParcelFileDescriptor;
184 import android.os.PersistableBundle;
185 import android.os.PowerManager;
186 import android.os.PowerManagerInternal;
187 import android.os.Process;
188 import android.os.RecoverySystem;
189 import android.os.RemoteCallback;
190 import android.os.RemoteException;
191 import android.os.ServiceManager;
192 import android.os.ServiceSpecificException;
193 import android.os.SystemClock;
194 import android.os.SystemProperties;
195 import android.os.UserHandle;
196 import android.os.UserManager;
197 import android.os.UserManagerInternal;
198 import android.os.UserManagerInternal.UserRestrictionsListener;
199 import android.os.storage.StorageManager;
200 import android.permission.PermissionControllerManager;
201 import android.provider.CalendarContract;
202 import android.provider.ContactsContract.QuickContact;
203 import android.provider.ContactsInternal;
204 import android.provider.Settings;
205 import android.provider.Settings.Global;
206 import android.provider.Telephony;
207 import android.security.IKeyChainAliasCallback;
208 import android.security.IKeyChainService;
209 import android.security.KeyChain;
210 import android.security.KeyChain.KeyChainConnection;
211 import android.security.KeyStore;
212 import android.security.keymaster.KeymasterCertificateChain;
213 import android.security.keystore.AttestationUtils;
214 import android.security.keystore.KeyGenParameterSpec;
215 import android.security.keystore.ParcelableKeyGenParameterSpec;
216 import android.service.persistentdata.PersistentDataBlockManager;
217 import android.stats.devicepolicy.DevicePolicyEnums;
218 import android.telephony.TelephonyManager;
219 import android.telephony.data.ApnSetting;
220 import android.text.TextUtils;
221 import android.util.ArrayMap;
222 import android.util.ArraySet;
223 import android.util.AtomicFile;
224 import android.util.Log;
225 import android.util.Pair;
226 import android.util.Slog;
227 import android.util.SparseArray;
228 import android.util.Xml;
229 import android.view.IWindowManager;
230 import android.view.accessibility.AccessibilityManager;
231 import android.view.accessibility.IAccessibilityManager;
232 import android.view.inputmethod.InputMethodInfo;
233 import android.view.inputmethod.InputMethodSystemProperty;
234 
235 import com.android.internal.R;
236 import com.android.internal.annotations.GuardedBy;
237 import com.android.internal.annotations.VisibleForTesting;
238 import com.android.internal.logging.MetricsLogger;
239 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
240 import com.android.internal.notification.SystemNotificationChannels;
241 import com.android.internal.os.BackgroundThread;
242 import com.android.internal.statusbar.IStatusBarService;
243 import com.android.internal.telephony.SmsApplication;
244 import com.android.internal.util.DumpUtils;
245 import com.android.internal.util.FastXmlSerializer;
246 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
247 import com.android.internal.util.FunctionalUtils.ThrowingSupplier;
248 import com.android.internal.util.JournaledFile;
249 import com.android.internal.util.Preconditions;
250 import com.android.internal.util.StatLogger;
251 import com.android.internal.util.XmlUtils;
252 import com.android.internal.widget.LockPatternUtils;
253 import com.android.server.LocalServices;
254 import com.android.server.LockGuard;
255 import com.android.server.SystemServerInitThreadPool;
256 import com.android.server.SystemService;
257 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
258 import com.android.server.inputmethod.InputMethodManagerInternal;
259 import com.android.server.net.NetworkPolicyManagerInternal;
260 import com.android.server.pm.UserRestrictionsUtils;
261 import com.android.server.storage.DeviceStorageMonitorInternal;
262 import com.android.server.uri.UriGrantsManagerInternal;
263 import com.android.server.wm.ActivityTaskManagerInternal;
264 
265 import com.google.android.collect.Sets;
266 
267 import org.xmlpull.v1.XmlPullParser;
268 import org.xmlpull.v1.XmlPullParserException;
269 import org.xmlpull.v1.XmlSerializer;
270 
271 import java.io.File;
272 import java.io.FileDescriptor;
273 import java.io.FileInputStream;
274 import java.io.FileNotFoundException;
275 import java.io.FileOutputStream;
276 import java.io.IOException;
277 import java.io.PrintWriter;
278 import java.lang.reflect.Constructor;
279 import java.nio.charset.StandardCharsets;
280 import java.text.DateFormat;
281 import java.time.LocalDate;
282 import java.util.ArrayList;
283 import java.util.Arrays;
284 import java.util.Collection;
285 import java.util.Collections;
286 import java.util.Date;
287 import java.util.HashMap;
288 import java.util.List;
289 import java.util.Map;
290 import java.util.Map.Entry;
291 import java.util.Set;
292 import java.util.concurrent.TimeUnit;
293 import java.util.concurrent.atomic.AtomicBoolean;
294 import java.util.function.Function;
295 
296 /**
297  * Implementation of the device policy APIs.
298  */
299 public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
300 
301     protected static final String LOG_TAG = "DevicePolicyManager";
302 
303     private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
304 
305     private static final String DEVICE_POLICIES_XML = "device_policies.xml";
306 
307     private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML =
308             "transfer-ownership-parameters.xml";
309 
310     private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
311 
312     private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
313 
314     private static final String TAG_LOCK_TASK_FEATURES = "lock-task-features";
315 
316     private static final String TAG_STATUS_BAR = "statusbar";
317 
318     private static final String ATTR_DISABLED = "disabled";
319 
320     private static final String ATTR_NAME = "name";
321 
322     private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
323             "do-not-ask-credentials-on-boot";
324 
325     private static final String TAG_AFFILIATION_ID = "affiliation-id";
326 
327     private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval";
328 
329     private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request";
330 
331     private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval";
332 
333     private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
334 
335     private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set";
336 
337     private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert";
338 
339     private static final String ATTR_ID = "id";
340 
341     private static final String ATTR_VALUE = "value";
342 
343     private static final String ATTR_ALIAS = "alias";
344 
345     private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
346 
347     private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token";
348 
349     private static final String TAG_PASSWORD_VALIDITY = "password-validity";
350 
351     private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle";
352 
353     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
354 
355     private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
356 
357     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
358 
359     private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
360             = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
361 
362     private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
363     private static final String ATTR_SETUP_COMPLETE = "setup-complete";
364     private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
365     private static final String ATTR_PERMISSION_POLICY = "permission-policy";
366     private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
367             "device-provisioning-config-applied";
368     private static final String ATTR_DEVICE_PAIRED = "device-paired";
369     private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
370     private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
371             = "application-restrictions-manager";
372 
373     // Comprehensive list of delegations.
374     private static final String DELEGATIONS[] = {
375         DELEGATION_CERT_INSTALL,
376         DELEGATION_APP_RESTRICTIONS,
377         DELEGATION_BLOCK_UNINSTALL,
378         DELEGATION_ENABLE_SYSTEM_APP,
379         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
380         DELEGATION_PACKAGE_ACCESS,
381         DELEGATION_PERMISSION_GRANT,
382         DELEGATION_INSTALL_EXISTING_PACKAGE,
383         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
384         DELEGATION_NETWORK_LOGGING,
385         DELEGATION_CERT_SELECTION,
386     };
387 
388     // Subset of delegations that can only be delegated by Device Owner.
389     private static final List<String> DEVICE_OWNER_DELEGATIONS = Arrays.asList(new String[] {
390             DELEGATION_NETWORK_LOGGING,
391     });
392 
393     // Subset of delegations that only one single package within a given user can hold
394     private static final List<String> EXCLUSIVE_DELEGATIONS = Arrays.asList(new String[] {
395             DELEGATION_NETWORK_LOGGING,
396             DELEGATION_CERT_SELECTION,
397     });
398 
399     /**
400      *  System property whose value is either "true" or "false", indicating whether
401      *  device owner is present.
402      */
403     private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.organization_owned";
404 
405     private static final int STATUS_BAR_DISABLE_MASK =
406             StatusBarManager.DISABLE_EXPAND |
407             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
408             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
409             StatusBarManager.DISABLE_SEARCH;
410 
411     private static final int STATUS_BAR_DISABLE2_MASK =
412             StatusBarManager.DISABLE2_QUICK_SETTINGS;
413 
414     private static final Set<String> SECURE_SETTINGS_WHITELIST;
415     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
416     private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
417     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
418     private static final Set<String> SYSTEM_SETTINGS_WHITELIST;
419     private static final Set<Integer> DA_DISALLOWED_POLICIES;
420     private static final String AB_DEVICE_KEY = "ro.build.ab_update";
421 
422     static {
423         SECURE_SETTINGS_WHITELIST = new ArraySet<>();
424         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
425         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
426         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
427 
428         SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
429         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
430         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
431 
432         GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
433         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
434         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_WIFI_ENABLED);
435         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
436         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
437         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
438         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
439         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
440         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
441         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
442         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.PRIVATE_DNS_MODE);
443         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.PRIVATE_DNS_SPECIFIER);
444 
445         GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
446         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
447         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
448         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
449         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
450         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
451 
452         SYSTEM_SETTINGS_WHITELIST = new ArraySet<>();
453         SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS);
454         SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE);
455         SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_OFF_TIMEOUT);
456 
457         DA_DISALLOWED_POLICIES = new ArraySet<>();
458         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
459         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES);
460         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD);
461         DA_DISALLOWED_POLICIES.add(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
462     }
463 
464     /**
465      * Keyguard features that when set on a profile affect the profile content or challenge only.
466      * These cannot be set on the managed profile's parent DPM instance
467      */
468     private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
469             DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
470 
471     /** Keyguard features that are allowed to be set on a managed profile */
472     private static final int PROFILE_KEYGUARD_FEATURES =
473             PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
474 
475     private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
476 
477     /**
478      * Minimum timeout in milliseconds after which unlocking with weak auth times out,
479      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
480      */
481     private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
482 
483     /**
484      * The amount of ms that a managed kiosk must go without user interaction to be considered
485      * unattended.
486      */
487     private static final int UNATTENDED_MANAGED_KIOSK_MS = 30000;
488 
489     /**
490      * Strings logged with {@link
491      * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}
492      * and {@link DevicePolicyEnums#PROVISIONING_ENTRY_POINT_ADB}.
493      */
494     private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
495     private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
496 
497     final Context mContext;
498     final Injector mInjector;
499     final IPackageManager mIPackageManager;
500     final UserManager mUserManager;
501     final UserManagerInternal mUserManagerInternal;
502     final UsageStatsManagerInternal mUsageStatsManagerInternal;
503     final TelephonyManager mTelephonyManager;
504     private final LockPatternUtils mLockPatternUtils;
505     private final DeviceAdminServiceController mDeviceAdminServiceController;
506     private final OverlayPackagesProvider mOverlayPackagesProvider;
507 
508     private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl();
509 
510     /**
511      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
512      * is requested for user u.
513      */
514     private final Set<Pair<String, Integer>> mPackagesToRemove =
515             new ArraySet<Pair<String, Integer>>();
516 
517     final LocalService mLocalService;
518 
519     // Stores and loads state on device and profile owners.
520     @VisibleForTesting
521     final Owners mOwners;
522 
523     private final Binder mToken = new Binder();
524 
525     /**
526      * Whether or not device admin feature is supported. If it isn't return defaults for all
527      * public methods.
528      */
529     final boolean mHasFeature;
530 
531     /**
532      * Whether or not this device is a watch.
533      */
534     final boolean mIsWatch;
535 
536     /**
537      * Whether this device has the telephony feature.
538      */
539     final boolean mHasTelephonyFeature;
540 
541     private final CertificateMonitor mCertificateMonitor;
542     private final SecurityLogMonitor mSecurityLogMonitor;
543 
544     @GuardedBy("getLockObject()")
545     private NetworkLogger mNetworkLogger;
546 
547     private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
548     private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
549 
550     private final SetupContentObserver mSetupContentObserver;
551     private final DevicePolicyConstantsObserver mConstantsObserver;
552 
553     private DevicePolicyConstants mConstants;
554 
555     private static final boolean ENABLE_LOCK_GUARD = true;
556 
557     interface Stats {
558         int LOCK_GUARD_GUARD = 0;
559 
560         int COUNT = LOCK_GUARD_GUARD + 1;
561     }
562 
563     private final StatLogger mStatLogger = new StatLogger(new String[] {
564             "LockGuard.guard()",
565     });
566 
567     private final Object mLockDoNoUseDirectly = LockGuard.installNewLock(
568             LockGuard.INDEX_DPMS, /* doWtf=*/ true);
569 
getLockObject()570     final Object getLockObject() {
571         if (ENABLE_LOCK_GUARD) {
572             final long start = mStatLogger.getTime();
573             LockGuard.guard(LockGuard.INDEX_DPMS);
574             mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start);
575         }
576         return mLockDoNoUseDirectly;
577     }
578 
579     /**
580      * Check if the current thread holds the DPMS lock, and if not, do a WTF.
581      *
582      * (Doing this check too much may be costly, so don't call it in a hot path.)
583      */
ensureLocked()584     final void ensureLocked() {
585         if (Thread.holdsLock(mLockDoNoUseDirectly)) {
586             return;
587         }
588         Slog.wtfStack(LOG_TAG, "Not holding DPMS lock.");
589     }
590 
591     @VisibleForTesting
592     final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager;
593 
594     private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
595         @Override
596         public void run() {
597             if(mRemoteBugreportServiceIsActive.get()) {
598                 onBugreportFailed();
599             }
600         }
601     };
602 
603     /** Listens only if mHasFeature == true. */
604     private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
605 
606         @Override
607         public void onReceive(Context context, Intent intent) {
608             if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
609                     && mRemoteBugreportServiceIsActive.get()) {
610                 onBugreportFinished(intent);
611             }
612         }
613     };
614 
615     /** Listens only if mHasFeature == true. */
616     private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
617 
618         @Override
619         public void onReceive(Context context, Intent intent) {
620             String action = intent.getAction();
621             mInjector.getNotificationManager().cancel(LOG_TAG,
622                     RemoteBugreportUtils.NOTIFICATION_ID);
623             if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
624                 onBugreportSharingAccepted();
625             } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
626                 onBugreportSharingDeclined();
627             }
628             mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
629         }
630     };
631 
632     public static final class Lifecycle extends SystemService {
633         private BaseIDevicePolicyManager mService;
634 
Lifecycle(Context context)635         public Lifecycle(Context context) {
636             super(context);
637             String dpmsClassName = context.getResources()
638                     .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
639             if (TextUtils.isEmpty(dpmsClassName)) {
640                 dpmsClassName = DevicePolicyManagerService.class.getName();
641             }
642             try {
643                 Class serviceClass = Class.forName(dpmsClassName);
644                 Constructor constructor = serviceClass.getConstructor(Context.class);
645                 mService = (BaseIDevicePolicyManager) constructor.newInstance(context);
646             } catch (Exception e) {
647                 throw new IllegalStateException(
648                     "Failed to instantiate DevicePolicyManagerService with class name: "
649                     + dpmsClassName, e);
650             }
651         }
652 
653         @Override
onStart()654         public void onStart() {
655             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
656         }
657 
658         @Override
onBootPhase(int phase)659         public void onBootPhase(int phase) {
660             mService.systemReady(phase);
661         }
662 
663         @Override
onStartUser(int userHandle)664         public void onStartUser(int userHandle) {
665             mService.handleStartUser(userHandle);
666         }
667 
668         @Override
onUnlockUser(int userHandle)669         public void onUnlockUser(int userHandle) {
670             mService.handleUnlockUser(userHandle);
671         }
672 
673         @Override
onStopUser(int userHandle)674         public void onStopUser(int userHandle) {
675             mService.handleStopUser(userHandle);
676         }
677     }
678 
679     public static class DevicePolicyData {
680         int mFailedPasswordAttempts = 0;
681         boolean mPasswordValidAtLastCheckpoint = true;
682 
683         int mUserHandle;
684         int mPasswordOwner = -1;
685         long mLastMaximumTimeToLock = -1;
686         boolean mUserSetupComplete = false;
687         boolean mPaired = false;
688         int mUserProvisioningState;
689         int mPermissionPolicy;
690 
691         boolean mDeviceProvisioningConfigApplied = false;
692 
693         final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
694         final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
695         final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
696 
697         // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
698         final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
699 
700         // This is the list of component allowed to start lock task mode.
701         List<String> mLockTaskPackages = new ArrayList<>();
702 
703         // Bitfield of feature flags to be enabled during LockTask mode.
704         // We default on the power button menu, in order to be consistent with pre-P behaviour.
705         int mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
706 
707         boolean mStatusBarDisabled = false;
708 
709         ComponentName mRestrictionsProvider;
710 
711         // Map of delegate package to delegation scopes
712         final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>();
713 
714         boolean doNotAskCredentialsOnBoot = false;
715 
716         Set<String> mAffiliationIds = new ArraySet<>();
717 
718         long mLastSecurityLogRetrievalTime = -1;
719 
720         long mLastBugReportRequestTime = -1;
721 
722         long mLastNetworkLogsRetrievalTime = -1;
723 
724         boolean mCurrentInputMethodSet = false;
725 
726         // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
727         Set<String> mOwnerInstalledCaCerts = new ArraySet<>();
728 
729         // Used for initialization of users created by createAndManageUser.
730         boolean mAdminBroadcastPending = false;
731         PersistableBundle mInitBundle = null;
732 
733         long mPasswordTokenHandle = 0;
734 
DevicePolicyData(int userHandle)735         public DevicePolicyData(int userHandle) {
736             mUserHandle = userHandle;
737         }
738     }
739 
740     @GuardedBy("getLockObject()")
741     final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
742 
743     @GuardedBy("getLockObject()")
744     final SparseArray<PasswordMetrics> mUserPasswordMetrics = new SparseArray<>();
745 
746     final Handler mHandler;
747     final Handler mBackgroundHandler;
748 
749     /** Listens only if mHasFeature == true. */
750     final BroadcastReceiver mReceiver = new BroadcastReceiver() {
751         @Override
752         public void onReceive(Context context, Intent intent) {
753             final String action = intent.getAction();
754             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
755                     getSendingUserId());
756 
757             /*
758              * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
759              * however it's too early in the boot process to register with IIpConnectivityMetrics
760              * to listen for events.
761              */
762             if (Intent.ACTION_USER_STARTED.equals(action)
763                     && userHandle == mOwners.getDeviceOwnerUserId()) {
764                 synchronized (getLockObject()) {
765                     if (isNetworkLoggingEnabledInternalLocked()) {
766                         setNetworkLoggingActiveInternal(true);
767                     }
768                 }
769             }
770             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
771                     && userHandle == mOwners.getDeviceOwnerUserId()
772                     && getDeviceOwnerRemoteBugreportUri() != null) {
773                 IntentFilter filterConsent = new IntentFilter();
774                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
775                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
776                 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
777                 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
778                         RemoteBugreportUtils.NOTIFICATION_ID,
779                         RemoteBugreportUtils.buildNotification(mContext,
780                                 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
781                                 UserHandle.ALL);
782             }
783             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
784                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
785                 if (VERBOSE_LOG) {
786                     Slog.v(LOG_TAG, "Sending password expiration notifications for action "
787                             + action + " for user " + userHandle);
788                 }
789                 mHandler.post(new Runnable() {
790                     @Override
791                     public void run() {
792                         handlePasswordExpirationNotification(userHandle);
793                     }
794                 });
795             }
796 
797             if (Intent.ACTION_USER_ADDED.equals(action)) {
798                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
799                 synchronized (getLockObject()) {
800                     // It might take a while for the user to become affiliated. Make security
801                     // and network logging unavailable in the meantime.
802                     maybePauseDeviceWideLoggingLocked();
803                 }
804             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
805                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
806                 synchronized (getLockObject()) {
807                     // Check whether the user is affiliated, *before* removing its data.
808                     boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
809                     removeUserData(userHandle);
810                     if (!isRemovedUserAffiliated) {
811                         // We discard the logs when unaffiliated users are deleted (so that the
812                         // device owner cannot retrieve data about that user after it's gone).
813                         discardDeviceWideLogsLocked();
814                         // Resume logging if all remaining users are affiliated.
815                         maybeResumeDeviceWideLoggingLocked();
816                     }
817                 }
818             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
819                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle);
820                 synchronized (getLockObject()) {
821                     maybeSendAdminEnabledBroadcastLocked(userHandle);
822                     // Reset the policy data
823                     mUserData.remove(userHandle);
824                 }
825                 handlePackagesChanged(null /* check all admins */, userHandle);
826             } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
827                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle);
828             } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
829                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle);
830             } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
831                 synchronized (getLockObject()) {
832                     maybeSendAdminEnabledBroadcastLocked(userHandle);
833                 }
834             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
835                 handlePackagesChanged(null /* check all admins */, userHandle);
836             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
837                     || (Intent.ACTION_PACKAGE_ADDED.equals(action)
838                     && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
839                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
840             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
841                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
842                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
843             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
844                 clearWipeProfileNotification();
845             } else if (Intent.ACTION_DATE_CHANGED.equals(action)
846                     || Intent.ACTION_TIME_CHANGED.equals(action)) {
847                 // Update freeze period record when clock naturally progresses to the next day
848                 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made
849                 // (ACTION_TIME_CHANGED)
850                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
851             }
852 
853         }
854 
855         private void sendDeviceOwnerUserCommand(String action, int userHandle) {
856             synchronized (getLockObject()) {
857                 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
858                 if (deviceOwner != null) {
859                     Bundle extras = new Bundle();
860                     extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
861                     sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null,
862                             /* inForeground */ true);
863                 }
864             }
865         }
866     };
867 
868     protected static class RestrictionsListener implements UserRestrictionsListener {
869         private Context mContext;
870 
RestrictionsListener(Context context)871         public RestrictionsListener(Context context) {
872             mContext = context;
873         }
874 
onUserRestrictionsChanged(int userId, Bundle newRestrictions, Bundle prevRestrictions)875         public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
876                 Bundle prevRestrictions) {
877             final boolean newlyDisallowed =
878                     newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE);
879             final boolean previouslyDisallowed =
880                     prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE);
881             final boolean restrictionChanged = (newlyDisallowed != previouslyDisallowed);
882 
883             if (restrictionChanged) {
884                 // Notify ManagedProvisioning to update the built-in cross profile intent filters.
885                 Intent intent = new Intent(
886                         DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
887                 intent.setPackage(getManagedProvisioningPackage(mContext));
888                 intent.putExtra(Intent.EXTRA_USER_ID, userId);
889                 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
890                 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
891             }
892         }
893     }
894 
895     static class ActiveAdmin {
896         private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
897         private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
898         private static final String TAG_DISABLE_CAMERA = "disable-camera";
899         private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
900         private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
901         private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
902                 = "disable-bt-contacts-sharing";
903         private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
904         private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
905         private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
906         private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
907         private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
908         private static final String TAG_ACCOUNT_TYPE = "account-type";
909         private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
910                 = "permitted-accessiblity-services";
911         private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
912         private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
913         private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
914         private static final String TAG_TRUST_AGENT_COMPONENT = "component";
915         private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
916         private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
917         private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
918         private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
919         private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
920         private static final String TAG_PERMITTED_IMES = "permitted-imes";
921         private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS =
922                 "permitted-notification-listeners";
923         private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
924         private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
925         private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
926         private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
927         private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
928         private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
929         private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
930         private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
931         private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
932         private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
933         private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
934         private static final String ATTR_VALUE = "value";
935         private static final String TAG_PASSWORD_QUALITY = "password-quality";
936         private static final String TAG_POLICIES = "policies";
937         private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
938                 "cross-profile-widget-providers";
939         private static final String TAG_PROVIDER = "provider";
940         private static final String TAG_PACKAGE_LIST_ITEM  = "item";
941         private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
942         private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
943         private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS =
944                 "default-enabled-user-restrictions";
945         private static final String TAG_RESTRICTION = "restriction";
946         private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
947         private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
948         private static final String TAG_PARENT_ADMIN = "parent-admin";
949         private static final String TAG_ORGANIZATION_COLOR = "organization-color";
950         private static final String TAG_ORGANIZATION_NAME = "organization-name";
951         private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
952         private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
953         private static final String TAG_IS_LOGOUT_ENABLED = "is_logout_enabled";
954         private static final String TAG_START_USER_SESSION_MESSAGE = "start_user_session_message";
955         private static final String TAG_END_USER_SESSION_MESSAGE = "end_user_session_message";
956         private static final String TAG_METERED_DATA_DISABLED_PACKAGES =
957                 "metered_data_disabled_packages";
958         private static final String TAG_CROSS_PROFILE_CALENDAR_PACKAGES =
959                 "cross-profile-calendar-packages";
960         private static final String TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL =
961                 "cross-profile-calendar-packages-null";
962 
963         DeviceAdminInfo info;
964 
965 
966         static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
967         int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
968 
969         static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
970         static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
971         static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
972         static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
973         static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
974         static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
975         static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
976         @NonNull
977         PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
978                 PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
979                 DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
980                 DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
981                 DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
982 
983         static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
984         long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
985 
986         long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
987 
988         static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
989         int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
990 
991         static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
992         long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
993 
994         static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
995         long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
996 
997         static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
998 
999         int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
1000 
1001         boolean encryptionRequested = false;
1002         boolean testOnlyAdmin = false;
1003         boolean disableCamera = false;
1004         boolean disableCallerId = false;
1005         boolean disableContactsSearch = false;
1006         boolean disableBluetoothContactSharing = true;
1007         boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
1008         boolean requireAutoTime = false; // Can only be set by a device owner.
1009         boolean forceEphemeralUsers = false; // Can only be set by a device owner.
1010         boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
1011         boolean isLogoutEnabled = false; // Can only be set by a device owner.
1012 
1013         // one notification after enabling + one more after reboots
1014         static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2;
1015         int numNetworkLoggingNotifications = 0;
1016         long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
1017 
1018         ActiveAdmin parentAdmin;
1019         final boolean isParent;
1020 
1021         static class TrustAgentInfo {
1022             public PersistableBundle options;
TrustAgentInfo(PersistableBundle bundle)1023             TrustAgentInfo(PersistableBundle bundle) {
1024                 options = bundle;
1025             }
1026         }
1027 
1028         // The list of packages which are not allowed to use metered data.
1029         List<String> meteredDisabledPackages;
1030 
1031         final Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
1032 
1033         // The list of permitted accessibility services package namesas set by a profile
1034         // or device owner. Null means all accessibility services are allowed, empty means
1035         // none except system services are allowed.
1036         List<String> permittedAccessiblityServices;
1037 
1038         // The list of permitted input methods package names as set by a profile or device owner.
1039         // Null means all input methods are allowed, empty means none except system imes are
1040         // allowed.
1041         List<String> permittedInputMethods;
1042 
1043         // The list of packages allowed to use a NotificationListenerService to receive events for
1044         // notifications from this user. Null means that all packages are allowed. Empty list means
1045         // that only packages from the system are allowed.
1046         List<String> permittedNotificationListeners;
1047 
1048         // List of package names to keep cached.
1049         List<String> keepUninstalledPackages;
1050 
1051         // TODO: review implementation decisions with frameworks team
1052         boolean specifiesGlobalProxy = false;
1053         String globalProxySpec = null;
1054         String globalProxyExclusionList = null;
1055 
1056         ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
1057 
1058         List<String> crossProfileWidgetProviders;
1059 
1060         Bundle userRestrictions;
1061 
1062         // User restrictions that have already been enabled by default for this admin (either when
1063         // setting the device or profile owner, or during a system update if one of those "enabled
1064         // by default" restrictions is newly added).
1065         final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>();
1066 
1067         // Support text provided by the admin to display to the user.
1068         CharSequence shortSupportMessage = null;
1069         CharSequence longSupportMessage = null;
1070 
1071         // Background color of confirm credentials screen. Default: teal.
1072         static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
1073         int organizationColor = DEF_ORGANIZATION_COLOR;
1074 
1075         // Default title of confirm credentials screen
1076         String organizationName = null;
1077 
1078         // Message for user switcher
1079         String startUserSessionMessage = null;
1080         String endUserSessionMessage = null;
1081 
1082         // The whitelist of packages that can access cross profile calendar APIs.
1083         // This whitelist should be in default an empty list, which indicates that no package
1084         // is whitelisted.
1085         List<String> mCrossProfileCalendarPackages = Collections.emptyList();
1086 
ActiveAdmin(DeviceAdminInfo _info, boolean parent)1087         ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
1088             info = _info;
1089             isParent = parent;
1090         }
1091 
getParentActiveAdmin()1092         ActiveAdmin getParentActiveAdmin() {
1093             Preconditions.checkState(!isParent);
1094 
1095             if (parentAdmin == null) {
1096                 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1097             }
1098             return parentAdmin;
1099         }
1100 
hasParentActiveAdmin()1101         boolean hasParentActiveAdmin() {
1102             return parentAdmin != null;
1103         }
1104 
getUid()1105         int getUid() { return info.getActivityInfo().applicationInfo.uid; }
1106 
getUserHandle()1107         public UserHandle getUserHandle() {
1108             return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
1109         }
1110 
writeToXml(XmlSerializer out)1111         void writeToXml(XmlSerializer out)
1112                 throws IllegalArgumentException, IllegalStateException, IOException {
1113             out.startTag(null, TAG_POLICIES);
1114             info.writePoliciesToXml(out);
1115             out.endTag(null, TAG_POLICIES);
1116             if (minimumPasswordMetrics.quality != PASSWORD_QUALITY_UNSPECIFIED) {
1117                 out.startTag(null, TAG_PASSWORD_QUALITY);
1118                 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
1119                 out.endTag(null, TAG_PASSWORD_QUALITY);
1120                 if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
1121                     out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
1122                     out.attribute(
1123                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
1124                     out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
1125                 }
1126                 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
1127                     out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
1128                     out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
1129                     out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
1130                 }
1131                 if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
1132                     out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
1133                     out.attribute(
1134                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
1135                     out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
1136                 }
1137                 if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
1138                     out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
1139                     out.attribute(
1140                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
1141                     out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
1142                 }
1143                 if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
1144                     out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
1145                     out.attribute(
1146                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
1147                     out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
1148                 }
1149                 if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
1150                     out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
1151                     out.attribute(
1152                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
1153                     out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
1154                 }
1155                 if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
1156                     out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
1157                     out.attribute(
1158                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
1159                     out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
1160                 }
1161                 if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
1162                     out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
1163                     out.attribute(
1164                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
1165                     out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
1166                 }
1167             }
1168             if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
1169                 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
1170                 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
1171                 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
1172             }
1173             if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
1174                 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
1175                 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
1176                 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
1177             }
1178             if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
1179                 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
1180                 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
1181                 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
1182             }
1183             if (specifiesGlobalProxy) {
1184                 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
1185                 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
1186                 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
1187                 if (globalProxySpec != null) {
1188                     out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
1189                     out.attribute(null, ATTR_VALUE, globalProxySpec);
1190                     out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
1191                 }
1192                 if (globalProxyExclusionList != null) {
1193                     out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
1194                     out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
1195                     out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
1196                 }
1197             }
1198             if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
1199                 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
1200                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
1201                 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
1202             }
1203             if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
1204                 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
1205                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
1206                 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
1207             }
1208             if (encryptionRequested) {
1209                 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
1210                 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
1211                 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
1212             }
1213             if (testOnlyAdmin) {
1214                 out.startTag(null, TAG_TEST_ONLY_ADMIN);
1215                 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
1216                 out.endTag(null, TAG_TEST_ONLY_ADMIN);
1217             }
1218             if (disableCamera) {
1219                 out.startTag(null, TAG_DISABLE_CAMERA);
1220                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
1221                 out.endTag(null, TAG_DISABLE_CAMERA);
1222             }
1223             if (disableCallerId) {
1224                 out.startTag(null, TAG_DISABLE_CALLER_ID);
1225                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
1226                 out.endTag(null, TAG_DISABLE_CALLER_ID);
1227             }
1228             if (disableContactsSearch) {
1229                 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
1230                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
1231                 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
1232             }
1233             if (!disableBluetoothContactSharing) {
1234                 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
1235                 out.attribute(null, ATTR_VALUE,
1236                         Boolean.toString(disableBluetoothContactSharing));
1237                 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
1238             }
1239             if (disableScreenCapture) {
1240                 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1241                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
1242                 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1243             }
1244             if (requireAutoTime) {
1245                 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
1246                 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
1247                 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
1248             }
1249             if (forceEphemeralUsers) {
1250                 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
1251                 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
1252                 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
1253             }
1254             if (isNetworkLoggingEnabled) {
1255                 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1256                 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
1257                 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
1258                         Integer.toString(numNetworkLoggingNotifications));
1259                 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
1260                         Long.toString(lastNetworkLoggingNotificationTimeMs));
1261                 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1262             }
1263             if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
1264                 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1265                 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
1266                 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1267             }
1268             if (!accountTypesWithManagementDisabled.isEmpty()) {
1269                 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
1270                 writeAttributeValuesToXml(
1271                         out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1272                 out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
1273             }
1274             if (!trustAgentInfos.isEmpty()) {
1275                 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
1276                 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1277                 for (Entry<String, TrustAgentInfo> entry : set) {
1278                     TrustAgentInfo trustAgentInfo = entry.getValue();
1279                     out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
1280                     out.attribute(null, ATTR_VALUE, entry.getKey());
1281                     if (trustAgentInfo.options != null) {
1282                         out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1283                         try {
1284                             trustAgentInfo.options.saveToXml(out);
1285                         } catch (XmlPullParserException e) {
1286                             Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
1287                         }
1288                         out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1289                     }
1290                     out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
1291                 }
1292                 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1293             }
1294             if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
1295                 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1296                 writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders);
1297                 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1298             }
1299             writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
1300                     permittedAccessiblityServices);
1301             writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
1302             writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS,
1303                     permittedNotificationListeners);
1304             writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
1305             writePackageListToXml(out, TAG_METERED_DATA_DISABLED_PACKAGES, meteredDisabledPackages);
1306             if (hasUserRestrictions()) {
1307                 UserRestrictionsUtils.writeRestrictions(
1308                         out, userRestrictions, TAG_USER_RESTRICTIONS);
1309             }
1310             if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) {
1311                 out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1312                 writeAttributeValuesToXml(
1313                         out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1314                 out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1315             }
1316             if (!TextUtils.isEmpty(shortSupportMessage)) {
1317                 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1318                 out.text(shortSupportMessage.toString());
1319                 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1320             }
1321             if (!TextUtils.isEmpty(longSupportMessage)) {
1322                 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
1323                 out.text(longSupportMessage.toString());
1324                 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
1325             }
1326             if (parentAdmin != null) {
1327                 out.startTag(null, TAG_PARENT_ADMIN);
1328                 parentAdmin.writeToXml(out);
1329                 out.endTag(null, TAG_PARENT_ADMIN);
1330             }
1331             if (organizationColor != DEF_ORGANIZATION_COLOR) {
1332                 out.startTag(null, TAG_ORGANIZATION_COLOR);
1333                 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
1334                 out.endTag(null, TAG_ORGANIZATION_COLOR);
1335             }
1336             if (organizationName != null) {
1337                 out.startTag(null, TAG_ORGANIZATION_NAME);
1338                 out.text(organizationName);
1339                 out.endTag(null, TAG_ORGANIZATION_NAME);
1340             }
1341             if (isLogoutEnabled) {
1342                 out.startTag(null, TAG_IS_LOGOUT_ENABLED);
1343                 out.attribute(null, ATTR_VALUE, Boolean.toString(isLogoutEnabled));
1344                 out.endTag(null, TAG_IS_LOGOUT_ENABLED);
1345             }
1346             if (startUserSessionMessage != null) {
1347                 out.startTag(null, TAG_START_USER_SESSION_MESSAGE);
1348                 out.text(startUserSessionMessage);
1349                 out.endTag(null, TAG_START_USER_SESSION_MESSAGE);
1350             }
1351             if (endUserSessionMessage != null) {
1352                 out.startTag(null, TAG_END_USER_SESSION_MESSAGE);
1353                 out.text(endUserSessionMessage);
1354                 out.endTag(null, TAG_END_USER_SESSION_MESSAGE);
1355             }
1356             if (mCrossProfileCalendarPackages == null) {
1357                 out.startTag(null, TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL);
1358                 out.endTag(null, TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL);
1359             } else {
1360                 writePackageListToXml(out, TAG_CROSS_PROFILE_CALENDAR_PACKAGES,
1361                         mCrossProfileCalendarPackages);
1362             }
1363         }
1364 
writePackageListToXml(XmlSerializer out, String outerTag, List<String> packageList)1365         void writePackageListToXml(XmlSerializer out, String outerTag,
1366                 List<String> packageList)
1367                 throws IllegalArgumentException, IllegalStateException, IOException {
1368             if (packageList == null) {
1369                 return;
1370             }
1371 
1372             out.startTag(null, outerTag);
1373             writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList);
1374             out.endTag(null, outerTag);
1375         }
1376 
writeAttributeValuesToXml(XmlSerializer out, String tag, @NonNull Collection<String> values)1377         void writeAttributeValuesToXml(XmlSerializer out, String tag,
1378                 @NonNull Collection<String> values) throws IOException {
1379             for (String value : values) {
1380                 out.startTag(null, tag);
1381                 out.attribute(null, ATTR_VALUE, value);
1382                 out.endTag(null, tag);
1383             }
1384         }
1385 
readFromXml(XmlPullParser parser, boolean shouldOverridePolicies)1386         void readFromXml(XmlPullParser parser, boolean shouldOverridePolicies)
1387                 throws XmlPullParserException, IOException {
1388             int outerDepth = parser.getDepth();
1389             int type;
1390             while ((type=parser.next()) != END_DOCUMENT
1391                    && (type != END_TAG || parser.getDepth() > outerDepth)) {
1392                 if (type == END_TAG || type == TEXT) {
1393                     continue;
1394                 }
1395                 String tag = parser.getName();
1396                 if (TAG_POLICIES.equals(tag)) {
1397                     if (shouldOverridePolicies) {
1398                         Log.d(LOG_TAG, "Overriding device admin policies from XML.");
1399                         info.readPoliciesFromXml(parser);
1400                     }
1401                 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1402                     minimumPasswordMetrics.quality = Integer.parseInt(
1403                             parser.getAttributeValue(null, ATTR_VALUE));
1404                 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1405                     minimumPasswordMetrics.length = Integer.parseInt(
1406                             parser.getAttributeValue(null, ATTR_VALUE));
1407                 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1408                     passwordHistoryLength = Integer.parseInt(
1409                             parser.getAttributeValue(null, ATTR_VALUE));
1410                 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1411                     minimumPasswordMetrics.upperCase = Integer.parseInt(
1412                             parser.getAttributeValue(null, ATTR_VALUE));
1413                 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1414                     minimumPasswordMetrics.lowerCase = Integer.parseInt(
1415                             parser.getAttributeValue(null, ATTR_VALUE));
1416                 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1417                     minimumPasswordMetrics.letters = Integer.parseInt(
1418                             parser.getAttributeValue(null, ATTR_VALUE));
1419                 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1420                     minimumPasswordMetrics.numeric = Integer.parseInt(
1421                             parser.getAttributeValue(null, ATTR_VALUE));
1422                 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1423                     minimumPasswordMetrics.symbols = Integer.parseInt(
1424                             parser.getAttributeValue(null, ATTR_VALUE));
1425                 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1426                     minimumPasswordMetrics.nonLetter = Integer.parseInt(
1427                             parser.getAttributeValue(null, ATTR_VALUE));
1428                 }else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1429                     maximumTimeToUnlock = Long.parseLong(
1430                             parser.getAttributeValue(null, ATTR_VALUE));
1431                 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1432                     strongAuthUnlockTimeout = Long.parseLong(
1433                             parser.getAttributeValue(null, ATTR_VALUE));
1434                 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1435                     maximumFailedPasswordsForWipe = Integer.parseInt(
1436                             parser.getAttributeValue(null, ATTR_VALUE));
1437                 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1438                     specifiesGlobalProxy = Boolean.parseBoolean(
1439                             parser.getAttributeValue(null, ATTR_VALUE));
1440                 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1441                     globalProxySpec =
1442                         parser.getAttributeValue(null, ATTR_VALUE);
1443                 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1444                     globalProxyExclusionList =
1445                         parser.getAttributeValue(null, ATTR_VALUE);
1446                 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1447                     passwordExpirationTimeout = Long.parseLong(
1448                             parser.getAttributeValue(null, ATTR_VALUE));
1449                 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1450                     passwordExpirationDate = Long.parseLong(
1451                             parser.getAttributeValue(null, ATTR_VALUE));
1452                 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1453                     encryptionRequested = Boolean.parseBoolean(
1454                             parser.getAttributeValue(null, ATTR_VALUE));
1455                 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1456                     testOnlyAdmin = Boolean.parseBoolean(
1457                             parser.getAttributeValue(null, ATTR_VALUE));
1458                 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1459                     disableCamera = Boolean.parseBoolean(
1460                             parser.getAttributeValue(null, ATTR_VALUE));
1461                 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1462                     disableCallerId = Boolean.parseBoolean(
1463                             parser.getAttributeValue(null, ATTR_VALUE));
1464                 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1465                     disableContactsSearch = Boolean.parseBoolean(
1466                             parser.getAttributeValue(null, ATTR_VALUE));
1467                 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1468                     disableBluetoothContactSharing = Boolean.parseBoolean(parser
1469                             .getAttributeValue(null, ATTR_VALUE));
1470                 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1471                     disableScreenCapture = Boolean.parseBoolean(
1472                             parser.getAttributeValue(null, ATTR_VALUE));
1473                 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1474                     requireAutoTime = Boolean.parseBoolean(
1475                             parser.getAttributeValue(null, ATTR_VALUE));
1476                 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1477                     forceEphemeralUsers = Boolean.parseBoolean(
1478                             parser.getAttributeValue(null, ATTR_VALUE));
1479                 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1480                     isNetworkLoggingEnabled = Boolean.parseBoolean(
1481                             parser.getAttributeValue(null, ATTR_VALUE));
1482                     lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1483                             parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1484                     numNetworkLoggingNotifications = Integer.parseInt(
1485                             parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1486                 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1487                     disabledKeyguardFeatures = Integer.parseInt(
1488                             parser.getAttributeValue(null, ATTR_VALUE));
1489                 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1490                     readAttributeValues(
1491                             parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1492                 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1493                     trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1494                 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1495                     crossProfileWidgetProviders = new ArrayList<>();
1496                     readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders);
1497                 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1498                     permittedAccessiblityServices = readPackageList(parser, tag);
1499                 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1500                     permittedInputMethods = readPackageList(parser, tag);
1501                 } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) {
1502                     permittedNotificationListeners = readPackageList(parser, tag);
1503                 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1504                     keepUninstalledPackages = readPackageList(parser, tag);
1505                 } else if (TAG_METERED_DATA_DISABLED_PACKAGES.equals(tag)) {
1506                     meteredDisabledPackages = readPackageList(parser, tag);
1507                 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1508                     userRestrictions = UserRestrictionsUtils.readRestrictions(parser);
1509                 } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) {
1510                     readAttributeValues(
1511                             parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1512                 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1513                     type = parser.next();
1514                     if (type == XmlPullParser.TEXT) {
1515                         shortSupportMessage = parser.getText();
1516                     } else {
1517                         Log.w(LOG_TAG, "Missing text when loading short support message");
1518                     }
1519                 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1520                     type = parser.next();
1521                     if (type == XmlPullParser.TEXT) {
1522                         longSupportMessage = parser.getText();
1523                     } else {
1524                         Log.w(LOG_TAG, "Missing text when loading long support message");
1525                     }
1526                 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1527                     Preconditions.checkState(!isParent);
1528                     parentAdmin = new ActiveAdmin(info, /* parent */ true);
1529                     parentAdmin.readFromXml(parser, shouldOverridePolicies);
1530                 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1531                     organizationColor = Integer.parseInt(
1532                             parser.getAttributeValue(null, ATTR_VALUE));
1533                 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1534                     type = parser.next();
1535                     if (type == XmlPullParser.TEXT) {
1536                         organizationName = parser.getText();
1537                     } else {
1538                         Log.w(LOG_TAG, "Missing text when loading organization name");
1539                     }
1540                 } else if (TAG_IS_LOGOUT_ENABLED.equals(tag)) {
1541                     isLogoutEnabled = Boolean.parseBoolean(
1542                             parser.getAttributeValue(null, ATTR_VALUE));
1543                 } else if (TAG_START_USER_SESSION_MESSAGE.equals(tag)) {
1544                     type = parser.next();
1545                     if (type == XmlPullParser.TEXT) {
1546                         startUserSessionMessage = parser.getText();
1547                     } else {
1548                         Log.w(LOG_TAG, "Missing text when loading start session message");
1549                     }
1550                 } else if (TAG_END_USER_SESSION_MESSAGE.equals(tag)) {
1551                     type = parser.next();
1552                     if (type == XmlPullParser.TEXT) {
1553                         endUserSessionMessage = parser.getText();
1554                     } else {
1555                         Log.w(LOG_TAG, "Missing text when loading end session message");
1556                     }
1557                 } else if (TAG_CROSS_PROFILE_CALENDAR_PACKAGES.equals(tag)) {
1558                     mCrossProfileCalendarPackages = readPackageList(parser, tag);
1559                 } else if (TAG_CROSS_PROFILE_CALENDAR_PACKAGES_NULL.equals(tag)) {
1560                     mCrossProfileCalendarPackages = null;
1561                 } else {
1562                     Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1563                     XmlUtils.skipCurrentTag(parser);
1564                 }
1565             }
1566         }
1567 
readPackageList(XmlPullParser parser, String tag)1568         private List<String> readPackageList(XmlPullParser parser,
1569                 String tag) throws XmlPullParserException, IOException {
1570             List<String> result = new ArrayList<String>();
1571             int outerDepth = parser.getDepth();
1572             int outerType;
1573             while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1574                     && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1575                 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1576                     continue;
1577                 }
1578                 String outerTag = parser.getName();
1579                 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1580                     String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1581                     if (packageName != null) {
1582                         result.add(packageName);
1583                     } else {
1584                         Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1585                     }
1586                 } else {
1587                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
1588                 }
1589             }
1590             return result;
1591         }
1592 
readAttributeValues( XmlPullParser parser, String tag, Collection<String> result)1593         private void readAttributeValues(
1594                 XmlPullParser parser, String tag, Collection<String> result)
1595                 throws XmlPullParserException, IOException {
1596             result.clear();
1597             int outerDepthDAM = parser.getDepth();
1598             int typeDAM;
1599             while ((typeDAM=parser.next()) != END_DOCUMENT
1600                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1601                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1602                     continue;
1603                 }
1604                 String tagDAM = parser.getName();
1605                 if (tag.equals(tagDAM)) {
1606                     result.add(parser.getAttributeValue(null, ATTR_VALUE));
1607                 } else {
1608                     Slog.e(LOG_TAG, "Expected tag " + tag +  " but found " + tagDAM);
1609                 }
1610             }
1611         }
1612 
getAllTrustAgentInfos( XmlPullParser parser, String tag)1613         private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1614                 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1615             int outerDepthDAM = parser.getDepth();
1616             int typeDAM;
1617             final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1618             while ((typeDAM=parser.next()) != END_DOCUMENT
1619                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1620                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1621                     continue;
1622                 }
1623                 String tagDAM = parser.getName();
1624                 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1625                     final String component = parser.getAttributeValue(null, ATTR_VALUE);
1626                     final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1627                     result.put(component, trustAgentInfo);
1628                 } else {
1629                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1630                 }
1631             }
1632             return result;
1633         }
1634 
getTrustAgentInfo(XmlPullParser parser, String tag)1635         private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1636                 throws XmlPullParserException, IOException  {
1637             int outerDepthDAM = parser.getDepth();
1638             int typeDAM;
1639             TrustAgentInfo result = new TrustAgentInfo(null);
1640             while ((typeDAM=parser.next()) != END_DOCUMENT
1641                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1642                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1643                     continue;
1644                 }
1645                 String tagDAM = parser.getName();
1646                 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1647                     result.options = PersistableBundle.restoreFromXml(parser);
1648                 } else {
1649                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1650                 }
1651             }
1652             return result;
1653         }
1654 
hasUserRestrictions()1655         boolean hasUserRestrictions() {
1656             return userRestrictions != null && userRestrictions.size() > 0;
1657         }
1658 
ensureUserRestrictions()1659         Bundle ensureUserRestrictions() {
1660             if (userRestrictions == null) {
1661                 userRestrictions = new Bundle();
1662             }
1663             return userRestrictions;
1664         }
1665 
transfer(DeviceAdminInfo deviceAdminInfo)1666         public void transfer(DeviceAdminInfo deviceAdminInfo) {
1667             if (hasParentActiveAdmin()) {
1668                 parentAdmin.info = deviceAdminInfo;
1669             }
1670             info = deviceAdminInfo;
1671         }
1672 
dump(String prefix, PrintWriter pw)1673         void dump(String prefix, PrintWriter pw) {
1674             pw.print(prefix); pw.print("uid="); pw.println(getUid());
1675             pw.print(prefix); pw.print("testOnlyAdmin=");
1676             pw.println(testOnlyAdmin);
1677             pw.print(prefix); pw.println("policies:");
1678             ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1679             if (pols != null) {
1680                 for (int i=0; i<pols.size(); i++) {
1681                     pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
1682                 }
1683             }
1684             pw.print(prefix); pw.print("passwordQuality=0x");
1685                     pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
1686             pw.print(prefix); pw.print("minimumPasswordLength=");
1687                     pw.println(minimumPasswordMetrics.length);
1688             pw.print(prefix); pw.print("passwordHistoryLength=");
1689                     pw.println(passwordHistoryLength);
1690             pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1691                     pw.println(minimumPasswordMetrics.upperCase);
1692             pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1693                     pw.println(minimumPasswordMetrics.lowerCase);
1694             pw.print(prefix); pw.print("minimumPasswordLetters=");
1695                     pw.println(minimumPasswordMetrics.letters);
1696             pw.print(prefix); pw.print("minimumPasswordNumeric=");
1697                     pw.println(minimumPasswordMetrics.numeric);
1698             pw.print(prefix); pw.print("minimumPasswordSymbols=");
1699                     pw.println(minimumPasswordMetrics.symbols);
1700             pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1701                     pw.println(minimumPasswordMetrics.nonLetter);
1702             pw.print(prefix); pw.print("maximumTimeToUnlock=");
1703                     pw.println(maximumTimeToUnlock);
1704             pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1705                     pw.println(strongAuthUnlockTimeout);
1706             pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1707                     pw.println(maximumFailedPasswordsForWipe);
1708             pw.print(prefix); pw.print("specifiesGlobalProxy=");
1709                     pw.println(specifiesGlobalProxy);
1710             pw.print(prefix); pw.print("passwordExpirationTimeout=");
1711                     pw.println(passwordExpirationTimeout);
1712             pw.print(prefix); pw.print("passwordExpirationDate=");
1713                     pw.println(passwordExpirationDate);
1714             if (globalProxySpec != null) {
1715                 pw.print(prefix); pw.print("globalProxySpec=");
1716                         pw.println(globalProxySpec);
1717             }
1718             if (globalProxyExclusionList != null) {
1719                 pw.print(prefix); pw.print("globalProxyEclusionList=");
1720                         pw.println(globalProxyExclusionList);
1721             }
1722             pw.print(prefix); pw.print("encryptionRequested=");
1723                     pw.println(encryptionRequested);
1724             pw.print(prefix); pw.print("disableCamera=");
1725                     pw.println(disableCamera);
1726             pw.print(prefix); pw.print("disableCallerId=");
1727                     pw.println(disableCallerId);
1728             pw.print(prefix); pw.print("disableContactsSearch=");
1729                     pw.println(disableContactsSearch);
1730             pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1731                     pw.println(disableBluetoothContactSharing);
1732             pw.print(prefix); pw.print("disableScreenCapture=");
1733                     pw.println(disableScreenCapture);
1734             pw.print(prefix); pw.print("requireAutoTime=");
1735                     pw.println(requireAutoTime);
1736             pw.print(prefix); pw.print("forceEphemeralUsers=");
1737                     pw.println(forceEphemeralUsers);
1738             pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1739                     pw.println(isNetworkLoggingEnabled);
1740             pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1741                     pw.println(disabledKeyguardFeatures);
1742             pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1743                     pw.println(crossProfileWidgetProviders);
1744             if (permittedAccessiblityServices != null) {
1745                 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1746                     pw.println(permittedAccessiblityServices);
1747             }
1748             if (permittedInputMethods != null) {
1749                 pw.print(prefix); pw.print("permittedInputMethods=");
1750                     pw.println(permittedInputMethods);
1751             }
1752             if (permittedNotificationListeners != null) {
1753                 pw.print(prefix); pw.print("permittedNotificationListeners=");
1754                 pw.println(permittedNotificationListeners);
1755             }
1756             if (keepUninstalledPackages != null) {
1757                 pw.print(prefix); pw.print("keepUninstalledPackages=");
1758                     pw.println(keepUninstalledPackages);
1759             }
1760             pw.print(prefix); pw.print("organizationColor=");
1761                     pw.println(organizationColor);
1762             if (organizationName != null) {
1763                 pw.print(prefix); pw.print("organizationName=");
1764                     pw.println(organizationName);
1765             }
1766             pw.print(prefix); pw.println("userRestrictions:");
1767             UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
1768             pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet=");
1769                     pw.println(defaultEnabledRestrictionsAlreadySet);
1770             pw.print(prefix); pw.print("isParent=");
1771                     pw.println(isParent);
1772             if (parentAdmin != null) {
1773                 pw.print(prefix);  pw.println("parentAdmin:");
1774                 parentAdmin.dump(prefix + "  ", pw);
1775             }
1776             if (mCrossProfileCalendarPackages != null) {
1777                 pw.print(prefix); pw.print("mCrossProfileCalendarPackages=");
1778                 pw.println(mCrossProfileCalendarPackages);
1779             }
1780         }
1781     }
1782 
handlePackagesChanged(@ullable String packageName, int userHandle)1783     private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1784         boolean removedAdmin = false;
1785         if (VERBOSE_LOG) {
1786             Slog.d(LOG_TAG, "Handling package changes package " + packageName
1787                     + " for user " + userHandle);
1788         }
1789         DevicePolicyData policy = getUserData(userHandle);
1790         synchronized (getLockObject()) {
1791             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1792                 ActiveAdmin aa = policy.mAdminList.get(i);
1793                 try {
1794                     // If we're checking all packages or if the specific one we're checking matches,
1795                     // then check if the package and receiver still exist.
1796                     final String adminPackage = aa.info.getPackageName();
1797                     if (packageName == null || packageName.equals(adminPackage)) {
1798                         if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1799                                 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1800                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
1801                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1802                                 userHandle) == null) {
1803                             removedAdmin = true;
1804                             policy.mAdminList.remove(i);
1805                             policy.mAdminMap.remove(aa.info.getComponent());
1806                             pushActiveAdminPackagesLocked(userHandle);
1807                             pushMeteredDisabledPackagesLocked(userHandle);
1808                         }
1809                     }
1810                 } catch (RemoteException re) {
1811                     // Shouldn't happen.
1812                 }
1813             }
1814             if (removedAdmin) {
1815                 validatePasswordOwnerLocked(policy);
1816             }
1817 
1818             boolean removedDelegate = false;
1819 
1820             // Check if a delegate was removed.
1821             for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1822                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
1823                 if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1824                     policy.mDelegationMap.removeAt(i);
1825                     removedDelegate = true;
1826                 }
1827             }
1828 
1829             // If it's an owner package, we may need to refresh the bound connection.
1830             final ComponentName owner = getOwnerComponent(userHandle);
1831             if ((packageName != null) && (owner != null)
1832                     && (owner.getPackageName().equals(packageName))) {
1833                 startOwnerService(userHandle, "package-broadcast");
1834             }
1835 
1836             // Persist updates if the removed package was an admin or delegate.
1837             if (removedAdmin || removedDelegate) {
1838                 saveSettingsLocked(policy.mUserHandle);
1839             }
1840         }
1841         if (removedAdmin) {
1842             // The removed admin might have disabled camera, so update user restrictions.
1843             pushUserRestrictions(userHandle);
1844         }
1845     }
1846 
isRemovedPackage(String changedPackage, String targetPackage, int userHandle)1847     private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1848         try {
1849             return targetPackage != null
1850                     && (changedPackage == null || changedPackage.equals(targetPackage))
1851                     && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1852         } catch (RemoteException e) {
1853             // Shouldn't happen
1854         }
1855 
1856         return false;
1857     }
1858 
1859     /**
1860      * Unit test will subclass it to inject mocks.
1861      */
1862     @VisibleForTesting
1863     static class Injector {
1864 
1865         public final Context mContext;
1866 
Injector(Context context)1867         Injector(Context context) {
1868             mContext = context;
1869         }
1870 
hasFeature()1871         public boolean hasFeature() {
1872             return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1873         }
1874 
createContextAsUser(UserHandle user)1875         Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1876             final String packageName = mContext.getPackageName();
1877             return mContext.createPackageContextAsUser(packageName, 0, user);
1878         }
1879 
getResources()1880         Resources getResources() {
1881             return mContext.getResources();
1882         }
1883 
newOwners()1884         Owners newOwners() {
1885             return new Owners(getUserManager(), getUserManagerInternal(),
1886                     getPackageManagerInternal(), getActivityTaskManagerInternal());
1887         }
1888 
getUserManager()1889         UserManager getUserManager() {
1890             return UserManager.get(mContext);
1891         }
1892 
getUserManagerInternal()1893         UserManagerInternal getUserManagerInternal() {
1894             return LocalServices.getService(UserManagerInternal.class);
1895         }
1896 
getPackageManagerInternal()1897         PackageManagerInternal getPackageManagerInternal() {
1898             return LocalServices.getService(PackageManagerInternal.class);
1899         }
1900 
getActivityTaskManagerInternal()1901         ActivityTaskManagerInternal getActivityTaskManagerInternal() {
1902             return LocalServices.getService(ActivityTaskManagerInternal.class);
1903         }
1904 
getPermissionControllerManager( @onNull UserHandle user)1905         @NonNull PermissionControllerManager getPermissionControllerManager(
1906                 @NonNull UserHandle user) {
1907             if (user.equals(mContext.getUser())) {
1908                 return mContext.getSystemService(PermissionControllerManager.class);
1909             } else {
1910                 try {
1911                     return mContext.createPackageContextAsUser(mContext.getPackageName(), 0,
1912                             user).getSystemService(PermissionControllerManager.class);
1913                 } catch (NameNotFoundException notPossible) {
1914                     // not possible
1915                     throw new IllegalStateException(notPossible);
1916                 }
1917             }
1918         }
1919 
getUsageStatsManagerInternal()1920         UsageStatsManagerInternal getUsageStatsManagerInternal() {
1921             return LocalServices.getService(UsageStatsManagerInternal.class);
1922         }
1923 
getNetworkPolicyManagerInternal()1924         NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() {
1925             return LocalServices.getService(NetworkPolicyManagerInternal.class);
1926         }
1927 
getNotificationManager()1928         NotificationManager getNotificationManager() {
1929             return mContext.getSystemService(NotificationManager.class);
1930         }
1931 
getIIpConnectivityMetrics()1932         IIpConnectivityMetrics getIIpConnectivityMetrics() {
1933             return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1934                 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1935         }
1936 
getPackageManager()1937         PackageManager getPackageManager() {
1938             return mContext.getPackageManager();
1939         }
1940 
getPowerManagerInternal()1941         PowerManagerInternal getPowerManagerInternal() {
1942             return LocalServices.getService(PowerManagerInternal.class);
1943         }
1944 
getTelephonyManager()1945         TelephonyManager getTelephonyManager() {
1946             return mContext.getSystemService(TelephonyManager.class);
1947         }
1948 
getTrustManager()1949         TrustManager getTrustManager() {
1950             return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1951         }
1952 
getAlarmManager()1953         AlarmManager getAlarmManager() {
1954             return mContext.getSystemService(AlarmManager.class);
1955         }
1956 
getConnectivityManager()1957         ConnectivityManager getConnectivityManager() {
1958             return mContext.getSystemService(ConnectivityManager.class);
1959         }
1960 
getIWindowManager()1961         IWindowManager getIWindowManager() {
1962             return IWindowManager.Stub
1963                     .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1964         }
1965 
getIActivityManager()1966         IActivityManager getIActivityManager() {
1967             return ActivityManager.getService();
1968         }
1969 
getIActivityTaskManager()1970         IActivityTaskManager getIActivityTaskManager() {
1971             return ActivityTaskManager.getService();
1972         }
1973 
getActivityManagerInternal()1974         ActivityManagerInternal getActivityManagerInternal() {
1975             return LocalServices.getService(ActivityManagerInternal.class);
1976         }
1977 
getIPackageManager()1978         IPackageManager getIPackageManager() {
1979             return AppGlobals.getPackageManager();
1980         }
1981 
getIBackupManager()1982         IBackupManager getIBackupManager() {
1983             return IBackupManager.Stub.asInterface(
1984                     ServiceManager.getService(Context.BACKUP_SERVICE));
1985         }
1986 
getIAudioService()1987         IAudioService getIAudioService() {
1988             return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1989         }
1990 
isBuildDebuggable()1991         boolean isBuildDebuggable() {
1992             return Build.IS_DEBUGGABLE;
1993         }
1994 
newLockPatternUtils()1995         LockPatternUtils newLockPatternUtils() {
1996             return new LockPatternUtils(mContext);
1997         }
1998 
storageManagerIsFileBasedEncryptionEnabled()1999         boolean storageManagerIsFileBasedEncryptionEnabled() {
2000             return StorageManager.isFileEncryptedNativeOnly();
2001         }
2002 
storageManagerIsNonDefaultBlockEncrypted()2003         boolean storageManagerIsNonDefaultBlockEncrypted() {
2004             long identity = Binder.clearCallingIdentity();
2005             try {
2006                 return StorageManager.isNonDefaultBlockEncrypted();
2007             } finally {
2008                 Binder.restoreCallingIdentity(identity);
2009             }
2010         }
2011 
storageManagerIsEncrypted()2012         boolean storageManagerIsEncrypted() {
2013             return StorageManager.isEncrypted();
2014         }
2015 
storageManagerIsEncryptable()2016         boolean storageManagerIsEncryptable() {
2017             return StorageManager.isEncryptable();
2018         }
2019 
getMyLooper()2020         Looper getMyLooper() {
2021             return Looper.myLooper();
2022         }
2023 
getWifiManager()2024         WifiManager getWifiManager() {
2025             return mContext.getSystemService(WifiManager.class);
2026         }
2027 
binderClearCallingIdentity()2028         long binderClearCallingIdentity() {
2029             return Binder.clearCallingIdentity();
2030         }
2031 
binderRestoreCallingIdentity(long token)2032         void binderRestoreCallingIdentity(long token) {
2033             Binder.restoreCallingIdentity(token);
2034         }
2035 
binderGetCallingUid()2036         int binderGetCallingUid() {
2037             return Binder.getCallingUid();
2038         }
2039 
binderGetCallingPid()2040         int binderGetCallingPid() {
2041             return Binder.getCallingPid();
2042         }
2043 
binderGetCallingUserHandle()2044         UserHandle binderGetCallingUserHandle() {
2045             return Binder.getCallingUserHandle();
2046         }
2047 
binderIsCallingUidMyUid()2048         boolean binderIsCallingUidMyUid() {
2049             return getCallingUid() == Process.myUid();
2050         }
2051 
binderWithCleanCallingIdentity(@onNull ThrowingRunnable action)2052         void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
2053              Binder.withCleanCallingIdentity(action);
2054         }
2055 
binderWithCleanCallingIdentity(@onNull ThrowingSupplier<T> action)2056         final <T> T binderWithCleanCallingIdentity(@NonNull ThrowingSupplier<T> action) {
2057             return Binder.withCleanCallingIdentity(action);
2058         }
2059 
userHandleGetCallingUserId()2060         final int userHandleGetCallingUserId() {
2061             return UserHandle.getUserId(binderGetCallingUid());
2062         }
2063 
environmentGetUserSystemDirectory(int userId)2064         File environmentGetUserSystemDirectory(int userId) {
2065             return Environment.getUserSystemDirectory(userId);
2066         }
2067 
powerManagerGoToSleep(long time, int reason, int flags)2068         void powerManagerGoToSleep(long time, int reason, int flags) {
2069             mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
2070         }
2071 
powerManagerReboot(String reason)2072         void powerManagerReboot(String reason) {
2073             mContext.getSystemService(PowerManager.class).reboot(reason);
2074         }
2075 
recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, boolean wipeEuicc)2076         void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
2077                 boolean wipeEuicc) throws IOException {
2078             RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc);
2079         }
2080 
systemPropertiesGetBoolean(String key, boolean def)2081         boolean systemPropertiesGetBoolean(String key, boolean def) {
2082             return SystemProperties.getBoolean(key, def);
2083         }
2084 
systemPropertiesGetLong(String key, long def)2085         long systemPropertiesGetLong(String key, long def) {
2086             return SystemProperties.getLong(key, def);
2087         }
2088 
systemPropertiesGet(String key, String def)2089         String systemPropertiesGet(String key, String def) {
2090             return SystemProperties.get(key, def);
2091         }
2092 
systemPropertiesGet(String key)2093         String systemPropertiesGet(String key) {
2094             return SystemProperties.get(key);
2095         }
2096 
systemPropertiesSet(String key, String value)2097         void systemPropertiesSet(String key, String value) {
2098             SystemProperties.set(key, value);
2099         }
2100 
userManagerIsSplitSystemUser()2101         boolean userManagerIsSplitSystemUser() {
2102             return UserManager.isSplitSystemUser();
2103         }
2104 
getDevicePolicyFilePathForSystemUser()2105         String getDevicePolicyFilePathForSystemUser() {
2106             return "/data/system/";
2107         }
2108 
pendingIntentGetActivityAsUser(Context context, int requestCode, @NonNull Intent intent, int flags, Bundle options, UserHandle user)2109         PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
2110                 @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
2111             return PendingIntent.getActivityAsUser(
2112                     context, requestCode, intent, flags, options, user);
2113         }
2114 
registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer, int userHandle)2115         void registerContentObserver(Uri uri, boolean notifyForDescendents,
2116                 ContentObserver observer, int userHandle) {
2117             mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
2118                     observer, userHandle);
2119         }
2120 
settingsSecureGetIntForUser(String name, int def, int userHandle)2121         int settingsSecureGetIntForUser(String name, int def, int userHandle) {
2122             return Settings.Secure.getIntForUser(mContext.getContentResolver(),
2123                     name, def, userHandle);
2124         }
2125 
settingsSecureGetStringForUser(String name, int userHandle)2126         String settingsSecureGetStringForUser(String name, int userHandle) {
2127             return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
2128                     userHandle);
2129         }
2130 
settingsSecurePutIntForUser(String name, int value, int userHandle)2131         void settingsSecurePutIntForUser(String name, int value, int userHandle) {
2132             Settings.Secure.putIntForUser(mContext.getContentResolver(),
2133                     name, value, userHandle);
2134         }
2135 
settingsSecurePutStringForUser(String name, String value, int userHandle)2136         void settingsSecurePutStringForUser(String name, String value, int userHandle) {
2137             Settings.Secure.putStringForUser(mContext.getContentResolver(),
2138                     name, value, userHandle);
2139         }
2140 
settingsGlobalPutStringForUser(String name, String value, int userHandle)2141         void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
2142             Settings.Global.putStringForUser(mContext.getContentResolver(),
2143                     name, value, userHandle);
2144         }
2145 
settingsSecurePutInt(String name, int value)2146         void settingsSecurePutInt(String name, int value) {
2147             Settings.Secure.putInt(mContext.getContentResolver(), name, value);
2148         }
2149 
settingsGlobalGetInt(String name, int def)2150         int settingsGlobalGetInt(String name, int def) {
2151             return Settings.Global.getInt(mContext.getContentResolver(), name, def);
2152         }
2153 
2154         @Nullable
settingsGlobalGetString(String name)2155         String settingsGlobalGetString(String name) {
2156             return Settings.Global.getString(mContext.getContentResolver(), name);
2157         }
2158 
settingsGlobalPutInt(String name, int value)2159         void settingsGlobalPutInt(String name, int value) {
2160             Settings.Global.putInt(mContext.getContentResolver(), name, value);
2161         }
2162 
settingsSecurePutString(String name, String value)2163         void settingsSecurePutString(String name, String value) {
2164             Settings.Secure.putString(mContext.getContentResolver(), name, value);
2165         }
2166 
settingsGlobalPutString(String name, String value)2167         void settingsGlobalPutString(String name, String value) {
2168             Settings.Global.putString(mContext.getContentResolver(), name, value);
2169         }
2170 
settingsSystemPutStringForUser(String name, String value, int userId)2171         void settingsSystemPutStringForUser(String name, String value, int userId) {
2172           Settings.System.putStringForUser(
2173               mContext.getContentResolver(), name, value, userId);
2174         }
2175 
securityLogSetLoggingEnabledProperty(boolean enabled)2176         void securityLogSetLoggingEnabledProperty(boolean enabled) {
2177             SecurityLog.setLoggingEnabledProperty(enabled);
2178         }
2179 
securityLogGetLoggingEnabledProperty()2180         boolean securityLogGetLoggingEnabledProperty() {
2181             return SecurityLog.getLoggingEnabledProperty();
2182         }
2183 
securityLogIsLoggingEnabled()2184         boolean securityLogIsLoggingEnabled() {
2185             return SecurityLog.isLoggingEnabled();
2186         }
2187 
keyChainBindAsUser(UserHandle user)2188         KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
2189             return KeyChain.bindAsUser(mContext, user);
2190         }
2191 
postOnSystemServerInitThreadPool(Runnable runnable)2192         void postOnSystemServerInitThreadPool(Runnable runnable) {
2193             SystemServerInitThreadPool.get().submit(runnable, LOG_TAG);
2194         }
2195 
newTransferOwnershipMetadataManager()2196         public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() {
2197             return new TransferOwnershipMetadataManager();
2198         }
2199 
runCryptoSelfTest()2200         public void runCryptoSelfTest() {
2201             CryptoTestHelper.runAndLogSelfTest();
2202         }
2203     }
2204 
2205     /**
2206      * Instantiates the service.
2207      */
DevicePolicyManagerService(Context context)2208     public DevicePolicyManagerService(Context context) {
2209         this(new Injector(context));
2210     }
2211 
2212     @VisibleForTesting
DevicePolicyManagerService(Injector injector)2213     DevicePolicyManagerService(Injector injector) {
2214         mInjector = injector;
2215         mContext = Preconditions.checkNotNull(injector.mContext);
2216         mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
2217 
2218         mConstantsObserver = new DevicePolicyConstantsObserver(mHandler);
2219         mConstantsObserver.register();
2220         mConstants = loadConstants();
2221 
2222         mOwners = Preconditions.checkNotNull(injector.newOwners());
2223 
2224         mUserManager = Preconditions.checkNotNull(injector.getUserManager());
2225         mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
2226         mUsageStatsManagerInternal = Preconditions.checkNotNull(
2227                 injector.getUsageStatsManagerInternal());
2228         mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
2229         mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
2230 
2231         mLocalService = new LocalService();
2232         mLockPatternUtils = injector.newLockPatternUtils();
2233 
2234         // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
2235         mSecurityLogMonitor = new SecurityLogMonitor(this);
2236 
2237         mHasFeature = mInjector.hasFeature();
2238         mIsWatch = mInjector.getPackageManager()
2239                 .hasSystemFeature(PackageManager.FEATURE_WATCH);
2240         mHasTelephonyFeature = mInjector.getPackageManager()
2241                 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
2242         mBackgroundHandler = BackgroundThread.getHandler();
2243 
2244         // Needed when mHasFeature == false, because it controls the certificate warning text.
2245         mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
2246 
2247         mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
2248 
2249         mOverlayPackagesProvider = new OverlayPackagesProvider(mContext);
2250 
2251         mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager();
2252 
2253         if (!mHasFeature) {
2254             // Skip the rest of the initialization
2255             mSetupContentObserver = null;
2256             return;
2257         }
2258 
2259         IntentFilter filter = new IntentFilter();
2260         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
2261         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
2262         filter.addAction(Intent.ACTION_USER_ADDED);
2263         filter.addAction(Intent.ACTION_USER_REMOVED);
2264         filter.addAction(Intent.ACTION_USER_STARTED);
2265         filter.addAction(Intent.ACTION_USER_STOPPED);
2266         filter.addAction(Intent.ACTION_USER_SWITCHED);
2267         filter.addAction(Intent.ACTION_USER_UNLOCKED);
2268         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2269         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2270         filter = new IntentFilter();
2271         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
2272         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2273         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
2274         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
2275         filter.addDataScheme("package");
2276         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2277         filter = new IntentFilter();
2278         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
2279         filter.addAction(Intent.ACTION_TIME_CHANGED);
2280         filter.addAction(Intent.ACTION_DATE_CHANGED);
2281         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2282 
2283         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
2284 
2285         mSetupContentObserver = new SetupContentObserver(mHandler);
2286 
2287         mUserManagerInternal.addUserRestrictionsListener(new RestrictionsListener(mContext));
2288     }
2289 
2290     /**
2291      * Creates and loads the policy data from xml.
2292      * @param userHandle the user for whom to load the policy data
2293      * @return
2294      */
2295     @NonNull
getUserData(int userHandle)2296     DevicePolicyData getUserData(int userHandle) {
2297         synchronized (getLockObject()) {
2298             DevicePolicyData policy = mUserData.get(userHandle);
2299             if (policy == null) {
2300                 policy = new DevicePolicyData(userHandle);
2301                 mUserData.append(userHandle, policy);
2302                 loadSettingsLocked(policy, userHandle);
2303             }
2304             return policy;
2305         }
2306     }
2307 
2308     /**
2309      * Provides PasswordMetrics object corresponding to the given user.
2310      * @param userHandle the user for whom to provide metrics.
2311      * @return the user password metrics, or {@code null} if none have been associated with
2312      * the user yet (for example, if the device has booted but not been unlocked).
2313      */
2314     @GuardedBy("getLockObject()")
getUserPasswordMetricsLocked(int userHandle)2315     PasswordMetrics getUserPasswordMetricsLocked(int userHandle) {
2316         return mUserPasswordMetrics.get(userHandle);
2317     }
2318 
2319     /**
2320      * Creates and loads the policy data from xml for data that is shared between
2321      * various profiles of a user. In contrast to {@link #getUserData(int)}
2322      * it allows access to data of users other than the calling user.
2323      *
2324      * This function should only be used for shared data, e.g. everything regarding
2325      * passwords and should be removed once multiple screen locks are present.
2326      * @param userHandle the user for whom to load the policy data
2327      * @return
2328      */
getUserDataUnchecked(int userHandle)2329     DevicePolicyData getUserDataUnchecked(int userHandle) {
2330         long ident = mInjector.binderClearCallingIdentity();
2331         try {
2332             return getUserData(userHandle);
2333         } finally {
2334             mInjector.binderRestoreCallingIdentity(ident);
2335         }
2336     }
2337 
removeUserData(int userHandle)2338     void removeUserData(int userHandle) {
2339         synchronized (getLockObject()) {
2340             if (userHandle == UserHandle.USER_SYSTEM) {
2341                 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
2342                 return;
2343             }
2344             updatePasswordQualityCacheForUserGroup(userHandle);
2345             mPolicyCache.onUserRemoved(userHandle);
2346             mOwners.removeProfileOwner(userHandle);
2347             mOwners.writeProfileOwner(userHandle);
2348 
2349             DevicePolicyData policy = mUserData.get(userHandle);
2350             if (policy != null) {
2351                 mUserData.remove(userHandle);
2352             }
2353             if (mUserPasswordMetrics.get(userHandle) != null) {
2354                 mUserPasswordMetrics.remove(userHandle);
2355             }
2356 
2357             File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2358                     DEVICE_POLICIES_XML);
2359             policyFile.delete();
2360             Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
2361         }
2362     }
2363 
loadOwners()2364     void loadOwners() {
2365         synchronized (getLockObject()) {
2366             mOwners.load();
2367             setDeviceOwnerSystemPropertyLocked();
2368             findOwnerComponentIfNecessaryLocked();
2369             migrateUserRestrictionsIfNecessaryLocked();
2370             maybeSetDefaultDeviceOwnerUserRestrictionsLocked();
2371 
2372             // TODO PO may not have a class name either due to b/17652534.  Address that too.
2373 
2374             updateDeviceOwnerLocked();
2375         }
2376     }
2377 
2378     /** Apply default restrictions that haven't been applied to device owners yet. */
maybeSetDefaultDeviceOwnerUserRestrictionsLocked()2379     private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() {
2380         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2381         if (deviceOwner != null) {
2382             maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(),
2383                     deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner());
2384         }
2385     }
2386 
2387     /** Apply default restrictions that haven't been applied to profile owners yet. */
maybeSetDefaultProfileOwnerUserRestrictions()2388     private void maybeSetDefaultProfileOwnerUserRestrictions() {
2389         synchronized (getLockObject()) {
2390             for (final int userId : mOwners.getProfileOwnerKeys()) {
2391                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
2392                 // The following restrictions used to be applied to managed profiles by different
2393                 // means (via Settings or by disabling components). Now they are proper user
2394                 // restrictions so we apply them to managed profile owners. Non-managed secondary
2395                 // users didn't have those restrictions so we skip them to keep existing behavior.
2396                 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
2397                     continue;
2398                 }
2399                 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner,
2400                         UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
2401                 ensureUnknownSourcesRestrictionForProfileOwnerLocked(
2402                         userId, profileOwner, false /* newOwner */);
2403             }
2404         }
2405     }
2406 
2407     /**
2408      * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
2409      * set of restrictions for this profile owner.
2410      */
ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, ActiveAdmin profileOwner, boolean newOwner)2411     private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
2412             ActiveAdmin profileOwner, boolean newOwner) {
2413         if (newOwner || mInjector.settingsSecureGetIntForUser(
2414                 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
2415             profileOwner.ensureUserRestrictions().putBoolean(
2416                     UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
2417             saveUserRestrictionsLocked(userId);
2418             mInjector.settingsSecurePutIntForUser(
2419                     Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
2420         }
2421     }
2422 
2423     /**
2424      * Apply default restrictions that haven't been applied to a given admin yet.
2425      */
maybeSetDefaultRestrictionsForAdminLocked( int userId, ActiveAdmin admin, Set<String> defaultRestrictions)2426     private void maybeSetDefaultRestrictionsForAdminLocked(
2427             int userId, ActiveAdmin admin, Set<String> defaultRestrictions) {
2428         if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
2429             return; // The same set of default restrictions has been already applied.
2430         }
2431         Slog.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
2432 
2433         if (VERBOSE_LOG) {
2434             Slog.d(LOG_TAG,"Default enabled restrictions: "
2435                     + defaultRestrictions
2436                     + ". Restrictions already enabled: "
2437                     + admin.defaultEnabledRestrictionsAlreadySet);
2438         }
2439 
2440         final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
2441         restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
2442         if (!restrictionsToSet.isEmpty()) {
2443             for (final String restriction : restrictionsToSet) {
2444                 admin.ensureUserRestrictions().putBoolean(restriction, true);
2445             }
2446             admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
2447             Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
2448             saveUserRestrictionsLocked(userId);
2449         }
2450     }
2451 
setDeviceOwnerSystemPropertyLocked()2452     private void setDeviceOwnerSystemPropertyLocked() {
2453         final boolean deviceProvisioned =
2454                 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2455         final boolean hasDeviceOwner = mOwners.hasDeviceOwner();
2456         // If the device is not provisioned and there is currently no device owner, do not set the
2457         // read-only system property yet, since Device owner may still be provisioned.
2458         if (!hasDeviceOwner && !deviceProvisioned) {
2459             return;
2460         }
2461         // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
2462         // always false at this point.
2463         if (StorageManager.inCryptKeeperBounce()) {
2464             return;
2465         }
2466 
2467         if (!mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT, "").isEmpty()) {
2468             Slog.w(LOG_TAG, "Trying to set ro.organization_owned, but it has already been set?");
2469         } else {
2470             final String value = Boolean.toString(hasDeviceOwner);
2471             mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, value);
2472             Slog.i(LOG_TAG, "Set ro.organization_owned property to " + value);
2473         }
2474     }
2475 
maybeStartSecurityLogMonitorOnActivityManagerReady()2476     private void maybeStartSecurityLogMonitorOnActivityManagerReady() {
2477         synchronized (getLockObject()) {
2478             if (mInjector.securityLogIsLoggingEnabled()) {
2479                 mSecurityLogMonitor.start();
2480                 mInjector.runCryptoSelfTest();
2481                 maybePauseDeviceWideLoggingLocked();
2482             }
2483         }
2484     }
2485 
findOwnerComponentIfNecessaryLocked()2486     private void findOwnerComponentIfNecessaryLocked() {
2487         if (!mOwners.hasDeviceOwner()) {
2488             return;
2489         }
2490         final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
2491 
2492         if (!TextUtils.isEmpty(doComponentName.getClassName())) {
2493             return; // Already a full component name.
2494         }
2495 
2496         final ComponentName doComponent = findAdminComponentWithPackageLocked(
2497                 doComponentName.getPackageName(),
2498                 mOwners.getDeviceOwnerUserId());
2499         if (doComponent == null) {
2500             Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
2501         } else {
2502             mOwners.setDeviceOwnerWithRestrictionsMigrated(
2503                     doComponent,
2504                     mOwners.getDeviceOwnerName(),
2505                     mOwners.getDeviceOwnerUserId(),
2506                     !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
2507             mOwners.writeDeviceOwner();
2508             if (VERBOSE_LOG) {
2509                 Log.v(LOG_TAG, "Device owner component filled in");
2510             }
2511         }
2512     }
2513 
2514     /**
2515      * We didn't use to persist user restrictions for each owners but only persisted in user
2516      * manager.
2517      */
migrateUserRestrictionsIfNecessaryLocked()2518     private void migrateUserRestrictionsIfNecessaryLocked() {
2519         boolean migrated = false;
2520         // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
2521         // except for the "system controlled" ones.
2522         if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
2523             if (VERBOSE_LOG) {
2524                 Log.v(LOG_TAG, "Migrating DO user restrictions");
2525             }
2526             migrated = true;
2527 
2528             // Migrate user 0 restrictions to DO.
2529             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
2530 
2531             migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
2532                     /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
2533 
2534             // Push DO user restrictions to user manager.
2535             pushUserRestrictions(UserHandle.USER_SYSTEM);
2536 
2537             mOwners.setDeviceOwnerUserRestrictionsMigrated();
2538         }
2539 
2540         // Migrate for POs.
2541 
2542         // The following restrictions can be set on secondary users by the device owner, so we
2543         // assume they're not from the PO.
2544         final Set<String> secondaryUserExceptionList = Sets.newArraySet(
2545                 UserManager.DISALLOW_OUTGOING_CALLS,
2546                 UserManager.DISALLOW_SMS);
2547 
2548         for (UserInfo ui : mUserManager.getUsers()) {
2549             final int userId = ui.id;
2550             if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
2551                 if (VERBOSE_LOG) {
2552                     Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
2553                 }
2554                 migrated = true;
2555 
2556                 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
2557 
2558                 final Set<String> exceptionList =
2559                         (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
2560 
2561                 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
2562                         exceptionList, /* isDeviceOwner =*/ false);
2563 
2564                 // Note if a secondary user has no PO but has a DA that disables camera, we
2565                 // don't get here and won't push the camera user restriction to UserManager
2566                 // here.  That's okay because we'll push user restrictions anyway when a user
2567                 // starts.  But we still do it because we want to let user manager persist
2568                 // upon migration.
2569                 pushUserRestrictions(userId);
2570 
2571                 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
2572             }
2573         }
2574         if (VERBOSE_LOG && migrated) {
2575             Log.v(LOG_TAG, "User restrictions migrated.");
2576         }
2577     }
2578 
migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, Set<String> exceptionList, boolean isDeviceOwner)2579     private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
2580             Set<String> exceptionList, boolean isDeviceOwner) {
2581         final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
2582                 user.getIdentifier());
2583 
2584         final Bundle newBaseRestrictions = new Bundle();
2585         final Bundle newOwnerRestrictions = new Bundle();
2586 
2587         for (String key : origRestrictions.keySet()) {
2588             if (!origRestrictions.getBoolean(key)) {
2589                 continue;
2590             }
2591             final boolean canOwnerChange = isDeviceOwner
2592                     ? UserRestrictionsUtils.canDeviceOwnerChange(key)
2593                     : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
2594 
2595             if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
2596                 newBaseRestrictions.putBoolean(key, true);
2597             } else {
2598                 newOwnerRestrictions.putBoolean(key, true);
2599             }
2600         }
2601 
2602         if (VERBOSE_LOG) {
2603             Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
2604             Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
2605             Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
2606         }
2607         mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
2608                 newBaseRestrictions);
2609 
2610         if (admin != null) {
2611             admin.ensureUserRestrictions().clear();
2612             admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
2613         } else {
2614             Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
2615         }
2616         saveSettingsLocked(user.getIdentifier());
2617     }
2618 
findAdminComponentWithPackageLocked(String packageName, int userId)2619     private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
2620         final DevicePolicyData policy = getUserData(userId);
2621         final int n = policy.mAdminList.size();
2622         ComponentName found = null;
2623         int nFound = 0;
2624         for (int i = 0; i < n; i++) {
2625             final ActiveAdmin admin = policy.mAdminList.get(i);
2626             if (packageName.equals(admin.info.getPackageName())) {
2627                 // Found!
2628                 if (nFound == 0) {
2629                     found = admin.info.getComponent();
2630                 }
2631                 nFound++;
2632             }
2633         }
2634         if (nFound > 1) {
2635             Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
2636         }
2637         return found;
2638     }
2639 
2640     /**
2641      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2642      * reminders.  Clears alarm if no expirations are configured.
2643      */
setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent)2644     private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2645         final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2646         final long now = System.currentTimeMillis();
2647         final long timeToExpire = expiration - now;
2648         final long alarmTime;
2649         if (expiration == 0) {
2650             // No expirations are currently configured:  Cancel alarm.
2651             alarmTime = 0;
2652         } else if (timeToExpire <= 0) {
2653             // The password has already expired:  Repeat every 24 hours.
2654             alarmTime = now + MS_PER_DAY;
2655         } else {
2656             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2657             // the expiration time.
2658             long alarmInterval = timeToExpire % MS_PER_DAY;
2659             if (alarmInterval == 0) {
2660                 alarmInterval = MS_PER_DAY;
2661             }
2662             alarmTime = now + alarmInterval;
2663         }
2664 
2665         long token = mInjector.binderClearCallingIdentity();
2666         try {
2667             int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2668             AlarmManager am = mInjector.getAlarmManager();
2669             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2670                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2671                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2672                     UserHandle.of(affectedUserHandle));
2673             am.cancel(pi);
2674             if (alarmTime != 0) {
2675                 am.set(AlarmManager.RTC, alarmTime, pi);
2676             }
2677         } finally {
2678             mInjector.binderRestoreCallingIdentity(token);
2679         }
2680     }
2681 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle)2682     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2683         ensureLocked();
2684         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2685         if (admin != null
2686                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2687                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2688             return admin;
2689         }
2690         return null;
2691     }
2692 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent)2693     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2694         ensureLocked();
2695         if (parent) {
2696             enforceManagedProfile(userHandle, "call APIs on the parent profile");
2697         }
2698         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2699         if (admin != null && parent) {
2700             admin = admin.getParentActiveAdmin();
2701         }
2702         return admin;
2703     }
2704 
getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)2705     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2706             throws SecurityException {
2707         return getActiveAdminOrCheckPermissionForCallerLocked(who,
2708                 reqPolicy, /* permission= */ null);
2709     }
2710 
2711     /**
2712      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2713      *
2714      * @return an active admin or {@code null} if there is no active admin but
2715      * {@code permission} is granted
2716      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2717      */
2718     @Nullable
getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, @Nullable String permission)2719     ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
2720             ComponentName who,
2721             int reqPolicy,
2722             @Nullable String permission) throws SecurityException {
2723         ensureLocked();
2724         final int callingUid = mInjector.binderGetCallingUid();
2725 
2726         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2727         if (result != null) {
2728             return result;
2729         } else if (permission != null
2730                 && (mContext.checkCallingPermission(permission)
2731                         == PackageManager.PERMISSION_GRANTED)) {
2732             return null;
2733         }
2734 
2735         if (who != null) {
2736             final int userId = UserHandle.getUserId(callingUid);
2737             final DevicePolicyData policy = getUserData(userId);
2738             ActiveAdmin admin = policy.mAdminMap.get(who);
2739             final boolean isDeviceOwner = isDeviceOwner(admin.info.getComponent(), userId);
2740             final boolean isProfileOwner = isProfileOwner(admin.info.getComponent(), userId);
2741 
2742             if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2743                 throw new SecurityException("Admin " + admin.info.getComponent()
2744                         + " does not own the device");
2745             }
2746             if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2747                 throw new SecurityException("Admin " + admin.info.getComponent()
2748                         + " does not own the profile");
2749             }
2750             if (DA_DISALLOWED_POLICIES.contains(reqPolicy) && !isDeviceOwner && !isProfileOwner) {
2751                 throw new SecurityException("Admin " + admin.info.getComponent()
2752                         + " is not a device owner or profile owner, so may not use policy: "
2753                         + admin.info.getTagForPolicy(reqPolicy));
2754             }
2755             throw new SecurityException("Admin " + admin.info.getComponent()
2756                     + " did not specify uses-policy for: "
2757                     + admin.info.getTagForPolicy(reqPolicy));
2758         } else {
2759             throw new SecurityException("No active admin owned by uid "
2760                     + callingUid + " for policy #" + reqPolicy);
2761         }
2762     }
2763 
getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)2764     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2765             throws SecurityException {
2766         return getActiveAdminOrCheckPermissionForCallerLocked(
2767                 who, reqPolicy, parent, /* permission= */ null);
2768     }
2769 
2770     /**
2771      * Finds an active admin for the caller then checks {@code permission} if admin check failed.
2772      *
2773      * @return an active admin or {@code null} if there is no active admin but
2774      * {@code permission} is granted
2775      * @throws SecurityException if caller neither has an active admin nor {@code permission}
2776      */
2777     @Nullable
getActiveAdminOrCheckPermissionForCallerLocked( ComponentName who, int reqPolicy, boolean parent, @Nullable String permission)2778     ActiveAdmin getActiveAdminOrCheckPermissionForCallerLocked(
2779             ComponentName who,
2780             int reqPolicy,
2781             boolean parent,
2782             @Nullable String permission) throws SecurityException {
2783         ensureLocked();
2784         if (parent) {
2785             enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2786                     "call APIs on the parent profile");
2787         }
2788         ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked(
2789                 who, reqPolicy, permission);
2790         return parent ? admin.getParentActiveAdmin() : admin;
2791     }
2792 
2793     /**
2794      * Find the admin for the component and userId bit of the uid, then check
2795      * the admin's uid matches the uid.
2796      */
getActiveAdminForUidLocked(ComponentName who, int uid)2797     private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2798         ensureLocked();
2799         final int userId = UserHandle.getUserId(uid);
2800         final DevicePolicyData policy = getUserData(userId);
2801         ActiveAdmin admin = policy.mAdminMap.get(who);
2802         if (admin == null) {
2803             throw new SecurityException("No active admin " + who + " for UID " + uid);
2804         }
2805         if (admin.getUid() != uid) {
2806             throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2807         }
2808         return admin;
2809     }
2810 
2811     /**
2812      * Returns the active admin for the user of the caller as denoted by uid, which implements
2813      * the {@code reqPolicy}.
2814      *
2815      * The {@code who} parameter is used as a hint:
2816      * If provided, it must be the component name of the active admin for that user and the caller
2817      * uid must match the uid of the admin.
2818      * If not provided, iterate over all of the active admins in the DevicePolicyData for that user
2819      * and return the one with the uid specified as parameter, and has the policy specified.
2820      */
getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, int uid)2821     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2822             int uid) {
2823         ensureLocked();
2824         // Try to find an admin which can use reqPolicy
2825         final int userId = UserHandle.getUserId(uid);
2826         final DevicePolicyData policy = getUserData(userId);
2827         if (who != null) {
2828             ActiveAdmin admin = policy.mAdminMap.get(who);
2829             if (admin == null) {
2830                 throw new SecurityException("No active admin " + who);
2831             }
2832             if (admin.getUid() != uid) {
2833                 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2834             }
2835             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2836                 return admin;
2837             }
2838         } else {
2839             for (ActiveAdmin admin : policy.mAdminList) {
2840                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2841                         userId)) {
2842                     return admin;
2843                 }
2844             }
2845         }
2846 
2847         return null;
2848     }
2849 
2850     @VisibleForTesting
isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, int userId)2851     boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2852             int userId) {
2853         ensureLocked();
2854         final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2855         final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2856 
2857         if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2858             return ownsDevice;
2859         } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2860             // DO always has the PO power.
2861             return ownsDevice || ownsProfile;
2862         } else {
2863             boolean allowedToUsePolicy = ownsDevice || ownsProfile
2864                     || !DA_DISALLOWED_POLICIES.contains(reqPolicy)
2865                     || getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.Q;
2866             return allowedToUsePolicy && admin.info.usesPolicy(reqPolicy);
2867         }
2868     }
2869 
2870     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2871         sendAdminCommandLocked(admin, action, null);
2872     }
2873 
2874     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2875         sendAdminCommandLocked(admin, action, null, result);
2876     }
2877 
2878     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2879             BroadcastReceiver result) {
2880         sendAdminCommandLocked(admin, action, adminExtras, result, false);
2881     }
2882 
2883     /**
2884      * Send an update to one specific admin, get notified when that admin returns a result.
2885      *
2886      * @return whether the broadcast was successfully sent
2887      */
2888     boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2889             BroadcastReceiver result, boolean inForeground) {
2890         Intent intent = new Intent(action);
2891         intent.setComponent(admin.info.getComponent());
2892         if (UserManager.isDeviceInDemoMode(mContext)) {
2893             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2894         }
2895         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2896             intent.putExtra("expiration", admin.passwordExpirationDate);
2897         }
2898         if (inForeground) {
2899             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2900         }
2901         if (adminExtras != null) {
2902             intent.putExtras(adminExtras);
2903         }
2904         if (mInjector.getPackageManager().queryBroadcastReceiversAsUser(
2905                 intent,
2906                 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2907                 admin.getUserHandle()).isEmpty()) {
2908             return false;
2909         }
2910 
2911         final BroadcastOptions options = BroadcastOptions.makeBasic();
2912         options.setBackgroundActivityStartsAllowed(true);
2913 
2914         if (result != null) {
2915             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2916                     null, AppOpsManager.OP_NONE, options.toBundle(),
2917                     result, mHandler, Activity.RESULT_OK, null, null);
2918         } else {
2919             mContext.sendBroadcastAsUser(intent, admin.getUserHandle(), null, options.toBundle());
2920         }
2921 
2922         return true;
2923     }
2924 
2925     /**
2926      * Send an update to all admins of a user that enforce a specified policy.
2927      */
2928     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
2929         final DevicePolicyData policy = getUserData(userHandle);
2930         final int count = policy.mAdminList.size();
2931         for (int i = 0; i < count; i++) {
2932             final ActiveAdmin admin = policy.mAdminList.get(i);
2933             if (admin.info.usesPolicy(reqPolicy)) {
2934                 sendAdminCommandLocked(admin, action, adminExtras, null);
2935             }
2936         }
2937     }
2938 
2939     /**
2940      * Send an update intent to all admins of a user and its profiles. Only send to admins that
2941      * enforce a specified policy.
2942      */
2943     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2944             int userHandle, Bundle adminExtras) {
2945         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2946         for (int profileId : profileIds) {
2947             sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
2948         }
2949     }
2950 
2951     /**
2952      * Sends a broadcast to each profile that share the password unlock with the given user id.
2953      */
2954     private void sendAdminCommandForLockscreenPoliciesLocked(
2955             String action, int reqPolicy, int userHandle) {
2956         final Bundle extras = new Bundle();
2957         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2958         if (isSeparateProfileChallengeEnabled(userHandle)) {
2959             sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
2960         } else {
2961             sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
2962         }
2963     }
2964 
2965     void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2966         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2967         DevicePolicyData policy = getUserData(userHandle);
2968         if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2969             policy.mRemovingAdmins.add(adminReceiver);
2970             sendAdminCommandLocked(admin,
2971                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2972                     new BroadcastReceiver() {
2973                         @Override
2974                         public void onReceive(Context context, Intent intent) {
2975                             removeAdminArtifacts(adminReceiver, userHandle);
2976                             removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2977                         }
2978                     });
2979         }
2980     }
2981 
2982 
2983     public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2984             boolean throwForMissingPermission) {
2985         if (!mHasFeature) {
2986             return null;
2987         }
2988         enforceFullCrossUsersPermission(userHandle);
2989         ActivityInfo ai = null;
2990         try {
2991             ai = mIPackageManager.getReceiverInfo(adminName,
2992                     PackageManager.GET_META_DATA |
2993                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2994                     PackageManager.MATCH_DIRECT_BOOT_AWARE |
2995                     PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2996         } catch (RemoteException e) {
2997             // shouldn't happen.
2998         }
2999         if (ai == null) {
3000             throw new IllegalArgumentException("Unknown admin: " + adminName);
3001         }
3002 
3003         if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
3004             final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
3005                     + permission.BIND_DEVICE_ADMIN;
3006             Slog.w(LOG_TAG, message);
3007             if (throwForMissingPermission &&
3008                     ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
3009                 throw new IllegalArgumentException(message);
3010             }
3011         }
3012 
3013         try {
3014             return new DeviceAdminInfo(mContext, ai);
3015         } catch (XmlPullParserException | IOException e) {
3016             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
3017                     e);
3018             return null;
3019         }
3020     }
3021 
3022     private File getPolicyFileDirectory(@UserIdInt int userId) {
3023         return userId == UserHandle.USER_SYSTEM
3024                 ? new File(mInjector.getDevicePolicyFilePathForSystemUser())
3025                 : mInjector.environmentGetUserSystemDirectory(userId);
3026     }
3027 
3028     private JournaledFile makeJournaledFile(@UserIdInt int userId) {
3029         final String base = new File(getPolicyFileDirectory(userId), DEVICE_POLICIES_XML)
3030                 .getAbsolutePath();
3031         if (VERBOSE_LOG) {
3032             Log.v(LOG_TAG, "Opening " + base);
3033         }
3034         return new JournaledFile(new File(base), new File(base + ".tmp"));
3035     }
3036 
3037     private void saveSettingsLocked(int userHandle) {
3038         DevicePolicyData policy = getUserData(userHandle);
3039         JournaledFile journal = makeJournaledFile(userHandle);
3040         FileOutputStream stream = null;
3041         try {
3042             stream = new FileOutputStream(journal.chooseForWrite(), false);
3043             XmlSerializer out = new FastXmlSerializer();
3044             out.setOutput(stream, StandardCharsets.UTF_8.name());
3045             out.startDocument(null, true);
3046 
3047             out.startTag(null, "policies");
3048             if (policy.mRestrictionsProvider != null) {
3049                 out.attribute(null, ATTR_PERMISSION_PROVIDER,
3050                         policy.mRestrictionsProvider.flattenToString());
3051             }
3052             if (policy.mUserSetupComplete) {
3053                 out.attribute(null, ATTR_SETUP_COMPLETE,
3054                         Boolean.toString(true));
3055             }
3056             if (policy.mPaired) {
3057                 out.attribute(null, ATTR_DEVICE_PAIRED,
3058                         Boolean.toString(true));
3059             }
3060             if (policy.mDeviceProvisioningConfigApplied) {
3061                 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
3062                         Boolean.toString(true));
3063             }
3064             if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
3065                 out.attribute(null, ATTR_PROVISIONING_STATE,
3066                         Integer.toString(policy.mUserProvisioningState));
3067             }
3068             if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
3069                 out.attribute(null, ATTR_PERMISSION_POLICY,
3070                         Integer.toString(policy.mPermissionPolicy));
3071             }
3072 
3073             // Serialize delegations.
3074             for (int i = 0; i < policy.mDelegationMap.size(); ++i) {
3075                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
3076                 final List<String> scopes = policy.mDelegationMap.valueAt(i);
3077 
3078                 // Every "delegation" tag serializes the information of one delegate-scope pair.
3079                 for (String scope : scopes) {
3080                     out.startTag(null, "delegation");
3081                     out.attribute(null, "delegatePackage", delegatePackage);
3082                     out.attribute(null, "scope", scope);
3083                     out.endTag(null, "delegation");
3084                 }
3085             }
3086 
3087             final int N = policy.mAdminList.size();
3088             for (int i=0; i<N; i++) {
3089                 ActiveAdmin ap = policy.mAdminList.get(i);
3090                 if (ap != null) {
3091                     out.startTag(null, "admin");
3092                     out.attribute(null, "name", ap.info.getComponent().flattenToString());
3093                     ap.writeToXml(out);
3094                     out.endTag(null, "admin");
3095                 }
3096             }
3097 
3098             if (policy.mPasswordOwner >= 0) {
3099                 out.startTag(null, "password-owner");
3100                 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
3101                 out.endTag(null, "password-owner");
3102             }
3103 
3104             if (policy.mFailedPasswordAttempts != 0) {
3105                 out.startTag(null, "failed-password-attempts");
3106                 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
3107                 out.endTag(null, "failed-password-attempts");
3108             }
3109 
3110             // For FDE devices only, we save this flag so we can report on password sufficiency
3111             // before the user enters their password for the first time after a reboot.  For
3112             // security reasons, we don't want to store the full set of active password metrics.
3113             if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
3114                 out.startTag(null, TAG_PASSWORD_VALIDITY);
3115                 out.attribute(null, ATTR_VALUE,
3116                         Boolean.toString(policy.mPasswordValidAtLastCheckpoint));
3117                 out.endTag(null, TAG_PASSWORD_VALIDITY);
3118             }
3119 
3120             for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
3121                 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
3122                 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
3123                 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
3124             }
3125 
3126             for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
3127                 String component = policy.mLockTaskPackages.get(i);
3128                 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
3129                 out.attribute(null, "name", component);
3130                 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
3131             }
3132 
3133             if (policy.mLockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
3134                 out.startTag(null, TAG_LOCK_TASK_FEATURES);
3135                 out.attribute(null, ATTR_VALUE, Integer.toString(policy.mLockTaskFeatures));
3136                 out.endTag(null, TAG_LOCK_TASK_FEATURES);
3137             }
3138 
3139             if (policy.mStatusBarDisabled) {
3140                 out.startTag(null, TAG_STATUS_BAR);
3141                 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
3142                 out.endTag(null, TAG_STATUS_BAR);
3143             }
3144 
3145             if (policy.doNotAskCredentialsOnBoot) {
3146                 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
3147                 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
3148             }
3149 
3150             for (String id : policy.mAffiliationIds) {
3151                 out.startTag(null, TAG_AFFILIATION_ID);
3152                 out.attribute(null, ATTR_ID, id);
3153                 out.endTag(null, TAG_AFFILIATION_ID);
3154             }
3155 
3156             if (policy.mLastSecurityLogRetrievalTime >= 0) {
3157                 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
3158                 out.attribute(null, ATTR_VALUE,
3159                         Long.toString(policy.mLastSecurityLogRetrievalTime));
3160                 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
3161             }
3162 
3163             if (policy.mLastBugReportRequestTime >= 0) {
3164                 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST);
3165                 out.attribute(null, ATTR_VALUE,
3166                         Long.toString(policy.mLastBugReportRequestTime));
3167                 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST);
3168             }
3169 
3170             if (policy.mLastNetworkLogsRetrievalTime >= 0) {
3171                 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
3172                 out.attribute(null, ATTR_VALUE,
3173                         Long.toString(policy.mLastNetworkLogsRetrievalTime));
3174                 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
3175             }
3176 
3177             if (policy.mAdminBroadcastPending) {
3178                 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
3179                 out.attribute(null, ATTR_VALUE,
3180                         Boolean.toString(policy.mAdminBroadcastPending));
3181                 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
3182             }
3183 
3184             if (policy.mInitBundle != null) {
3185                 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
3186                 policy.mInitBundle.saveToXml(out);
3187                 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
3188             }
3189 
3190             if (policy.mPasswordTokenHandle != 0) {
3191                 out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE);
3192                 out.attribute(null, ATTR_VALUE,
3193                         Long.toString(policy.mPasswordTokenHandle));
3194                 out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE);
3195             }
3196 
3197             if (policy.mCurrentInputMethodSet) {
3198                 out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET);
3199                 out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET);
3200             }
3201 
3202             for (final String cert : policy.mOwnerInstalledCaCerts) {
3203                 out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT);
3204                 out.attribute(null, ATTR_ALIAS, cert);
3205                 out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT);
3206             }
3207 
3208             out.endTag(null, "policies");
3209 
3210             out.endDocument();
3211             stream.flush();
3212             FileUtils.sync(stream);
3213             stream.close();
3214             journal.commit();
3215             sendChangedNotification(userHandle);
3216         } catch (XmlPullParserException | IOException e) {
3217             Slog.w(LOG_TAG, "failed writing file", e);
3218             try {
3219                 if (stream != null) {
3220                     stream.close();
3221                 }
3222             } catch (IOException ex) {
3223                 // Ignore
3224             }
3225             journal.rollback();
3226         }
3227     }
3228 
3229     private void sendChangedNotification(int userHandle) {
3230         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
3231         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3232         long ident = mInjector.binderClearCallingIdentity();
3233         try {
3234             mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
3235         } finally {
3236             mInjector.binderRestoreCallingIdentity(ident);
3237         }
3238     }
3239 
3240     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
3241         JournaledFile journal = makeJournaledFile(userHandle);
3242         FileInputStream stream = null;
3243         File file = journal.chooseForRead();
3244         boolean needsRewrite = false;
3245         try {
3246             stream = new FileInputStream(file);
3247             XmlPullParser parser = Xml.newPullParser();
3248             parser.setInput(stream, StandardCharsets.UTF_8.name());
3249 
3250             int type;
3251             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
3252                     && type != XmlPullParser.START_TAG) {
3253             }
3254             String tag = parser.getName();
3255             if (!"policies".equals(tag)) {
3256                 throw new XmlPullParserException(
3257                         "Settings do not start with policies tag: found " + tag);
3258             }
3259 
3260             // Extract the permission provider component name if available
3261             String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
3262             if (permissionProvider != null) {
3263                 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
3264             }
3265             String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
3266             if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
3267                 policy.mUserSetupComplete = true;
3268             }
3269             String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
3270             if (paired != null && Boolean.toString(true).equals(paired)) {
3271                 policy.mPaired = true;
3272             }
3273             String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
3274                     ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
3275             if (deviceProvisioningConfigApplied != null
3276                     && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
3277                 policy.mDeviceProvisioningConfigApplied = true;
3278             }
3279             String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
3280             if (!TextUtils.isEmpty(provisioningState)) {
3281                 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
3282             }
3283             String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
3284             if (!TextUtils.isEmpty(permissionPolicy)) {
3285                 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
3286             }
3287             // Check for delegation compatibility with pre-O.
3288             // TODO(edmanp) remove in P.
3289             {
3290                 final String certDelegate = parser.getAttributeValue(null,
3291                         ATTR_DELEGATED_CERT_INSTALLER);
3292                 if (certDelegate != null) {
3293                     List<String> scopes = policy.mDelegationMap.get(certDelegate);
3294                     if (scopes == null) {
3295                         scopes = new ArrayList<>();
3296                         policy.mDelegationMap.put(certDelegate, scopes);
3297                     }
3298                     if (!scopes.contains(DELEGATION_CERT_INSTALL)) {
3299                         scopes.add(DELEGATION_CERT_INSTALL);
3300                         needsRewrite = true;
3301                     }
3302                 }
3303                 final String appRestrictionsDelegate = parser.getAttributeValue(null,
3304                         ATTR_APPLICATION_RESTRICTIONS_MANAGER);
3305                 if (appRestrictionsDelegate != null) {
3306                     List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate);
3307                     if (scopes == null) {
3308                         scopes = new ArrayList<>();
3309                         policy.mDelegationMap.put(appRestrictionsDelegate, scopes);
3310                     }
3311                     if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) {
3312                         scopes.add(DELEGATION_APP_RESTRICTIONS);
3313                         needsRewrite = true;
3314                     }
3315                 }
3316             }
3317 
3318             type = parser.next();
3319             int outerDepth = parser.getDepth();
3320             policy.mLockTaskPackages.clear();
3321             policy.mAdminList.clear();
3322             policy.mAdminMap.clear();
3323             policy.mAffiliationIds.clear();
3324             policy.mOwnerInstalledCaCerts.clear();
3325             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
3326                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3327                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3328                     continue;
3329                 }
3330                 tag = parser.getName();
3331                 if ("admin".equals(tag)) {
3332                     String name = parser.getAttributeValue(null, "name");
3333                     try {
3334                         DeviceAdminInfo dai = findAdmin(
3335                                 ComponentName.unflattenFromString(name), userHandle,
3336                                 /* throwForMissingPermission= */ false);
3337                         if (VERBOSE_LOG
3338                                 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
3339                                 != userHandle)) {
3340                             Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
3341                                     + dai.getActivityInfo().applicationInfo.uid + " for user "
3342                                     + userHandle);
3343                         }
3344                         if (dai != null) {
3345                             boolean shouldOverwritePolicies =
3346                                     shouldOverwritePoliciesFromXml(dai.getComponent(), userHandle);
3347                             ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
3348                             ap.readFromXml(parser, shouldOverwritePolicies);
3349                             policy.mAdminMap.put(ap.info.getComponent(), ap);
3350                         }
3351                     } catch (RuntimeException e) {
3352                         Slog.w(LOG_TAG, "Failed loading admin " + name, e);
3353                     }
3354                 } else if ("delegation".equals(tag)) {
3355                     // Parse delegation info.
3356                     final String delegatePackage = parser.getAttributeValue(null,
3357                             "delegatePackage");
3358                     final String scope = parser.getAttributeValue(null, "scope");
3359 
3360                     // Get a reference to the scopes list for the delegatePackage.
3361                     List<String> scopes = policy.mDelegationMap.get(delegatePackage);
3362                     // Or make a new list if none was found.
3363                     if (scopes == null) {
3364                         scopes = new ArrayList<>();
3365                         policy.mDelegationMap.put(delegatePackage, scopes);
3366                     }
3367                     // Add the new scope to the list of delegatePackage if it's not already there.
3368                     if (!scopes.contains(scope)) {
3369                         scopes.add(scope);
3370                     }
3371                 } else if ("failed-password-attempts".equals(tag)) {
3372                     policy.mFailedPasswordAttempts = Integer.parseInt(
3373                             parser.getAttributeValue(null, "value"));
3374                 } else if ("password-owner".equals(tag)) {
3375                     policy.mPasswordOwner = Integer.parseInt(
3376                             parser.getAttributeValue(null, "value"));
3377                 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
3378                     policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
3379                 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
3380                     policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
3381                 } else if (TAG_LOCK_TASK_FEATURES.equals(tag)) {
3382                     policy.mLockTaskFeatures = Integer.parseInt(
3383                             parser.getAttributeValue(null, ATTR_VALUE));
3384                 } else if (TAG_STATUS_BAR.equals(tag)) {
3385                     policy.mStatusBarDisabled = Boolean.parseBoolean(
3386                             parser.getAttributeValue(null, ATTR_DISABLED));
3387                 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
3388                     policy.doNotAskCredentialsOnBoot = true;
3389                 } else if (TAG_AFFILIATION_ID.equals(tag)) {
3390                     policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID));
3391                 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) {
3392                     policy.mLastSecurityLogRetrievalTime = Long.parseLong(
3393                             parser.getAttributeValue(null, ATTR_VALUE));
3394                 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) {
3395                     policy.mLastBugReportRequestTime = Long.parseLong(
3396                             parser.getAttributeValue(null, ATTR_VALUE));
3397                 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) {
3398                     policy.mLastNetworkLogsRetrievalTime = Long.parseLong(
3399                             parser.getAttributeValue(null, ATTR_VALUE));
3400                 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
3401                     String pending = parser.getAttributeValue(null, ATTR_VALUE);
3402                     policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
3403                 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
3404                     policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
3405                 } else if ("active-password".equals(tag)) {
3406                     // Remove password metrics from saved settings, as we no longer wish to store
3407                     // these on disk
3408                     needsRewrite = true;
3409                 } else if (TAG_PASSWORD_VALIDITY.equals(tag)) {
3410                     if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
3411                         // This flag is only used for FDE devices
3412                         policy.mPasswordValidAtLastCheckpoint = Boolean.parseBoolean(
3413                                 parser.getAttributeValue(null, ATTR_VALUE));
3414                     }
3415                 } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) {
3416                     policy.mPasswordTokenHandle = Long.parseLong(
3417                             parser.getAttributeValue(null, ATTR_VALUE));
3418                 } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) {
3419                     policy.mCurrentInputMethodSet = true;
3420                 } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) {
3421                     policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS));
3422                 } else {
3423                     Slog.w(LOG_TAG, "Unknown tag: " + tag);
3424                     XmlUtils.skipCurrentTag(parser);
3425                 }
3426             }
3427         } catch (FileNotFoundException e) {
3428             // Don't be noisy, this is normal if we haven't defined any policies.
3429         } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
3430                 | IndexOutOfBoundsException e) {
3431             Slog.w(LOG_TAG, "failed parsing " + file, e);
3432         }
3433         try {
3434             if (stream != null) {
3435                 stream.close();
3436             }
3437         } catch (IOException e) {
3438             // Ignore
3439         }
3440 
3441         // Generate a list of admins from the admin map
3442         policy.mAdminList.addAll(policy.mAdminMap.values());
3443 
3444         // Might need to upgrade the file by rewriting it
3445         if (needsRewrite) {
3446             saveSettingsLocked(userHandle);
3447         }
3448 
3449         validatePasswordOwnerLocked(policy);
3450         updateMaximumTimeToLockLocked(userHandle);
3451         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
3452         updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle);
3453         if (policy.mStatusBarDisabled) {
3454             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
3455         }
3456     }
3457 
shouldOverwritePoliciesFromXml( ComponentName deviceAdminComponent, int userHandle)3458     private boolean shouldOverwritePoliciesFromXml(
3459             ComponentName deviceAdminComponent, int userHandle) {
3460         // http://b/123415062: If DA, overwrite with the stored policies that were agreed by the
3461         // user to prevent apps from sneaking additional policies into updates.
3462         return !isProfileOwner(deviceAdminComponent, userHandle)
3463                 && !isDeviceOwner(deviceAdminComponent, userHandle);
3464     }
3465 
updateLockTaskPackagesLocked(List<String> packages, int userId)3466     private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
3467         long ident = mInjector.binderClearCallingIdentity();
3468         try {
3469             mInjector.getIActivityManager()
3470                     .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
3471         } catch (RemoteException e) {
3472             // Not gonna happen.
3473         } finally {
3474             mInjector.binderRestoreCallingIdentity(ident);
3475         }
3476     }
3477 
updateLockTaskFeaturesLocked(int flags, int userId)3478     private void updateLockTaskFeaturesLocked(int flags, int userId) {
3479         long ident = mInjector.binderClearCallingIdentity();
3480         try {
3481             mInjector.getIActivityTaskManager().updateLockTaskFeatures(userId, flags);
3482         } catch (RemoteException e) {
3483             // Not gonna happen.
3484         } finally {
3485             mInjector.binderRestoreCallingIdentity(ident);
3486         }
3487     }
3488 
updateDeviceOwnerLocked()3489     private void updateDeviceOwnerLocked() {
3490         long ident = mInjector.binderClearCallingIdentity();
3491         try {
3492             // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
3493             // user id and also protect all other DAs too.
3494             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
3495             if (deviceOwnerComponent != null) {
3496                 mInjector.getIActivityManager()
3497                         .updateDeviceOwner(deviceOwnerComponent.getPackageName());
3498             }
3499         } catch (RemoteException e) {
3500             // Not gonna happen.
3501         } finally {
3502             mInjector.binderRestoreCallingIdentity(ident);
3503         }
3504     }
3505 
validateQualityConstant(int quality)3506     static void validateQualityConstant(int quality) {
3507         switch (quality) {
3508             case PASSWORD_QUALITY_UNSPECIFIED:
3509             case PASSWORD_QUALITY_BIOMETRIC_WEAK:
3510             case PASSWORD_QUALITY_SOMETHING:
3511             case PASSWORD_QUALITY_NUMERIC:
3512             case PASSWORD_QUALITY_NUMERIC_COMPLEX:
3513             case PASSWORD_QUALITY_ALPHABETIC:
3514             case PASSWORD_QUALITY_ALPHANUMERIC:
3515             case PASSWORD_QUALITY_COMPLEX:
3516             case PASSWORD_QUALITY_MANAGED:
3517                 return;
3518         }
3519         throw new IllegalArgumentException("Invalid quality constant: 0x"
3520                 + Integer.toHexString(quality));
3521     }
3522 
validatePasswordOwnerLocked(DevicePolicyData policy)3523     void validatePasswordOwnerLocked(DevicePolicyData policy) {
3524         if (policy.mPasswordOwner >= 0) {
3525             boolean haveOwner = false;
3526             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
3527                 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
3528                     haveOwner = true;
3529                     break;
3530                 }
3531             }
3532             if (!haveOwner) {
3533                 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
3534                         + " no longer active; disabling");
3535                 policy.mPasswordOwner = -1;
3536             }
3537         }
3538     }
3539 
3540     @VisibleForTesting
3541     @Override
systemReady(int phase)3542     void systemReady(int phase) {
3543         if (!mHasFeature) {
3544             return;
3545         }
3546         switch (phase) {
3547             case SystemService.PHASE_LOCK_SETTINGS_READY:
3548                 onLockSettingsReady();
3549                 loadAdminDataAsync();
3550                 mOwners.systemReady();
3551                 break;
3552             case SystemService.PHASE_ACTIVITY_MANAGER_READY:
3553                 maybeStartSecurityLogMonitorOnActivityManagerReady();
3554                 break;
3555             case SystemService.PHASE_BOOT_COMPLETED:
3556                 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
3557                 break;
3558         }
3559     }
3560 
onLockSettingsReady()3561     private void onLockSettingsReady() {
3562         getUserData(UserHandle.USER_SYSTEM);
3563         loadOwners();
3564         cleanUpOldUsers();
3565         maybeSetDefaultProfileOwnerUserRestrictions();
3566         handleStartUser(UserHandle.USER_SYSTEM);
3567         maybeLogStart();
3568 
3569         // Register an observer for watching for user setup complete and settings changes.
3570         mSetupContentObserver.register();
3571         // Initialize the user setup state, to handle the upgrade case.
3572         updateUserSetupCompleteAndPaired();
3573 
3574         List<String> packageList;
3575         synchronized (getLockObject()) {
3576             packageList = getKeepUninstalledPackagesLocked();
3577         }
3578         if (packageList != null) {
3579             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3580         }
3581 
3582         synchronized (getLockObject()) {
3583             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3584             if (deviceOwner != null) {
3585                 // Push the force-ephemeral-users policy to the user manager.
3586                 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3587 
3588                 // Update user switcher message to activity manager.
3589                 ActivityManagerInternal activityManagerInternal =
3590                         mInjector.getActivityManagerInternal();
3591                 activityManagerInternal.setSwitchingFromSystemUserMessage(
3592                         deviceOwner.startUserSessionMessage);
3593                 activityManagerInternal.setSwitchingToSystemUserMessage(
3594                         deviceOwner.endUserSessionMessage);
3595             }
3596 
3597             revertTransferOwnershipIfNecessaryLocked();
3598         }
3599     }
3600 
revertTransferOwnershipIfNecessaryLocked()3601     private void revertTransferOwnershipIfNecessaryLocked() {
3602         if (!mTransferOwnershipMetadataManager.metadataFileExists()) {
3603             return;
3604         }
3605         Slog.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer.");
3606         final TransferOwnershipMetadataManager.Metadata metadata =
3607                 mTransferOwnershipMetadataManager.loadMetadataFile();
3608         // Revert transfer
3609         if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) {
3610             transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3611                     metadata.userId);
3612             deleteTransferOwnershipMetadataFileLocked();
3613             deleteTransferOwnershipBundleLocked(metadata.userId);
3614         } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) {
3615             transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3616                     metadata.userId);
3617             deleteTransferOwnershipMetadataFileLocked();
3618             deleteTransferOwnershipBundleLocked(metadata.userId);
3619         }
3620         updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
3621     }
3622 
maybeLogStart()3623     private void maybeLogStart() {
3624         if (!SecurityLog.isLoggingEnabled()) {
3625             return;
3626         }
3627         final String verifiedBootState =
3628                 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate");
3629         final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode");
3630         SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode);
3631     }
3632 
ensureDeviceOwnerUserStarted()3633     private void ensureDeviceOwnerUserStarted() {
3634         final int userId;
3635         synchronized (getLockObject()) {
3636             if (!mOwners.hasDeviceOwner()) {
3637                 return;
3638             }
3639             userId = mOwners.getDeviceOwnerUserId();
3640         }
3641         if (VERBOSE_LOG) {
3642             Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
3643         }
3644         if (userId != UserHandle.USER_SYSTEM) {
3645             try {
3646                 mInjector.getIActivityManager().startUserInBackground(userId);
3647 
3648                 // STOPSHIP Prevent the DO user from being killed.
3649 
3650             } catch (RemoteException e) {
3651                 Slog.w(LOG_TAG, "Exception starting user", e);
3652             }
3653         }
3654     }
3655 
3656     @Override
handleStartUser(int userId)3657     void handleStartUser(int userId) {
3658         updateScreenCaptureDisabled(userId,
3659                 getScreenCaptureDisabled(null, userId));
3660         pushUserRestrictions(userId);
3661         // When system user is started (device boot), load cache for all users.
3662         // This is to mitigate the potential race between loading the cache and keyguard
3663         // reading the value during user switch, due to onStartUser() being asynchronous.
3664         updatePasswordQualityCacheForUserGroup(
3665                 userId == UserHandle.USER_SYSTEM ? UserHandle.USER_ALL : userId);
3666 
3667         startOwnerService(userId, "start-user");
3668     }
3669 
3670     @Override
handleUnlockUser(int userId)3671     void handleUnlockUser(int userId) {
3672         startOwnerService(userId, "unlock-user");
3673     }
3674 
3675     @Override
handleStopUser(int userId)3676     void handleStopUser(int userId) {
3677         stopOwnerService(userId, "stop-user");
3678     }
3679 
startOwnerService(int userId, String actionForLog)3680     private void startOwnerService(int userId, String actionForLog) {
3681         final ComponentName owner = getOwnerComponent(userId);
3682         if (owner != null) {
3683             mDeviceAdminServiceController.startServiceForOwner(
3684                     owner.getPackageName(), userId, actionForLog);
3685         }
3686     }
3687 
stopOwnerService(int userId, String actionForLog)3688     private void stopOwnerService(int userId, String actionForLog) {
3689         mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog);
3690     }
3691 
cleanUpOldUsers()3692     private void cleanUpOldUsers() {
3693         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3694         // before reboot
3695         Set<Integer> usersWithProfileOwners;
3696         Set<Integer> usersWithData;
3697         synchronized (getLockObject()) {
3698             usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3699             usersWithData = new ArraySet<>();
3700             for (int i = 0; i < mUserData.size(); i++) {
3701                 usersWithData.add(mUserData.keyAt(i));
3702             }
3703         }
3704         List<UserInfo> allUsers = mUserManager.getUsers();
3705 
3706         Set<Integer> deletedUsers = new ArraySet<>();
3707         deletedUsers.addAll(usersWithProfileOwners);
3708         deletedUsers.addAll(usersWithData);
3709         for (UserInfo userInfo : allUsers) {
3710             deletedUsers.remove(userInfo.id);
3711         }
3712         for (Integer userId : deletedUsers) {
3713             removeUserData(userId);
3714         }
3715     }
3716 
handlePasswordExpirationNotification(int userHandle)3717     private void handlePasswordExpirationNotification(int userHandle) {
3718         final Bundle adminExtras = new Bundle();
3719         adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3720 
3721         synchronized (getLockObject()) {
3722             final long now = System.currentTimeMillis();
3723 
3724             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3725                     userHandle, /* parent */ false);
3726             final int N = admins.size();
3727             for (int i = 0; i < N; i++) {
3728                 ActiveAdmin admin = admins.get(i);
3729                 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
3730                         && admin.passwordExpirationTimeout > 0L
3731                         && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3732                         && admin.passwordExpirationDate > 0L) {
3733                     sendAdminCommandLocked(admin,
3734                             DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3735                 }
3736             }
3737             setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3738         }
3739     }
3740 
3741     /**
3742      * Clean up internal state when the set of installed trusted CA certificates changes.
3743      *
3744      * @param userHandle user to check for. This must be a real user and not, for example,
3745      *        {@link UserHandle#ALL}.
3746      * @param installedCertificates the full set of certificate authorities currently installed for
3747      *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3748      *        correspond to some subset of this.
3749      */
onInstalledCertificatesChanged(final UserHandle userHandle, final @NonNull Collection<String> installedCertificates)3750     protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3751             final @NonNull Collection<String> installedCertificates) {
3752         if (!mHasFeature) {
3753             return;
3754         }
3755         enforceManageUsers();
3756 
3757         synchronized (getLockObject()) {
3758             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3759 
3760             boolean changed = false;
3761             changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3762             changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3763             if (changed) {
3764                 saveSettingsLocked(userHandle.getIdentifier());
3765             }
3766         }
3767     }
3768 
3769     /**
3770      * Internal method used by {@link CertificateMonitor}.
3771      */
getAcceptedCaCertificates(final UserHandle userHandle)3772     protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3773         if (!mHasFeature) {
3774             return Collections.<String> emptySet();
3775         }
3776         synchronized (getLockObject()) {
3777             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3778             return policy.mAcceptedCaCertificates;
3779         }
3780     }
3781 
3782     /**
3783      * @param adminReceiver The admin to add
3784      * @param refreshing true = update an active admin, no error
3785      */
3786     @Override
setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle)3787     public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
3788         if (!mHasFeature) {
3789             return;
3790         }
3791         setActiveAdmin(adminReceiver, refreshing, userHandle, null);
3792     }
3793 
setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, Bundle onEnableData)3794     private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
3795             Bundle onEnableData) {
3796         mContext.enforceCallingOrSelfPermission(
3797                 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3798         enforceFullCrossUsersPermission(userHandle);
3799 
3800         DevicePolicyData policy = getUserData(userHandle);
3801         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3802                 /* throwForMissingPermission= */ true);
3803         synchronized (getLockObject()) {
3804             checkActiveAdminPrecondition(adminReceiver, info, policy);
3805             long ident = mInjector.binderClearCallingIdentity();
3806             try {
3807                 final ActiveAdmin existingAdmin
3808                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3809                 if (!refreshing && existingAdmin != null) {
3810                     throw new IllegalArgumentException("Admin is already added");
3811                 }
3812                 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3813                 newAdmin.testOnlyAdmin =
3814                         (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3815                                 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3816                 policy.mAdminMap.put(adminReceiver, newAdmin);
3817                 int replaceIndex = -1;
3818                 final int N = policy.mAdminList.size();
3819                 for (int i=0; i < N; i++) {
3820                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3821                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3822                         replaceIndex = i;
3823                         break;
3824                     }
3825                 }
3826                 if (replaceIndex == -1) {
3827                     policy.mAdminList.add(newAdmin);
3828                     enableIfNecessary(info.getPackageName(), userHandle);
3829                     mUsageStatsManagerInternal.onActiveAdminAdded(
3830                             adminReceiver.getPackageName(), userHandle);
3831                 } else {
3832                     policy.mAdminList.set(replaceIndex, newAdmin);
3833                 }
3834                 saveSettingsLocked(userHandle);
3835                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3836                         onEnableData, null);
3837             } finally {
3838                 mInjector.binderRestoreCallingIdentity(ident);
3839             }
3840         }
3841     }
3842 
loadAdminDataAsync()3843     private void loadAdminDataAsync() {
3844         mInjector.postOnSystemServerInitThreadPool(() -> {
3845             pushActiveAdminPackages();
3846             mUsageStatsManagerInternal.onAdminDataAvailable();
3847             pushAllMeteredRestrictedPackages();
3848             mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable();
3849         });
3850     }
3851 
pushActiveAdminPackages()3852     private void pushActiveAdminPackages() {
3853         synchronized (getLockObject()) {
3854             final List<UserInfo> users = mUserManager.getUsers();
3855             for (int i = users.size() - 1; i >= 0; --i) {
3856                 final int userId = users.get(i).id;
3857                 mUsageStatsManagerInternal.setActiveAdminApps(
3858                         getActiveAdminPackagesLocked(userId), userId);
3859             }
3860         }
3861     }
3862 
pushAllMeteredRestrictedPackages()3863     private void pushAllMeteredRestrictedPackages() {
3864         synchronized (getLockObject()) {
3865             final List<UserInfo> users = mUserManager.getUsers();
3866             for (int i = users.size() - 1; i >= 0; --i) {
3867                 final int userId = users.get(i).id;
3868                 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync(
3869                         getMeteredDisabledPackagesLocked(userId), userId);
3870             }
3871         }
3872     }
3873 
pushActiveAdminPackagesLocked(int userId)3874     private void pushActiveAdminPackagesLocked(int userId) {
3875         mUsageStatsManagerInternal.setActiveAdminApps(
3876                 getActiveAdminPackagesLocked(userId), userId);
3877     }
3878 
getActiveAdminPackagesLocked(int userId)3879     private Set<String> getActiveAdminPackagesLocked(int userId) {
3880         final DevicePolicyData policy = getUserData(userId);
3881         Set<String> adminPkgs = null;
3882         for (int i = policy.mAdminList.size() - 1; i >= 0; --i) {
3883             final String pkgName = policy.mAdminList.get(i).info.getPackageName();
3884             if (adminPkgs == null) {
3885                 adminPkgs = new ArraySet<>();
3886             }
3887             adminPkgs.add(pkgName);
3888         }
3889         return adminPkgs;
3890     }
3891 
transferActiveAdminUncheckedLocked(ComponentName incomingReceiver, ComponentName outgoingReceiver, int userHandle)3892     private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver,
3893             ComponentName outgoingReceiver, int userHandle) {
3894         final DevicePolicyData policy = getUserData(userHandle);
3895         if (!policy.mAdminMap.containsKey(outgoingReceiver)
3896                 && policy.mAdminMap.containsKey(incomingReceiver)) {
3897             // Nothing to transfer - the incoming receiver is already the active admin.
3898             return;
3899         }
3900         final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle,
3901             /* throwForMissingPermission= */ true);
3902         final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver);
3903         final int oldAdminUid = adminToTransfer.getUid();
3904 
3905         adminToTransfer.transfer(incomingDeviceInfo);
3906         policy.mAdminMap.remove(outgoingReceiver);
3907         policy.mAdminMap.put(incomingReceiver, adminToTransfer);
3908         if (policy.mPasswordOwner == oldAdminUid) {
3909             policy.mPasswordOwner = adminToTransfer.getUid();
3910         }
3911 
3912         saveSettingsLocked(userHandle);
3913         sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3914                 null, null);
3915     }
3916 
checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info, DevicePolicyData policy)3917     private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info,
3918             DevicePolicyData policy) {
3919         if (info == null) {
3920             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3921         }
3922         if (!info.getActivityInfo().applicationInfo.isInternal()) {
3923             throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3924                     + adminReceiver);
3925         }
3926         if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3927             throw new IllegalArgumentException("Instant apps cannot be device admins: "
3928                     + adminReceiver);
3929         }
3930         if (policy.mRemovingAdmins.contains(adminReceiver)) {
3931             throw new IllegalArgumentException(
3932                     "Trying to set an admin which is being removed");
3933         }
3934     }
3935 
3936     @Override
isAdminActive(ComponentName adminReceiver, int userHandle)3937     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3938         if (!mHasFeature) {
3939             return false;
3940         }
3941         enforceFullCrossUsersPermission(userHandle);
3942         synchronized (getLockObject()) {
3943             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3944         }
3945     }
3946 
3947     @Override
isRemovingAdmin(ComponentName adminReceiver, int userHandle)3948     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3949         if (!mHasFeature) {
3950             return false;
3951         }
3952         enforceFullCrossUsersPermission(userHandle);
3953         synchronized (getLockObject()) {
3954             DevicePolicyData policyData = getUserData(userHandle);
3955             return policyData.mRemovingAdmins.contains(adminReceiver);
3956         }
3957     }
3958 
3959     @Override
hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle)3960     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3961         if (!mHasFeature) {
3962             return false;
3963         }
3964         enforceFullCrossUsersPermission(userHandle);
3965         synchronized (getLockObject()) {
3966             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3967             if (administrator == null) {
3968                 throw new SecurityException("No active admin " + adminReceiver);
3969             }
3970             return administrator.info.usesPolicy(policyId);
3971         }
3972     }
3973 
3974     @Override
3975     @SuppressWarnings("unchecked")
getActiveAdmins(int userHandle)3976     public List<ComponentName> getActiveAdmins(int userHandle) {
3977         if (!mHasFeature) {
3978             return Collections.EMPTY_LIST;
3979         }
3980 
3981         enforceFullCrossUsersPermission(userHandle);
3982         synchronized (getLockObject()) {
3983             DevicePolicyData policy = getUserData(userHandle);
3984             final int N = policy.mAdminList.size();
3985             if (N <= 0) {
3986                 return null;
3987             }
3988             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3989             for (int i=0; i<N; i++) {
3990                 res.add(policy.mAdminList.get(i).info.getComponent());
3991             }
3992             return res;
3993         }
3994     }
3995 
3996     @Override
packageHasActiveAdmins(String packageName, int userHandle)3997     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3998         if (!mHasFeature) {
3999             return false;
4000         }
4001         enforceFullCrossUsersPermission(userHandle);
4002         synchronized (getLockObject()) {
4003             DevicePolicyData policy = getUserData(userHandle);
4004             final int N = policy.mAdminList.size();
4005             for (int i=0; i<N; i++) {
4006                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
4007                     return true;
4008                 }
4009             }
4010             return false;
4011         }
4012     }
4013 
4014     @Override
forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle)4015     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
4016         if (!mHasFeature) {
4017             return;
4018         }
4019         Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
4020         enforceShell("forceRemoveActiveAdmin");
4021         long ident = mInjector.binderClearCallingIdentity();
4022         try {
4023             synchronized (getLockObject()) {
4024                 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
4025                     throw new SecurityException("Attempt to remove non-test admin "
4026                             + adminReceiver + " " + userHandle);
4027                 }
4028 
4029                 // If admin is a device or profile owner tidy that up first.
4030                 if (isDeviceOwner(adminReceiver, userHandle)) {
4031                     clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
4032                 }
4033                 if (isProfileOwner(adminReceiver, userHandle)) {
4034                     final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
4035                             userHandle, /* parent */ false);
4036                     clearProfileOwnerLocked(admin, userHandle);
4037                 }
4038             }
4039             // Remove the admin skipping sending the broadcast.
4040             removeAdminArtifacts(adminReceiver, userHandle);
4041             Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
4042         } finally {
4043             mInjector.binderRestoreCallingIdentity(ident);
4044         }
4045     }
4046 
clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle)4047     private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) {
4048         // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state
4049         if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
4050             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle);
4051         }
4052     }
4053 
4054     /**
4055      * Return if a given package has testOnly="true", in which case we'll relax certain rules
4056      * for CTS.
4057      *
4058      * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
4059      * to check wehter an active admin is test-only or not.
4060      *
4061      * The system allows this flag to be changed when an app is updated, which is not good
4062      * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
4063      * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
4064      */
isPackageTestOnly(String packageName, int userHandle)4065     private boolean isPackageTestOnly(String packageName, int userHandle) {
4066         final ApplicationInfo ai;
4067         try {
4068             ai = mInjector.getIPackageManager().getApplicationInfo(packageName,
4069                     (PackageManager.MATCH_DIRECT_BOOT_AWARE
4070                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
4071         } catch (RemoteException e) {
4072             throw new IllegalStateException(e);
4073         }
4074         if (ai == null) {
4075             throw new IllegalStateException("Couldn't find package: "
4076                     + packageName + " on user " + userHandle);
4077         }
4078         return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
4079     }
4080 
4081     /**
4082      * See {@link #isPackageTestOnly}.
4083      */
isAdminTestOnlyLocked(ComponentName who, int userHandle)4084     private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
4085         final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
4086         return (admin != null) && admin.testOnlyAdmin;
4087     }
4088 
enforceShell(String method)4089     private void enforceShell(String method) {
4090         final int callingUid = mInjector.binderGetCallingUid();
4091         if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
4092             throw new SecurityException("Non-shell user attempted to call " + method);
4093         }
4094     }
4095 
4096     @Override
removeActiveAdmin(ComponentName adminReceiver, int userHandle)4097     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
4098         if (!mHasFeature) {
4099             return;
4100         }
4101         enforceFullCrossUsersPermission(userHandle);
4102         enforceUserUnlocked(userHandle);
4103         synchronized (getLockObject()) {
4104             ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
4105             if (admin == null) {
4106                 return;
4107             }
4108             // Active device/profile owners must remain active admins.
4109             if (isDeviceOwner(adminReceiver, userHandle)
4110                     || isProfileOwner(adminReceiver, userHandle)) {
4111                 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
4112                         adminReceiver);
4113                 return;
4114             }
4115             if (admin.getUid() != mInjector.binderGetCallingUid()) {
4116                 mContext.enforceCallingOrSelfPermission(
4117                         android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
4118             }
4119             long ident = mInjector.binderClearCallingIdentity();
4120             try {
4121                 removeActiveAdminLocked(adminReceiver, userHandle);
4122             } finally {
4123                 mInjector.binderRestoreCallingIdentity(ident);
4124             }
4125         }
4126     }
4127 
4128     @Override
isSeparateProfileChallengeAllowed(int userHandle)4129     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
4130         if (!isCallerWithSystemUid()) {
4131             throw new SecurityException("Caller must be system");
4132         }
4133         ComponentName profileOwner = getProfileOwner(userHandle);
4134         // Profile challenge is supported on N or newer release.
4135         return profileOwner != null &&
4136                 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
4137     }
4138 
4139     @Override
setPasswordQuality(ComponentName who, int quality, boolean parent)4140     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
4141         if (!mHasFeature) {
4142             return;
4143         }
4144         Preconditions.checkNotNull(who, "ComponentName is null");
4145         validateQualityConstant(quality);
4146 
4147         final int userId = mInjector.userHandleGetCallingUserId();
4148         synchronized (getLockObject()) {
4149             ActiveAdmin ap = getActiveAdminForCallerLocked(
4150                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4151             final long ident = mInjector.binderClearCallingIdentity();
4152             try {
4153                 final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4154                 if (metrics.quality != quality) {
4155                     metrics.quality = quality;
4156                     updatePasswordValidityCheckpointLocked(userId, parent);
4157                     updatePasswordQualityCacheForUserGroup(userId);
4158                     saveSettingsLocked(userId);
4159                 }
4160                 maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4161             } finally {
4162                 mInjector.binderRestoreCallingIdentity(ident);
4163             }
4164         }
4165         DevicePolicyEventLogger
4166                 .createEvent(DevicePolicyEnums.SET_PASSWORD_QUALITY)
4167                 .setAdmin(who)
4168                 .setInt(quality)
4169                 .setBoolean(parent)
4170                 .write();
4171     }
4172 
4173     /**
4174      * Updates a flag that tells us whether the user's password currently satisfies the
4175      * requirements set by all of the user's active admins. The flag is updated both in memory
4176      * and persisted to disk by calling {@link #saveSettingsLocked}, for the value of the flag
4177      * be the correct one upon boot.
4178      * This should be called whenever the password or the admin policies have changed.
4179      */
4180     @GuardedBy("getLockObject()")
updatePasswordValidityCheckpointLocked(int userHandle, boolean parent)4181     private void updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) {
4182         final int credentialOwner = getCredentialOwner(userHandle, parent);
4183         DevicePolicyData policy = getUserData(credentialOwner);
4184         PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
4185         if (metrics == null) {
4186             metrics = new PasswordMetrics();
4187         }
4188         policy.mPasswordValidAtLastCheckpoint =
4189                 isPasswordSufficientForUserWithoutCheckpointLocked(
4190                         metrics, userHandle, parent);
4191 
4192         saveSettingsLocked(credentialOwner);
4193     }
4194 
4195     /**
4196      * Update password quality values in policy cache for all users in the same user group as
4197      * the given user. The cached password quality for user X is the aggregated quality among all
4198      * admins who have influence of user X's screenlock, i.e. it's equivalent to the return value of
4199      * getPasswordQuality(null, user X, false).
4200      *
4201      * Caches for all users in the same user group often need to be updated alltogether because a
4202      * user's admin policy can affect another's aggregated password quality in some situation.
4203      * For example a managed profile's policy will affect the parent user if the profile has unified
4204      * challenge. A profile can also explicitly set a parent password quality which will affect the
4205      * aggregated password quality of the parent user.
4206      */
updatePasswordQualityCacheForUserGroup(@serIdInt int userId)4207     private void updatePasswordQualityCacheForUserGroup(@UserIdInt int userId) {
4208         final List<UserInfo> users;
4209         if (userId == UserHandle.USER_ALL) {
4210             users = mUserManager.getUsers();
4211         } else {
4212             users = mUserManager.getProfiles(userId);
4213         }
4214         for (UserInfo userInfo : users) {
4215             final int currentUserId = userInfo.id;
4216             mPolicyCache.setPasswordQuality(currentUserId,
4217                     getPasswordQuality(null, currentUserId, false));
4218         }
4219     }
4220 
4221     @Override
getPasswordQuality(ComponentName who, int userHandle, boolean parent)4222     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
4223         if (!mHasFeature) {
4224             return PASSWORD_QUALITY_UNSPECIFIED;
4225         }
4226         enforceFullCrossUsersPermission(userHandle);
4227         synchronized (getLockObject()) {
4228             int mode = PASSWORD_QUALITY_UNSPECIFIED;
4229 
4230             if (who != null) {
4231                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4232                 return admin != null ? admin.minimumPasswordMetrics.quality : mode;
4233             }
4234 
4235             // Return the strictest policy across all participating admins.
4236             List<ActiveAdmin> admins =
4237                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4238             final int N = admins.size();
4239             for (int i = 0; i < N; i++) {
4240                 ActiveAdmin admin = admins.get(i);
4241                 if (mode < admin.minimumPasswordMetrics.quality) {
4242                     mode = admin.minimumPasswordMetrics.quality;
4243                 }
4244             }
4245             return mode;
4246         }
4247     }
4248 
getActiveAdminsForLockscreenPoliciesLocked( int userHandle, boolean parent)4249     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
4250             int userHandle, boolean parent) {
4251         if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
4252             // If this user has a separate challenge, only return its restrictions.
4253             return getUserDataUnchecked(userHandle).mAdminList;
4254         } else {
4255             // Return all admins for this user and the profiles that are visible from this
4256             // user that do not use a separate work challenge.
4257             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4258             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4259                 DevicePolicyData policy = getUserData(userInfo.id);
4260                 if (!userInfo.isManagedProfile()) {
4261                     admins.addAll(policy.mAdminList);
4262                 } else {
4263                     // For managed profiles, we always include the policies set on the parent
4264                     // profile. Additionally, we include the ones set on the managed profile
4265                     // if no separate challenge is in place.
4266                     boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
4267                     final int N = policy.mAdminList.size();
4268                     for (int i = 0; i < N; i++) {
4269                         ActiveAdmin admin = policy.mAdminList.get(i);
4270                         if (admin.hasParentActiveAdmin()) {
4271                             admins.add(admin.getParentActiveAdmin());
4272                         }
4273                         if (!hasSeparateChallenge) {
4274                             admins.add(admin);
4275                         }
4276                     }
4277                 }
4278             }
4279             return admins;
4280         }
4281     }
4282 
isSeparateProfileChallengeEnabled(int userHandle)4283     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
4284         long ident = mInjector.binderClearCallingIdentity();
4285         try {
4286             return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
4287         } finally {
4288             mInjector.binderRestoreCallingIdentity(ident);
4289         }
4290     }
4291 
4292     @Override
setPasswordMinimumLength(ComponentName who, int length, boolean parent)4293     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
4294         if (!mHasFeature) {
4295             return;
4296         }
4297         Preconditions.checkNotNull(who, "ComponentName is null");
4298         final int userId = mInjector.userHandleGetCallingUserId();
4299         synchronized (getLockObject()) {
4300             ActiveAdmin ap = getActiveAdminForCallerLocked(
4301                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4302             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4303             if (metrics.length != length) {
4304                 metrics.length = length;
4305                 updatePasswordValidityCheckpointLocked(userId, parent);
4306                 saveSettingsLocked(userId);
4307             }
4308             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4309         }
4310         DevicePolicyEventLogger
4311                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LENGTH)
4312                 .setAdmin(who)
4313                 .setInt(length)
4314                 .write();
4315     }
4316 
4317     @Override
getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent)4318     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
4319         return getStrictestPasswordRequirement(who, userHandle, parent,
4320                 admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_UNSPECIFIED);
4321     }
4322 
4323     @Override
setPasswordHistoryLength(ComponentName who, int length, boolean parent)4324     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
4325         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4326             return;
4327         }
4328         Preconditions.checkNotNull(who, "ComponentName is null");
4329         final int userId = mInjector.userHandleGetCallingUserId();
4330         synchronized (getLockObject()) {
4331             ActiveAdmin ap = getActiveAdminForCallerLocked(
4332                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4333             if (ap.passwordHistoryLength != length) {
4334                 ap.passwordHistoryLength = length;
4335                 updatePasswordValidityCheckpointLocked(userId, parent);
4336                 saveSettingsLocked(userId);
4337             }
4338         }
4339         if (SecurityLog.isLoggingEnabled()) {
4340             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4341             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET,
4342                     who.getPackageName(), userId, affectedUserId, length);
4343         }
4344     }
4345 
4346     @Override
getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent)4347     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
4348         if (!mLockPatternUtils.hasSecureLockScreen()) {
4349             return 0;
4350         }
4351         return getStrictestPasswordRequirement(who, userHandle, parent,
4352                 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
4353     }
4354 
4355     @Override
setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent)4356     public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
4357         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4358             return;
4359         }
4360         Preconditions.checkNotNull(who, "ComponentName is null");
4361         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
4362         final int userHandle = mInjector.userHandleGetCallingUserId();
4363         synchronized (getLockObject()) {
4364             ActiveAdmin ap = getActiveAdminForCallerLocked(
4365                     who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
4366             // Calling this API automatically bumps the expiration date
4367             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4368             ap.passwordExpirationDate = expiration;
4369             ap.passwordExpirationTimeout = timeout;
4370             if (timeout > 0L) {
4371                 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
4372                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
4373                         .format(new Date(expiration)));
4374             }
4375             saveSettingsLocked(userHandle);
4376 
4377             // in case this is the first one, set the alarm on the appropriate user.
4378             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
4379         }
4380         if (SecurityLog.isLoggingEnabled()) {
4381             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
4382             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(),
4383                     userHandle, affectedUserId, timeout);
4384         }
4385     }
4386 
4387     /**
4388      * Return a single admin's expiration cycle time, or the min of all cycle times.
4389      * Returns 0 if not configured.
4390      */
4391     @Override
getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent)4392     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
4393         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4394             return 0L;
4395         }
4396         enforceFullCrossUsersPermission(userHandle);
4397         synchronized (getLockObject()) {
4398             long timeout = 0L;
4399 
4400             if (who != null) {
4401                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4402                 return admin != null ? admin.passwordExpirationTimeout : timeout;
4403             }
4404 
4405             // Return the strictest policy across all participating admins.
4406             List<ActiveAdmin> admins =
4407                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4408             final int N = admins.size();
4409             for (int i = 0; i < N; i++) {
4410                 ActiveAdmin admin = admins.get(i);
4411                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
4412                         && timeout > admin.passwordExpirationTimeout)) {
4413                     timeout = admin.passwordExpirationTimeout;
4414                 }
4415             }
4416             return timeout;
4417         }
4418     }
4419 
4420     @Override
addCrossProfileWidgetProvider(ComponentName admin, String packageName)4421     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4422         final int userId = UserHandle.getCallingUserId();
4423         List<String> changedProviders = null;
4424 
4425         synchronized (getLockObject()) {
4426             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4427                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4428             if (activeAdmin.crossProfileWidgetProviders == null) {
4429                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
4430             }
4431             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4432             if (!providers.contains(packageName)) {
4433                 providers.add(packageName);
4434                 changedProviders = new ArrayList<>(providers);
4435                 saveSettingsLocked(userId);
4436             }
4437         }
4438 
4439         DevicePolicyEventLogger
4440                 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_WIDGET_PROVIDER)
4441                 .setAdmin(admin)
4442                 .write();
4443 
4444         if (changedProviders != null) {
4445             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
4446             return true;
4447         }
4448 
4449         return false;
4450     }
4451 
4452     @Override
removeCrossProfileWidgetProvider(ComponentName admin, String packageName)4453     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4454         final int userId = UserHandle.getCallingUserId();
4455         List<String> changedProviders = null;
4456 
4457         synchronized (getLockObject()) {
4458             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4459                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4460             if (activeAdmin.crossProfileWidgetProviders == null
4461                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4462                 return false;
4463             }
4464             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4465             if (providers.remove(packageName)) {
4466                 changedProviders = new ArrayList<>(providers);
4467                 saveSettingsLocked(userId);
4468             }
4469         }
4470 
4471         DevicePolicyEventLogger
4472                 .createEvent(DevicePolicyEnums.REMOVE_CROSS_PROFILE_WIDGET_PROVIDER)
4473                 .setAdmin(admin)
4474                 .write();
4475 
4476         if (changedProviders != null) {
4477             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
4478             return true;
4479         }
4480 
4481         return false;
4482     }
4483 
4484     @Override
getCrossProfileWidgetProviders(ComponentName admin)4485     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
4486         synchronized (getLockObject()) {
4487             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4488                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4489             if (activeAdmin.crossProfileWidgetProviders == null
4490                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4491                 return null;
4492             }
4493             if (mInjector.binderIsCallingUidMyUid()) {
4494                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
4495             } else {
4496                 return activeAdmin.crossProfileWidgetProviders;
4497             }
4498         }
4499     }
4500 
4501     /**
4502      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
4503      * Returns 0 if not configured.
4504      */
getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent)4505     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
4506         long timeout = 0L;
4507 
4508         if (who != null) {
4509             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4510             return admin != null ? admin.passwordExpirationDate : timeout;
4511         }
4512 
4513         // Return the strictest policy across all participating admins.
4514         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4515         final int N = admins.size();
4516         for (int i = 0; i < N; i++) {
4517             ActiveAdmin admin = admins.get(i);
4518             if (timeout == 0L || (admin.passwordExpirationDate != 0
4519                     && timeout > admin.passwordExpirationDate)) {
4520                 timeout = admin.passwordExpirationDate;
4521             }
4522         }
4523         return timeout;
4524     }
4525 
4526     @Override
getPasswordExpiration(ComponentName who, int userHandle, boolean parent)4527     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
4528         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4529             return 0L;
4530         }
4531         enforceFullCrossUsersPermission(userHandle);
4532         synchronized (getLockObject()) {
4533             return getPasswordExpirationLocked(who, userHandle, parent);
4534         }
4535     }
4536 
4537     @Override
setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent)4538     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
4539         if (!mHasFeature) {
4540             return;
4541         }
4542         Preconditions.checkNotNull(who, "ComponentName is null");
4543         final int userId = mInjector.userHandleGetCallingUserId();
4544         synchronized (getLockObject()) {
4545             final ActiveAdmin ap = getActiveAdminForCallerLocked(
4546                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4547             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4548             if (metrics.upperCase != length) {
4549                 metrics.upperCase = length;
4550                 updatePasswordValidityCheckpointLocked(userId, parent);
4551                 saveSettingsLocked(userId);
4552             }
4553             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4554         }
4555         DevicePolicyEventLogger
4556                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_UPPER_CASE)
4557                 .setAdmin(who)
4558                 .setInt(length)
4559                 .write();
4560     }
4561 
4562     @Override
getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent)4563     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
4564         return getStrictestPasswordRequirement(who, userHandle, parent,
4565                 admin -> admin.minimumPasswordMetrics.upperCase, PASSWORD_QUALITY_COMPLEX);
4566     }
4567 
4568     @Override
setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent)4569     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
4570         Preconditions.checkNotNull(who, "ComponentName is null");
4571         final int userId = mInjector.userHandleGetCallingUserId();
4572         synchronized (getLockObject()) {
4573             ActiveAdmin ap = getActiveAdminForCallerLocked(
4574                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4575             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4576             if (metrics.lowerCase != length) {
4577                 metrics.lowerCase = length;
4578                 updatePasswordValidityCheckpointLocked(userId, parent);
4579                 saveSettingsLocked(userId);
4580             }
4581             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4582         }
4583         DevicePolicyEventLogger
4584                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LOWER_CASE)
4585                 .setAdmin(who)
4586                 .setInt(length)
4587                 .write();
4588     }
4589 
4590     @Override
getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent)4591     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
4592         return getStrictestPasswordRequirement(who, userHandle, parent,
4593                 admin -> admin.minimumPasswordMetrics.lowerCase, PASSWORD_QUALITY_COMPLEX);
4594     }
4595 
4596     @Override
setPasswordMinimumLetters(ComponentName who, int length, boolean parent)4597     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
4598         if (!mHasFeature) {
4599             return;
4600         }
4601         Preconditions.checkNotNull(who, "ComponentName is null");
4602         final int userId = mInjector.userHandleGetCallingUserId();
4603         synchronized (getLockObject()) {
4604             ActiveAdmin ap = getActiveAdminForCallerLocked(
4605                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4606             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4607             if (metrics.letters != length) {
4608                 metrics.letters = length;
4609                 updatePasswordValidityCheckpointLocked(userId, parent);
4610                 saveSettingsLocked(userId);
4611             }
4612             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4613         }
4614         DevicePolicyEventLogger
4615                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_LETTERS)
4616                 .setAdmin(who)
4617                 .setInt(length)
4618                 .write();
4619     }
4620 
4621     @Override
getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent)4622     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
4623         return getStrictestPasswordRequirement(who, userHandle, parent,
4624                 admin -> admin.minimumPasswordMetrics.letters, PASSWORD_QUALITY_COMPLEX);
4625     }
4626 
4627     @Override
setPasswordMinimumNumeric(ComponentName who, int length, boolean parent)4628     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
4629         if (!mHasFeature) {
4630             return;
4631         }
4632         Preconditions.checkNotNull(who, "ComponentName is null");
4633         final int userId = mInjector.userHandleGetCallingUserId();
4634         synchronized (getLockObject()) {
4635             ActiveAdmin ap = getActiveAdminForCallerLocked(
4636                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4637             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4638             if (metrics.numeric != length) {
4639                 metrics.numeric = length;
4640                 updatePasswordValidityCheckpointLocked(userId, parent);
4641                 saveSettingsLocked(userId);
4642             }
4643             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4644         }
4645         DevicePolicyEventLogger
4646                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NUMERIC)
4647                 .setAdmin(who)
4648                 .setInt(length)
4649                 .write();
4650     }
4651 
4652     @Override
getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent)4653     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
4654         return getStrictestPasswordRequirement(who, userHandle, parent,
4655                 admin -> admin.minimumPasswordMetrics.numeric, PASSWORD_QUALITY_COMPLEX);
4656     }
4657 
4658     @Override
setPasswordMinimumSymbols(ComponentName who, int length, boolean parent)4659     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
4660         if (!mHasFeature) {
4661             return;
4662         }
4663         Preconditions.checkNotNull(who, "ComponentName is null");
4664         final int userId = mInjector.userHandleGetCallingUserId();
4665         synchronized (getLockObject()) {
4666             ActiveAdmin ap = getActiveAdminForCallerLocked(
4667                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4668             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4669             if (metrics.symbols != length) {
4670                 ap.minimumPasswordMetrics.symbols = length;
4671                 updatePasswordValidityCheckpointLocked(userId, parent);
4672                 saveSettingsLocked(userId);
4673             }
4674             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4675         }
4676         DevicePolicyEventLogger
4677                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_SYMBOLS)
4678                 .setAdmin(who)
4679                 .setInt(length)
4680                 .write();
4681     }
4682 
4683     @Override
getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent)4684     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
4685         return getStrictestPasswordRequirement(who, userHandle, parent,
4686                 admin -> admin.minimumPasswordMetrics.symbols, PASSWORD_QUALITY_COMPLEX);
4687     }
4688 
4689     @Override
setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent)4690     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
4691         if (!mHasFeature) {
4692             return;
4693         }
4694         Preconditions.checkNotNull(who, "ComponentName is null");
4695         final int userId = mInjector.userHandleGetCallingUserId();
4696         synchronized (getLockObject()) {
4697             ActiveAdmin ap = getActiveAdminForCallerLocked(
4698                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4699             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4700             if (metrics.nonLetter != length) {
4701                 ap.minimumPasswordMetrics.nonLetter = length;
4702                 updatePasswordValidityCheckpointLocked(userId, parent);
4703                 saveSettingsLocked(userId);
4704             }
4705             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4706         }
4707         DevicePolicyEventLogger
4708                 .createEvent(DevicePolicyEnums.SET_PASSWORD_MINIMUM_NON_LETTER)
4709                 .setAdmin(who)
4710                 .setInt(length)
4711                 .write();
4712     }
4713 
4714     @Override
getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent)4715     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
4716         return getStrictestPasswordRequirement(who, userHandle, parent,
4717                 admin -> admin.minimumPasswordMetrics.nonLetter, PASSWORD_QUALITY_COMPLEX);
4718     }
4719 
4720     /**
4721      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
4722      */
getStrictestPasswordRequirement(ComponentName who, int userHandle, boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality)4723     private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
4724             boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
4725         if (!mHasFeature) {
4726             return 0;
4727         }
4728         enforceFullCrossUsersPermission(userHandle);
4729         synchronized (getLockObject()) {
4730             if (who != null) {
4731                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4732                 return admin != null ? getter.apply(admin) : 0;
4733             }
4734 
4735             int maxValue = 0;
4736             final List<ActiveAdmin> admins =
4737                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4738             final int N = admins.size();
4739             for (int i = 0; i < N; i++) {
4740                 final ActiveAdmin admin = admins.get(i);
4741                 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
4742                     continue;
4743                 }
4744                 final Integer adminValue = getter.apply(admin);
4745                 if (adminValue > maxValue) {
4746                     maxValue = adminValue;
4747                 }
4748             }
4749             return maxValue;
4750         }
4751     }
4752 
4753     @Override
isActivePasswordSufficient(int userHandle, boolean parent)4754     public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
4755         if (!mHasFeature) {
4756             return true;
4757         }
4758         enforceFullCrossUsersPermission(userHandle);
4759         enforceUserUnlocked(userHandle, parent);
4760 
4761         synchronized (getLockObject()) {
4762             // This API can only be called by an active device admin,
4763             // so try to retrieve it to check that the caller is one.
4764             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4765             int credentialOwner = getCredentialOwner(userHandle, parent);
4766             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
4767             PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
4768             return isActivePasswordSufficientForUserLocked(
4769                     policy.mPasswordValidAtLastCheckpoint, metrics, userHandle, parent);
4770         }
4771     }
4772 
4773     @Override
isUsingUnifiedPassword(ComponentName admin)4774     public boolean isUsingUnifiedPassword(ComponentName admin) {
4775         if (!mHasFeature) {
4776             return true;
4777         }
4778         final int userId = mInjector.userHandleGetCallingUserId();
4779         enforceProfileOrDeviceOwner(admin);
4780         enforceManagedProfile(userId, "query unified challenge status");
4781         return !isSeparateProfileChallengeEnabled(userId);
4782     }
4783 
4784     @Override
isProfileActivePasswordSufficientForParent(int userHandle)4785     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
4786         if (!mHasFeature) {
4787             return true;
4788         }
4789         enforceFullCrossUsersPermission(userHandle);
4790         enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
4791 
4792         synchronized (getLockObject()) {
4793             final int targetUser = getProfileParentId(userHandle);
4794             enforceUserUnlocked(targetUser, false);
4795             int credentialOwner = getCredentialOwner(userHandle, false);
4796             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
4797             PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
4798             return isActivePasswordSufficientForUserLocked(
4799                     policy.mPasswordValidAtLastCheckpoint, metrics, targetUser, false);
4800         }
4801     }
4802 
isActivePasswordSufficientForUserLocked( boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle, boolean parent)4803     private boolean isActivePasswordSufficientForUserLocked(
4804             boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle,
4805             boolean parent) {
4806         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) {
4807             // Before user enters their password for the first time after a reboot, return the
4808             // value of this flag, which tells us whether the password was valid the last time
4809             // settings were saved.  If DPC changes password requirements on boot so that the
4810             // current password no longer meets the requirements, this value will be stale until
4811             // the next time the password is entered.
4812             return passwordValidAtLastCheckpoint;
4813         }
4814 
4815         if (metrics == null) {
4816             // This could happen if the user never had a password set, for example, so
4817             // setActivePasswordState has never been called for it.
4818             metrics = new PasswordMetrics();
4819         }
4820 
4821         return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle, parent);
4822     }
4823 
4824     /**
4825      * Returns {@code true} if the password represented by the {@code metrics} argument
4826      * sufficiently fulfills the password requirements for the user corresponding to
4827      * {@code userId} (or its parent, if {@code parent} is set to {@code true}).
4828      */
isPasswordSufficientForUserWithoutCheckpointLocked( PasswordMetrics metrics, @UserIdInt int userId, boolean parent)4829     private boolean isPasswordSufficientForUserWithoutCheckpointLocked(
4830             PasswordMetrics metrics, @UserIdInt int userId, boolean parent) {
4831         final int requiredQuality = getPasswordQuality(null, userId, parent);
4832 
4833         if (requiredQuality >= PASSWORD_QUALITY_NUMERIC
4834                 && metrics.length < getPasswordMinimumLength(null, userId, parent)) {
4835             return false;
4836         }
4837 
4838         // PASSWORD_QUALITY_COMPLEX doesn't represent actual password quality, it means that number
4839         // of characters of each class should be checked instead of quality itself.
4840         if (requiredQuality == PASSWORD_QUALITY_COMPLEX) {
4841             return metrics.upperCase >= getPasswordMinimumUpperCase(null, userId, parent)
4842                     && metrics.lowerCase >= getPasswordMinimumLowerCase(null, userId, parent)
4843                     && metrics.letters >= getPasswordMinimumLetters(null, userId, parent)
4844                     && metrics.numeric >= getPasswordMinimumNumeric(null, userId, parent)
4845                     && metrics.symbols >= getPasswordMinimumSymbols(null, userId, parent)
4846                     && metrics.nonLetter >= getPasswordMinimumNonLetter(null, userId, parent);
4847         } else {
4848             return metrics.quality >= requiredQuality;
4849         }
4850     }
4851 
4852     @Override
4853     @PasswordComplexity
getPasswordComplexity()4854     public int getPasswordComplexity() {
4855         DevicePolicyEventLogger
4856                 .createEvent(DevicePolicyEnums.GET_USER_PASSWORD_COMPLEXITY_LEVEL)
4857                 .setStrings(mInjector.getPackageManager()
4858                         .getPackagesForUid(mInjector.binderGetCallingUid()))
4859                 .write();
4860         final int callingUserId = mInjector.userHandleGetCallingUserId();
4861         enforceUserUnlocked(callingUserId);
4862         mContext.enforceCallingOrSelfPermission(
4863                 REQUEST_PASSWORD_COMPLEXITY,
4864                 "Must have " + REQUEST_PASSWORD_COMPLEXITY + " permission.");
4865 
4866         synchronized (getLockObject()) {
4867             int targetUserId = getCredentialOwner(callingUserId, /* parent= */ false);
4868             PasswordMetrics metrics = getUserPasswordMetricsLocked(targetUserId);
4869             return metrics == null ? PASSWORD_COMPLEXITY_NONE : metrics.determineComplexity();
4870         }
4871     }
4872 
4873     @Override
getCurrentFailedPasswordAttempts(int userHandle, boolean parent)4874     public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4875         if (!mLockPatternUtils.hasSecureLockScreen()) {
4876             return 0;
4877         }
4878         enforceFullCrossUsersPermission(userHandle);
4879         synchronized (getLockObject()) {
4880             if (!isCallerWithSystemUid()) {
4881                 // This API can be called by an active device admin or by keyguard code.
4882                 if (mContext.checkCallingPermission(permission.ACCESS_KEYGUARD_SECURE_STORAGE)
4883                         != PackageManager.PERMISSION_GRANTED) {
4884                     getActiveAdminForCallerLocked(
4885                             null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4886                 }
4887             }
4888 
4889             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4890 
4891             return policy.mFailedPasswordAttempts;
4892         }
4893     }
4894 
4895     @Override
setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent)4896     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4897         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4898             return;
4899         }
4900         Preconditions.checkNotNull(who, "ComponentName is null");
4901         final int userId = mInjector.userHandleGetCallingUserId();
4902         synchronized (getLockObject()) {
4903             // This API can only be called by an active device admin,
4904             // so try to retrieve it to check that the caller is one.
4905             getActiveAdminForCallerLocked(
4906                     who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4907             ActiveAdmin ap = getActiveAdminForCallerLocked(
4908                     who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4909             if (ap.maximumFailedPasswordsForWipe != num) {
4910                 ap.maximumFailedPasswordsForWipe = num;
4911                 saveSettingsLocked(userId);
4912             }
4913         }
4914         if (SecurityLog.isLoggingEnabled()) {
4915             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4916             SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(),
4917                     userId, affectedUserId, num);
4918         }
4919     }
4920 
4921     @Override
getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent)4922     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
4923         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4924             return 0;
4925         }
4926         enforceFullCrossUsersPermission(userHandle);
4927         synchronized (getLockObject()) {
4928             ActiveAdmin admin = (who != null)
4929                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
4930                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
4931             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
4932         }
4933     }
4934 
4935     @Override
getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent)4936     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
4937         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
4938             return UserHandle.USER_NULL;
4939         }
4940         enforceFullCrossUsersPermission(userHandle);
4941         synchronized (getLockObject()) {
4942             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4943                     userHandle, parent);
4944             return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
4945         }
4946     }
4947 
4948     /**
4949      * Returns the admin with the strictest policy on maximum failed passwords for:
4950      * <ul>
4951      *   <li>this user if it has a separate profile challenge, or
4952      *   <li>this user and all profiles that don't have their own challenge otherwise.
4953      * </ul>
4954      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
4955      * the primary profile.
4956      * Returns {@code null} if no participating admin has that policy set.
4957      */
getAdminWithMinimumFailedPasswordsForWipeLocked( int userHandle, boolean parent)4958     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
4959             int userHandle, boolean parent) {
4960         int count = 0;
4961         ActiveAdmin strictestAdmin = null;
4962 
4963         // Return the strictest policy across all participating admins.
4964         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4965         final int N = admins.size();
4966         for (int i = 0; i < N; i++) {
4967             ActiveAdmin admin = admins.get(i);
4968             if (admin.maximumFailedPasswordsForWipe ==
4969                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
4970                 continue;  // No max number of failed passwords policy set for this profile.
4971             }
4972 
4973             // We always favor the primary profile if several profiles have the same value set.
4974             int userId = admin.getUserHandle().getIdentifier();
4975             if (count == 0 ||
4976                     count > admin.maximumFailedPasswordsForWipe ||
4977                     (count == admin.maximumFailedPasswordsForWipe &&
4978                             getUserInfo(userId).isPrimary())) {
4979                 count = admin.maximumFailedPasswordsForWipe;
4980                 strictestAdmin = admin;
4981             }
4982         }
4983         return strictestAdmin;
4984     }
4985 
getUserInfo(@serIdInt int userId)4986     private UserInfo getUserInfo(@UserIdInt int userId) {
4987         final long token = mInjector.binderClearCallingIdentity();
4988         try {
4989             return mUserManager.getUserInfo(userId);
4990         } finally {
4991             mInjector.binderRestoreCallingIdentity(token);
4992         }
4993     }
4994 
canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId)4995     private boolean canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId) {
4996         // Only if the admins targets a pre-O SDK
4997         return getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.O;
4998     }
4999 
5000     /* PO or DO could do an untrusted reset in certain conditions. */
canUserHaveUntrustedCredentialReset(@serIdInt int userId)5001     private boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) {
5002         synchronized (getLockObject()) {
5003             // An active DO or PO might be able to fo an untrusted credential reset
5004             for (final ActiveAdmin admin : getUserData(userId).mAdminList) {
5005                 if (!isActiveAdminWithPolicyForUserLocked(admin,
5006                           DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, userId)) {
5007                     continue;
5008                 }
5009                 if (canPOorDOCallResetPassword(admin, userId)) {
5010                     return true;
5011                 }
5012             }
5013             return false;
5014         }
5015     }
5016     @Override
resetPassword(String passwordOrNull, int flags)5017     public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
5018         if (!mLockPatternUtils.hasSecureLockScreen()) {
5019             Slog.w(LOG_TAG, "Cannot reset password when the device has no lock screen");
5020             return false;
5021         }
5022 
5023         final int callingUid = mInjector.binderGetCallingUid();
5024         final int userHandle = mInjector.userHandleGetCallingUserId();
5025 
5026         String password = passwordOrNull != null ? passwordOrNull : "";
5027 
5028         // Password resetting to empty/null is not allowed for managed profiles.
5029         if (TextUtils.isEmpty(password)) {
5030             enforceNotManagedProfile(userHandle, "clear the active password");
5031         }
5032 
5033         synchronized (getLockObject()) {
5034             // If caller has PO (or DO) it can change the password, so see if that's the case first.
5035             ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
5036                     null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
5037             final boolean preN;
5038             if (admin != null) {
5039                 if (!canPOorDOCallResetPassword(admin, userHandle)) {
5040                     throw new SecurityException("resetPassword() is deprecated for DPC targeting O"
5041                             + " or later");
5042                 }
5043                 preN = getTargetSdk(admin.info.getPackageName(),
5044                         userHandle) <= android.os.Build.VERSION_CODES.M;
5045             } else {
5046                 // Otherwise, make sure the caller has any active admin with the right policy or
5047                 // the required permission.
5048                 admin = getActiveAdminOrCheckPermissionForCallerLocked(
5049                         null,
5050                         DeviceAdminInfo.USES_POLICY_RESET_PASSWORD,
5051                         android.Manifest.permission.RESET_PASSWORD);
5052                 // Cannot be preN if admin is null because an exception would have been
5053                 // thrown before getting here
5054                 preN = admin == null ? false : getTargetSdk(admin.info.getPackageName(),
5055                         userHandle) <= android.os.Build.VERSION_CODES.M;
5056 
5057                 // As of N, password resetting to empty/null is not allowed anymore.
5058                 // TODO Should we allow DO/PO to set an empty password?
5059                 if (TextUtils.isEmpty(password)) {
5060                     if (!preN) {
5061                         throw new SecurityException("Cannot call with null password");
5062                     } else {
5063                         Slog.e(LOG_TAG, "Cannot call with null password");
5064                         return false;
5065                     }
5066                 }
5067                 // As of N, password cannot be changed by the admin if it is already set.
5068                 if (isLockScreenSecureUnchecked(userHandle)) {
5069                     if (!preN) {
5070                         throw new SecurityException("Cannot change current password");
5071                     } else {
5072                         Slog.e(LOG_TAG, "Cannot change current password");
5073                         return false;
5074                     }
5075                 }
5076             }
5077             // Do not allow to reset password when current user has a managed profile
5078             if (!isManagedProfile(userHandle)) {
5079                 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
5080                     if (userInfo.isManagedProfile()) {
5081                         if (!preN) {
5082                             throw new IllegalStateException(
5083                                     "Cannot reset password on user has managed profile");
5084                         } else {
5085                             Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
5086                             return false;
5087                         }
5088                     }
5089                 }
5090             }
5091             // Do not allow to reset password when user is locked
5092             if (!mUserManager.isUserUnlocked(userHandle)) {
5093                 if (!preN) {
5094                     throw new IllegalStateException("Cannot reset password when user is locked");
5095                 } else {
5096                     Slog.e(LOG_TAG, "Cannot reset password when user is locked");
5097                     return false;
5098                 }
5099             }
5100         }
5101 
5102         return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle);
5103     }
5104 
resetPasswordInternal(String password, long tokenHandle, byte[] token, int flags, int callingUid, int userHandle)5105     private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
5106             int flags, int callingUid, int userHandle) {
5107         int quality;
5108         synchronized (getLockObject()) {
5109             quality = getPasswordQuality(null, userHandle, /* parent */ false);
5110             if (quality == PASSWORD_QUALITY_MANAGED) {
5111                 quality = PASSWORD_QUALITY_UNSPECIFIED;
5112             }
5113             // TODO(b/120484642): remove getBytes() below
5114             final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password.getBytes());
5115             final int realQuality = metrics.quality;
5116             if (realQuality < quality && quality != PASSWORD_QUALITY_COMPLEX) {
5117                 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
5118                         + Integer.toHexString(realQuality)
5119                         + " does not meet required quality 0x"
5120                         + Integer.toHexString(quality));
5121                 return false;
5122             }
5123             quality = Math.max(realQuality, quality);
5124             int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
5125             if (password.length() < length) {
5126                 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
5127                         + " does not meet required length " + length);
5128                 return false;
5129             }
5130             if (quality == PASSWORD_QUALITY_COMPLEX) {
5131                 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
5132                 if(metrics.letters < neededLetters) {
5133                     Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
5134                             + " does not meet required number of letters " + neededLetters);
5135                     return false;
5136                 }
5137                 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
5138                 if (metrics.numeric < neededNumeric) {
5139                     Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
5140                             + " does not meet required number of numerical digits "
5141                             + neededNumeric);
5142                     return false;
5143                 }
5144                 int neededLowerCase = getPasswordMinimumLowerCase(
5145                         null, userHandle, /* parent */ false);
5146                 if (metrics.lowerCase < neededLowerCase) {
5147                     Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
5148                             + metrics.lowerCase
5149                             + " does not meet required number of lowercase letters "
5150                             + neededLowerCase);
5151                     return false;
5152                 }
5153                 int neededUpperCase = getPasswordMinimumUpperCase(
5154                         null, userHandle, /* parent */ false);
5155                 if (metrics.upperCase < neededUpperCase) {
5156                     Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
5157                             + metrics.upperCase
5158                             + " does not meet required number of uppercase letters "
5159                             + neededUpperCase);
5160                     return false;
5161                 }
5162                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
5163                 if (metrics.symbols < neededSymbols) {
5164                     Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
5165                             + " does not meet required number of special symbols " + neededSymbols);
5166                     return false;
5167                 }
5168                 int neededNonLetter = getPasswordMinimumNonLetter(
5169                         null, userHandle, /* parent */ false);
5170                 if (metrics.nonLetter < neededNonLetter) {
5171                     Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
5172                             + metrics.nonLetter
5173                             + " does not meet required number of non-letter characters "
5174                             + neededNonLetter);
5175                     return false;
5176                 }
5177             }
5178         }
5179 
5180         DevicePolicyData policy = getUserData(userHandle);
5181         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
5182             Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
5183             return false;
5184         }
5185 
5186         boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
5187         boolean doNotAskCredentialsOnBoot =
5188                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
5189         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
5190             setDoNotAskCredentialsOnBoot();
5191         }
5192 
5193         // Don't do this with the lock held, because it is going to call
5194         // back in to the service.
5195         final long ident = mInjector.binderClearCallingIdentity();
5196         final boolean result;
5197         try {
5198             if (token == null) {
5199                 // This is the legacy reset password for DPM. Here we want to be able to override
5200                 // the old device password without necessarily knowing it.
5201                 if (!TextUtils.isEmpty(password)) {
5202                     mLockPatternUtils.saveLockPassword(password.getBytes(), null, quality,
5203                             userHandle, /*allowUntrustedChange */true);
5204                 } else {
5205                     mLockPatternUtils.clearLock(null, userHandle,
5206                             /*allowUntrustedChange */ true);
5207                 }
5208                 result = true;
5209             } else {
5210                 if (!TextUtils.isEmpty(password)) {
5211                     result = mLockPatternUtils.setLockCredentialWithToken(password.getBytes(),
5212                             LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
5213                             quality, tokenHandle, token, userHandle);
5214                 } else {
5215                     result = mLockPatternUtils.setLockCredentialWithToken(null,
5216                             LockPatternUtils.CREDENTIAL_TYPE_NONE,
5217                             quality, tokenHandle, token, userHandle);
5218                 }
5219             }
5220             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
5221             if (requireEntry) {
5222                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
5223                         UserHandle.USER_ALL);
5224             }
5225             synchronized (getLockObject()) {
5226                 int newOwner = requireEntry ? callingUid : -1;
5227                 if (policy.mPasswordOwner != newOwner) {
5228                     policy.mPasswordOwner = newOwner;
5229                     saveSettingsLocked(userHandle);
5230                 }
5231             }
5232         } finally {
5233             mInjector.binderRestoreCallingIdentity(ident);
5234         }
5235         return result;
5236     }
5237 
isLockScreenSecureUnchecked(int userId)5238     private boolean isLockScreenSecureUnchecked(int userId) {
5239         long ident = mInjector.binderClearCallingIdentity();
5240         try {
5241             return mLockPatternUtils.isSecure(userId);
5242         } finally {
5243             mInjector.binderRestoreCallingIdentity(ident);
5244         }
5245     }
5246 
setDoNotAskCredentialsOnBoot()5247     private void setDoNotAskCredentialsOnBoot() {
5248         synchronized (getLockObject()) {
5249             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
5250             if (!policyData.doNotAskCredentialsOnBoot) {
5251                 policyData.doNotAskCredentialsOnBoot = true;
5252                 saveSettingsLocked(UserHandle.USER_SYSTEM);
5253             }
5254         }
5255     }
5256 
5257     @Override
getDoNotAskCredentialsOnBoot()5258     public boolean getDoNotAskCredentialsOnBoot() {
5259         mContext.enforceCallingOrSelfPermission(
5260                 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
5261         synchronized (getLockObject()) {
5262             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
5263             return policyData.doNotAskCredentialsOnBoot;
5264         }
5265     }
5266 
5267     @Override
setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent)5268     public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
5269         if (!mHasFeature) {
5270             return;
5271         }
5272         Preconditions.checkNotNull(who, "ComponentName is null");
5273         final int userHandle = mInjector.userHandleGetCallingUserId();
5274         synchronized (getLockObject()) {
5275             final ActiveAdmin ap = getActiveAdminForCallerLocked(
5276                     who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
5277             if (ap.maximumTimeToUnlock != timeMs) {
5278                 ap.maximumTimeToUnlock = timeMs;
5279                 saveSettingsLocked(userHandle);
5280                 updateMaximumTimeToLockLocked(userHandle);
5281             }
5282         }
5283         if (SecurityLog.isLoggingEnabled()) {
5284             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
5285             SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
5286                     who.getPackageName(), userHandle, affectedUserId, timeMs);
5287         }
5288     }
5289 
updateMaximumTimeToLockLocked(@serIdInt int userId)5290     private void updateMaximumTimeToLockLocked(@UserIdInt int userId) {
5291         // Update the profile's timeout
5292         if (isManagedProfile(userId)) {
5293             updateProfileLockTimeoutLocked(userId);
5294         }
5295 
5296         final long timeMs;
5297         final long ident = mInjector.binderClearCallingIdentity();
5298         try {
5299             // Update the device timeout
5300             final int parentId = getProfileParentId(userId);
5301             timeMs = getMaximumTimeToLockPolicyFromAdmins(
5302                     getActiveAdminsForLockscreenPoliciesLocked(parentId, false));
5303 
5304             final DevicePolicyData policy = getUserDataUnchecked(parentId);
5305             if (policy.mLastMaximumTimeToLock == timeMs) {
5306                 return;
5307             }
5308             policy.mLastMaximumTimeToLock = timeMs;
5309 
5310             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
5311                 // Make sure KEEP_SCREEN_ON is disabled, since that
5312                 // would allow bypassing of the maximum time to lock.
5313                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
5314             }
5315             getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
5316                     UserHandle.USER_SYSTEM, timeMs);
5317         } finally {
5318             mInjector.binderRestoreCallingIdentity(ident);
5319         }
5320     }
5321 
updateProfileLockTimeoutLocked(@serIdInt int userId)5322     private void updateProfileLockTimeoutLocked(@UserIdInt int userId) {
5323         final long timeMs;
5324         if (isSeparateProfileChallengeEnabled(userId)) {
5325             timeMs = getMaximumTimeToLockPolicyFromAdmins(
5326                     getActiveAdminsForLockscreenPoliciesLocked(userId, false /* parent */));
5327         } else {
5328             timeMs = Long.MAX_VALUE;
5329         }
5330 
5331         final DevicePolicyData policy = getUserDataUnchecked(userId);
5332         if (policy.mLastMaximumTimeToLock == timeMs) {
5333             return;
5334         }
5335         policy.mLastMaximumTimeToLock = timeMs;
5336 
5337         final long ident = mInjector.binderClearCallingIdentity();
5338         try {
5339             getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
5340                     userId, policy.mLastMaximumTimeToLock);
5341         } finally {
5342             mInjector.binderRestoreCallingIdentity(ident);
5343         }
5344     }
5345 
5346     @Override
getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent)5347     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
5348         if (!mHasFeature) {
5349             return 0;
5350         }
5351         enforceFullCrossUsersPermission(userHandle);
5352         synchronized (getLockObject()) {
5353             if (who != null) {
5354                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5355                 return admin != null ? admin.maximumTimeToUnlock : 0;
5356             }
5357             // Return the strictest policy across all participating admins.
5358             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5359                     userHandle, parent);
5360             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins);
5361             return timeMs == Long.MAX_VALUE ? 0 : timeMs;
5362         }
5363     }
5364 
getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins)5365     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
5366         long time = Long.MAX_VALUE;
5367         for (final ActiveAdmin admin : admins) {
5368             if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) {
5369                 time = admin.maximumTimeToUnlock;
5370             }
5371         }
5372         return time;
5373     }
5374 
5375     @Override
setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, boolean parent)5376     public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
5377             boolean parent) {
5378         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
5379             return;
5380         }
5381         Preconditions.checkNotNull(who, "ComponentName is null");
5382         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
5383         // timeoutMs with value 0 means that the admin doesn't participate
5384         // timeoutMs is clamped to the interval in case the internal constants change in the future
5385         final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
5386         if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
5387             timeoutMs = minimumStrongAuthTimeout;
5388         }
5389         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
5390             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5391         }
5392 
5393         final int userHandle = mInjector.userHandleGetCallingUserId();
5394         synchronized (getLockObject()) {
5395             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5396                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
5397             if (ap.strongAuthUnlockTimeout != timeoutMs) {
5398                 ap.strongAuthUnlockTimeout = timeoutMs;
5399                 saveSettingsLocked(userHandle);
5400             }
5401         }
5402     }
5403 
5404     /**
5405      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
5406      * admins if who is null.
5407      * Returns 0 if not configured for the provided admin.
5408      */
5409     @Override
getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent)5410     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
5411         if (!mHasFeature) {
5412             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5413         }
5414         if (!mLockPatternUtils.hasSecureLockScreen()) {
5415             // No strong auth timeout on devices not supporting the
5416             // {@link PackageManager#FEATURE_SECURE_LOCK_SCREEN} feature
5417             return 0;
5418         }
5419         enforceFullCrossUsersPermission(userId);
5420         synchronized (getLockObject()) {
5421             if (who != null) {
5422                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
5423                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
5424             }
5425 
5426             // Return the strictest policy across all participating admins.
5427             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
5428 
5429             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5430             for (int i = 0; i < admins.size(); i++) {
5431                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
5432                 if (timeout != 0) { // take only participating admins into account
5433                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
5434                 }
5435             }
5436             return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
5437         }
5438     }
5439 
getMinimumStrongAuthTimeoutMs()5440     private long getMinimumStrongAuthTimeoutMs() {
5441         if (!mInjector.isBuildDebuggable()) {
5442             return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
5443         }
5444         // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
5445         // name cannot be longer than 31 characters
5446         return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
5447                 MINIMUM_STRONG_AUTH_TIMEOUT_MS),
5448                 MINIMUM_STRONG_AUTH_TIMEOUT_MS);
5449     }
5450 
5451     @Override
lockNow(int flags, boolean parent)5452     public void lockNow(int flags, boolean parent) {
5453         if (!mHasFeature) {
5454             return;
5455         }
5456 
5457         final int callingUserId = mInjector.userHandleGetCallingUserId();
5458         ComponentName adminComponent = null;
5459         synchronized (getLockObject()) {
5460             // Make sure the caller has any active admin with the right policy or
5461             // the required permission.
5462             final ActiveAdmin admin = getActiveAdminOrCheckPermissionForCallerLocked(
5463                     null,
5464                     DeviceAdminInfo.USES_POLICY_FORCE_LOCK,
5465                     parent,
5466                     android.Manifest.permission.LOCK_DEVICE);
5467             final long ident = mInjector.binderClearCallingIdentity();
5468             try {
5469                 adminComponent = admin == null ? null : admin.info.getComponent();
5470                 if (adminComponent != null) {
5471                     // For Profile Owners only, callers with only permission not allowed.
5472                     if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
5473                         // Evict key
5474                         enforceManagedProfile(
5475                                 callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5476                         if (!isProfileOwner(adminComponent, callingUserId)) {
5477                             throw new SecurityException("Only profile owner admins can set "
5478                                     + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5479                         }
5480                         if (parent) {
5481                             throw new IllegalArgumentException(
5482                                     "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
5483                         }
5484                         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5485                             throw new UnsupportedOperationException(
5486                                     "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices");
5487                         }
5488                         mUserManager.evictCredentialEncryptionKey(callingUserId);
5489                     }
5490                 }
5491 
5492                 // Lock all users unless this is a managed profile with a separate challenge
5493                 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
5494                         ? UserHandle.USER_ALL : callingUserId);
5495                 mLockPatternUtils.requireStrongAuth(
5496                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
5497 
5498                 // Require authentication for the device or profile
5499                 if (userToLock == UserHandle.USER_ALL) {
5500                     // Power off the display
5501                     mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
5502                             PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
5503                     mInjector.getIWindowManager().lockNow(null);
5504                 } else {
5505                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
5506                 }
5507 
5508                 if (SecurityLog.isLoggingEnabled() && adminComponent != null) {
5509                     final int affectedUserId =
5510                             parent ? getProfileParentId(callingUserId) : callingUserId;
5511                     SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK,
5512                             adminComponent.getPackageName(), callingUserId, affectedUserId);
5513                 }
5514             } catch (RemoteException e) {
5515             } finally {
5516                 mInjector.binderRestoreCallingIdentity(ident);
5517             }
5518         }
5519         DevicePolicyEventLogger
5520                 .createEvent(DevicePolicyEnums.LOCK_NOW)
5521                 .setAdmin(adminComponent)
5522                 .setInt(flags)
5523                 .write();
5524     }
5525 
5526     @Override
enforceCanManageCaCerts(ComponentName who, String callerPackage)5527     public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
5528         if (who == null) {
5529             if (!isCallerDelegate(callerPackage, mInjector.binderGetCallingUid(),
5530                     DELEGATION_CERT_INSTALL)) {
5531                 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
5532             }
5533         } else {
5534             enforceProfileOrDeviceOwner(who);
5535         }
5536     }
5537 
enforceDeviceOwner(ComponentName who)5538     private void enforceDeviceOwner(ComponentName who) {
5539         synchronized (getLockObject()) {
5540             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5541         }
5542     }
5543 
enforceProfileOrDeviceOwner(ComponentName who)5544     private void enforceProfileOrDeviceOwner(ComponentName who) {
5545         synchronized (getLockObject()) {
5546             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5547         }
5548     }
5549 
enforceNetworkStackOrProfileOrDeviceOwner(ComponentName who)5550     private void enforceNetworkStackOrProfileOrDeviceOwner(ComponentName who) {
5551         if (mContext.checkCallingPermission(PERMISSION_MAINLINE_NETWORK_STACK)
5552                 == PackageManager.PERMISSION_GRANTED) {
5553             return;
5554         }
5555         enforceProfileOrDeviceOwner(who);
5556     }
5557 
5558     @Override
approveCaCert(String alias, int userId, boolean approval)5559     public boolean approveCaCert(String alias, int userId, boolean approval) {
5560         enforceManageUsers();
5561         synchronized (getLockObject()) {
5562             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
5563             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
5564             if (!changed) {
5565                 return false;
5566             }
5567             saveSettingsLocked(userId);
5568         }
5569         mCertificateMonitor.onCertificateApprovalsChanged(userId);
5570         return true;
5571     }
5572 
5573     @Override
isCaCertApproved(String alias, int userId)5574     public boolean isCaCertApproved(String alias, int userId) {
5575         enforceManageUsers();
5576         synchronized (getLockObject()) {
5577             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
5578         }
5579     }
5580 
removeCaApprovalsIfNeeded(int userId)5581     private void removeCaApprovalsIfNeeded(int userId) {
5582         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
5583             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
5584             if (userInfo.isManagedProfile()){
5585                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
5586             }
5587             if (!isSecure) {
5588                 synchronized (getLockObject()) {
5589                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
5590                     saveSettingsLocked(userInfo.id);
5591                 }
5592                 mCertificateMonitor.onCertificateApprovalsChanged(userId);
5593             }
5594         }
5595     }
5596 
5597     @Override
installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)5598     public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)
5599             throws RemoteException {
5600         if (!mHasFeature) {
5601             return false;
5602         }
5603         enforceCanManageCaCerts(admin, callerPackage);
5604 
5605         final String alias;
5606 
5607         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
5608         final long id = mInjector.binderClearCallingIdentity();
5609         try {
5610             alias = mCertificateMonitor.installCaCert(userHandle, certBuffer);
5611             final boolean isDelegate = (admin == null);
5612             DevicePolicyEventLogger
5613                     .createEvent(DevicePolicyEnums.INSTALL_CA_CERT)
5614                     .setAdmin(callerPackage)
5615                     .setBoolean(isDelegate)
5616                     .write();
5617             if (alias == null) {
5618                 Log.w(LOG_TAG, "Problem installing cert");
5619                 return false;
5620             }
5621         } finally {
5622             mInjector.binderRestoreCallingIdentity(id);
5623         }
5624 
5625         synchronized (getLockObject()) {
5626             getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias);
5627             saveSettingsLocked(userHandle.getIdentifier());
5628         }
5629         return true;
5630     }
5631 
5632     @Override
uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases)5633     public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
5634         if (!mHasFeature) {
5635             return;
5636         }
5637         enforceCanManageCaCerts(admin, callerPackage);
5638 
5639         final int userId = mInjector.userHandleGetCallingUserId();
5640         final long id = mInjector.binderClearCallingIdentity();
5641         try {
5642             mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases);
5643             final boolean isDelegate = (admin == null);
5644             DevicePolicyEventLogger
5645                     .createEvent(DevicePolicyEnums.UNINSTALL_CA_CERTS)
5646                     .setAdmin(callerPackage)
5647                     .setBoolean(isDelegate)
5648                     .write();
5649         } finally {
5650             mInjector.binderRestoreCallingIdentity(id);
5651         }
5652 
5653         synchronized (getLockObject()) {
5654             if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) {
5655                 saveSettingsLocked(userId);
5656             }
5657         }
5658     }
5659 
5660     @Override
installKeyPair(ComponentName who, String callerPackage, byte[] privKey, byte[] cert, byte[] chain, String alias, boolean requestAccess, boolean isUserSelectable)5661     public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
5662             byte[] cert, byte[] chain, String alias, boolean requestAccess,
5663             boolean isUserSelectable) {
5664         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5665                 DELEGATION_CERT_INSTALL);
5666 
5667 
5668         final int callingUid = mInjector.binderGetCallingUid();
5669         final long id = mInjector.binderClearCallingIdentity();
5670         try {
5671             final KeyChainConnection keyChainConnection =
5672                     KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
5673             try {
5674                 IKeyChainService keyChain = keyChainConnection.getService();
5675                 if (!keyChain.installKeyPair(privKey, cert, chain, alias, KeyStore.UID_SELF)) {
5676                     return false;
5677                 }
5678                 if (requestAccess) {
5679                     keyChain.setGrant(callingUid, alias, true);
5680                 }
5681                 keyChain.setUserSelectable(alias, isUserSelectable);
5682                 final boolean isDelegate = (who == null);
5683                 DevicePolicyEventLogger
5684                         .createEvent(DevicePolicyEnums.INSTALL_KEY_PAIR)
5685                         .setAdmin(callerPackage)
5686                         .setBoolean(isDelegate)
5687                         .write();
5688                 return true;
5689             } catch (RemoteException e) {
5690                 Log.e(LOG_TAG, "Installing certificate", e);
5691             } finally {
5692                 keyChainConnection.close();
5693             }
5694         } catch (InterruptedException e) {
5695             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
5696             Thread.currentThread().interrupt();
5697         } finally {
5698             mInjector.binderRestoreCallingIdentity(id);
5699         }
5700         return false;
5701     }
5702 
5703     @Override
removeKeyPair(ComponentName who, String callerPackage, String alias)5704     public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
5705         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5706                 DELEGATION_CERT_INSTALL);
5707 
5708         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5709         final long id = Binder.clearCallingIdentity();
5710         try {
5711             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
5712             try {
5713                 IKeyChainService keyChain = keyChainConnection.getService();
5714                 final boolean result = keyChain.removeKeyPair(alias);
5715                 final boolean isDelegate = (who == null);
5716                 DevicePolicyEventLogger
5717                         .createEvent(DevicePolicyEnums.REMOVE_KEY_PAIR)
5718                         .setAdmin(callerPackage)
5719                         .setBoolean(isDelegate)
5720                         .write();
5721                 return result;
5722             } catch (RemoteException e) {
5723                 Log.e(LOG_TAG, "Removing keypair", e);
5724             } finally {
5725                 keyChainConnection.close();
5726             }
5727         } catch (InterruptedException e) {
5728             Log.w(LOG_TAG, "Interrupted while removing keypair", e);
5729             Thread.currentThread().interrupt();
5730         } finally {
5731             Binder.restoreCallingIdentity(id);
5732         }
5733         return false;
5734     }
5735 
5736     /**
5737      * Enforce one the following conditions are met:
5738      * (1) The device has a Device Owner, and one of the following holds:
5739      *   (1.1) The caller is the Device Owner
5740      *   (1.2) The caller is another app in the same user as the device owner, AND
5741      *         The caller is the delegated certificate installer.
5742      * (2) The user has a profile owner, AND:
5743      *   (2.1) The profile owner has been granted access to Device IDs and one of the following
5744      *         holds:
5745      *     (2.1.1) The caller is the profile owner.
5746      *     (2.1.2) The caller is from another app in the same user as the profile owner, AND
5747      *       (2.1.2.1) The caller is the delegated cert installer.
5748      *
5749      *  For the device owner case, simply check that the caller is the device owner or the
5750      *  delegated certificate installer.
5751      *
5752      *  For the profile owner case, first check that the caller is the profile owner or can
5753      *  manage the DELEGATION_CERT_INSTALL scope.
5754      *  If that check succeeds, ensure the profile owner was granted access to device
5755      *  identifiers. The grant is transitive: The delegated cert installer is implicitly allowed
5756      *  access to device identifiers in this case as part of the delegation.
5757      */
5758     @VisibleForTesting
enforceCallerCanRequestDeviceIdAttestation( ComponentName who, String callerPackage, int callerUid)5759     public void enforceCallerCanRequestDeviceIdAttestation(
5760             ComponentName who, String callerPackage, int callerUid) throws SecurityException {
5761         final int userId = UserHandle.getUserId(callerUid);
5762 
5763         /**
5764          *  First check if there's a profile owner because the device could be in COMP mode (where
5765          *  there's a device owner and profile owner on the same device).
5766          *  If the caller is from the work profile, then it must be the PO or the delegate, and
5767          *  it must have the right permission to access device identifiers.
5768          */
5769         if (hasProfileOwner(userId)) {
5770             // Make sure that the caller is the profile owner or delegate.
5771             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5772                     DELEGATION_CERT_INSTALL);
5773             // Verify that the profile owner was granted access to Device IDs.
5774             if (canProfileOwnerAccessDeviceIds(userId)) {
5775                 return;
5776             }
5777             throw new SecurityException(
5778                     "Profile Owner is not allowed to access Device IDs.");
5779         }
5780 
5781         // If not, fall back to the device owner check.
5782         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
5783                 DELEGATION_CERT_INSTALL);
5784     }
5785 
5786     @VisibleForTesting
translateIdAttestationFlags( int idAttestationFlags)5787     public static int[] translateIdAttestationFlags(
5788             int idAttestationFlags) {
5789         Map<Integer, Integer> idTypeToAttestationFlag = new HashMap();
5790         idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
5791         idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
5792         idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
5793 
5794         int numFlagsSet = Integer.bitCount(idAttestationFlags);
5795         // No flags are set - return null to indicate no device ID attestation information should
5796         // be included in the attestation record.
5797         if (numFlagsSet == 0) {
5798             return null;
5799         }
5800 
5801         // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if
5802         // no other flag is set. That will lead to inclusion of general device make data in the
5803         // attestation record, but no specific device identifiers.
5804         if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) {
5805             numFlagsSet -= 1;
5806             idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO);
5807         }
5808 
5809         int[] attestationUtilsFlags = new int[numFlagsSet];
5810         int i = 0;
5811         for (Integer idType: idTypeToAttestationFlag.keySet()) {
5812             if ((idType & idAttestationFlags) != 0) {
5813                 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType);
5814             }
5815         }
5816 
5817         return attestationUtilsFlags;
5818     }
5819 
5820     @Override
generateKeyPair(ComponentName who, String callerPackage, String algorithm, ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags, KeymasterCertificateChain attestationChain)5821     public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
5822             ParcelableKeyGenParameterSpec parcelableKeySpec,
5823             int idAttestationFlags,
5824             KeymasterCertificateChain attestationChain) {
5825         // Get attestation flags, if any.
5826         final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags);
5827         final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
5828         final int callingUid = mInjector.binderGetCallingUid();
5829 
5830         if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) {
5831             enforceCallerCanRequestDeviceIdAttestation(who, callerPackage, callingUid);
5832         } else {
5833             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5834                     DELEGATION_CERT_INSTALL);
5835         }
5836         final KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
5837         final String alias = keySpec.getKeystoreAlias();
5838         if (TextUtils.isEmpty(alias)) {
5839             throw new IllegalArgumentException("Empty alias provided.");
5840         }
5841         // As the caller will be granted access to the key, ensure no UID was specified, as
5842         // it will not have the desired effect.
5843         if (keySpec.getUid() != KeyStore.UID_SELF) {
5844             Log.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
5845             return false;
5846         }
5847 
5848         if (deviceIdAttestationRequired && (keySpec.getAttestationChallenge() == null)) {
5849             throw new IllegalArgumentException(
5850                     "Requested Device ID attestation but challenge is empty.");
5851         }
5852 
5853         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
5854         final long id = mInjector.binderClearCallingIdentity();
5855         try {
5856             try (KeyChainConnection keyChainConnection =
5857                     KeyChain.bindAsUser(mContext, userHandle)) {
5858                 IKeyChainService keyChain = keyChainConnection.getService();
5859 
5860                 // Copy the provided keySpec, excluding the attestation challenge, which will be
5861                 // used later for requesting key attestation record.
5862                 final KeyGenParameterSpec noAttestationSpec =
5863                     new KeyGenParameterSpec.Builder(keySpec)
5864                         .setAttestationChallenge(null)
5865                         .build();
5866 
5867                 final int generationResult = keyChain.generateKeyPair(algorithm,
5868                     new ParcelableKeyGenParameterSpec(noAttestationSpec));
5869                 if (generationResult != KeyChain.KEY_GEN_SUCCESS) {
5870                     Log.e(LOG_TAG, String.format(
5871                             "KeyChain failed to generate a keypair, error %d.", generationResult));
5872                     switch (generationResult) {
5873                         case KeyChain.KEY_GEN_STRONGBOX_UNAVAILABLE:
5874                             throw new ServiceSpecificException(
5875                                     DevicePolicyManager.KEY_GEN_STRONGBOX_UNAVAILABLE,
5876                                     String.format("KeyChain error: %d", generationResult));
5877                         default:
5878                             return false;
5879                     }
5880                 }
5881 
5882                 // Set a grant for the caller here so that when the client calls
5883                 // requestPrivateKey, it will be able to get the key from Keystore.
5884                 // Note the use of the calling  UID, since the request for the private
5885                 // key will come from the client's process, so the grant has to be for
5886                 // that UID.
5887                 keyChain.setGrant(callingUid, alias, true);
5888 
5889                 final byte[] attestationChallenge = keySpec.getAttestationChallenge();
5890                 if (attestationChallenge != null) {
5891                     final int attestationResult = keyChain.attestKey(
5892                             alias, attestationChallenge, attestationUtilsFlags, attestationChain);
5893                     if (attestationResult != KeyChain.KEY_ATTESTATION_SUCCESS) {
5894                         Log.e(LOG_TAG, String.format(
5895                                 "Attestation for %s failed (rc=%d), deleting key.",
5896                                 alias, attestationResult));
5897                         keyChain.removeKeyPair(alias);
5898                         if (attestationResult == KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS) {
5899                             throw new UnsupportedOperationException(
5900                                     "Device does not support Device ID attestation.");
5901                         }
5902                         return false;
5903                     }
5904                 }
5905                 final boolean isDelegate = (who == null);
5906                 DevicePolicyEventLogger
5907                         .createEvent(DevicePolicyEnums.GENERATE_KEY_PAIR)
5908                         .setAdmin(callerPackage)
5909                         .setBoolean(isDelegate)
5910                         .setInt(idAttestationFlags)
5911                         .setStrings(algorithm)
5912                         .write();
5913                 return true;
5914             }
5915         } catch (RemoteException e) {
5916             Log.e(LOG_TAG, "KeyChain error while generating a keypair", e);
5917         } catch (InterruptedException e) {
5918             Log.w(LOG_TAG, "Interrupted while generating keypair", e);
5919             Thread.currentThread().interrupt();
5920         } finally {
5921             mInjector.binderRestoreCallingIdentity(id);
5922         }
5923         return false;
5924     }
5925 
5926     @Override
setKeyPairCertificate(ComponentName who, String callerPackage, String alias, byte[] cert, byte[] chain, boolean isUserSelectable)5927     public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias,
5928             byte[] cert, byte[] chain, boolean isUserSelectable) {
5929         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5930                 DELEGATION_CERT_INSTALL);
5931 
5932         final int callingUid = mInjector.binderGetCallingUid();
5933         final long id = mInjector.binderClearCallingIdentity();
5934         try (final KeyChainConnection keyChainConnection =
5935                 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid))) {
5936             IKeyChainService keyChain = keyChainConnection.getService();
5937             if (!keyChain.setKeyPairCertificate(alias, cert, chain)) {
5938                 return false;
5939             }
5940             keyChain.setUserSelectable(alias, isUserSelectable);
5941             final boolean isDelegate = (who == null);
5942             DevicePolicyEventLogger
5943                     .createEvent(DevicePolicyEnums.SET_KEY_PAIR_CERTIFICATE)
5944                     .setAdmin(callerPackage)
5945                     .setBoolean(isDelegate)
5946                     .write();
5947             return true;
5948         } catch (InterruptedException e) {
5949             Log.w(LOG_TAG, "Interrupted while setting keypair certificate", e);
5950             Thread.currentThread().interrupt();
5951         } catch (RemoteException e) {
5952             Log.e(LOG_TAG, "Failed setting keypair certificate", e);
5953         } finally {
5954             mInjector.binderRestoreCallingIdentity(id);
5955         }
5956         return false;
5957     }
5958 
5959     @Override
choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, final IBinder response)5960     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
5961             final IBinder response) {
5962         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
5963         if (!isCallerWithSystemUid()) {
5964             return;
5965         }
5966 
5967         final UserHandle caller = mInjector.binderGetCallingUserHandle();
5968         // If there is a profile owner, redirect to that; otherwise query the device owner.
5969         ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
5970         if (aliasChooser == null && caller.isSystem()) {
5971             synchronized (getLockObject()) {
5972                 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
5973                 if (deviceOwnerAdmin != null) {
5974                     aliasChooser = deviceOwnerAdmin.info.getComponent();
5975                 }
5976             }
5977         }
5978         if (aliasChooser == null) {
5979             sendPrivateKeyAliasResponse(null, response);
5980             return;
5981         }
5982 
5983         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
5984         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
5985         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
5986         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
5987         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
5988         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
5989 
5990         final ComponentName delegateReceiver;
5991         delegateReceiver = resolveDelegateReceiver(DELEGATION_CERT_SELECTION,
5992                 DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS, caller.getIdentifier());
5993 
5994         final boolean isDelegate;
5995         if (delegateReceiver != null) {
5996             intent.setComponent(delegateReceiver);
5997             isDelegate = true;
5998         } else {
5999             intent.setComponent(aliasChooser);
6000             isDelegate = false;
6001         }
6002 
6003         final long id = mInjector.binderClearCallingIdentity();
6004         try {
6005             mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
6006                 @Override
6007                 public void onReceive(Context context, Intent intent) {
6008                     final String chosenAlias = getResultData();
6009                     sendPrivateKeyAliasResponse(chosenAlias, response);
6010                 }
6011             }, null, Activity.RESULT_OK, null, null);
6012             DevicePolicyEventLogger
6013                     .createEvent(DevicePolicyEnums.CHOOSE_PRIVATE_KEY_ALIAS)
6014                     .setAdmin(intent.getComponent())
6015                     .setBoolean(isDelegate)
6016                     .write();
6017         } finally {
6018             mInjector.binderRestoreCallingIdentity(id);
6019         }
6020     }
6021 
sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder)6022     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
6023         final IKeyChainAliasCallback keyChainAliasResponse =
6024                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
6025         // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
6026         // is oneway, which means it won't block if the recipient lives in another process.
6027         try {
6028             keyChainAliasResponse.alias(alias);
6029         } catch (Exception e) {
6030             // Caller could throw RuntimeException or RemoteException back across processes. Catch
6031             // everything just to be sure.
6032             Log.e(LOG_TAG, "error while responding to callback", e);
6033         }
6034     }
6035 
6036     /**
6037      * Determine whether DPMS should check if a delegate package is already installed before
6038      * granting it new delegations via {@link #setDelegatedScopes}.
6039      */
shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, int targetSdk, List<String> scopes)6040     private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
6041             int targetSdk, List<String> scopes) {
6042         // 1) Never skip is installed check from N.
6043         if (targetSdk >= Build.VERSION_CODES.N) {
6044             return true;
6045         }
6046         // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
6047         if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
6048             return false;
6049         }
6050         // 3) Skip if all previously granted scopes are being cleared.
6051         if (scopes.isEmpty()) {
6052             return false;
6053         }
6054         // Otherwise it should check that delegatePackage is installed.
6055         return true;
6056     }
6057 
6058     /**
6059      * Set the scopes of a device owner or profile owner delegate.
6060      *
6061      * @param who the device owner or profile owner.
6062      * @param delegatePackage the name of the delegate package.
6063      * @param scopes the list of delegation scopes to be given to the delegate package.
6064      */
6065     @Override
setDelegatedScopes(ComponentName who, String delegatePackage, List<String> scopeList)6066     public void setDelegatedScopes(ComponentName who, String delegatePackage,
6067             List<String> scopeList) throws SecurityException {
6068         Preconditions.checkNotNull(who, "ComponentName is null");
6069         Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
6070         Preconditions.checkCollectionElementsNotNull(scopeList, "Scopes");
6071         // Remove possible duplicates.
6072         final ArrayList<String> scopes = new ArrayList(new ArraySet(scopeList));
6073         // Ensure given scopes are valid.
6074         if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
6075             throw new IllegalArgumentException("Unexpected delegation scopes");
6076         }
6077         final boolean hasDoDelegation = !Collections.disjoint(scopes, DEVICE_OWNER_DELEGATIONS);
6078         // Retrieve the user ID of the calling process.
6079         final int userId = mInjector.userHandleGetCallingUserId();
6080         synchronized (getLockObject()) {
6081             // Ensure calling process is device/profile owner.
6082             if (hasDoDelegation) {
6083                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6084             } else {
6085                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6086             }
6087             // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
6088             if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
6089                         getTargetSdk(who.getPackageName(), userId), scopes)) {
6090                 // Throw when the delegate package is not installed.
6091                 if (!isPackageInstalledForUser(delegatePackage, userId)) {
6092                     throw new IllegalArgumentException("Package " + delegatePackage
6093                             + " is not installed on the current user");
6094                 }
6095             }
6096 
6097             // Set the new delegate in user policies.
6098             final DevicePolicyData policy = getUserData(userId);
6099             List<String> exclusiveScopes = null;
6100             if (!scopes.isEmpty()) {
6101                 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
6102                 exclusiveScopes = new ArrayList<>(scopes);
6103                 exclusiveScopes.retainAll(EXCLUSIVE_DELEGATIONS);
6104             } else {
6105                 // Remove any delegation info if the given scopes list is empty.
6106                 policy.mDelegationMap.remove(delegatePackage);
6107             }
6108             sendDelegationChangedBroadcast(delegatePackage, scopes, userId);
6109 
6110             // If set, remove exclusive scopes from all other delegates
6111             if (exclusiveScopes != null && !exclusiveScopes.isEmpty()) {
6112                 for (int i = policy.mDelegationMap.size() - 1; i >= 0; --i) {
6113                     final String currentPackage = policy.mDelegationMap.keyAt(i);
6114                     final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
6115 
6116                     if (!currentPackage.equals(delegatePackage)) {
6117                         // Iterate through all other delegates
6118                         if (currentScopes.removeAll(exclusiveScopes)) {
6119                             // And if this delegate had some exclusive scopes which are now moved
6120                             // to the new delegate, notify about its delegation changes.
6121                             if (currentScopes.isEmpty()) {
6122                                 policy.mDelegationMap.removeAt(i);
6123                             }
6124                             sendDelegationChangedBroadcast(currentPackage,
6125                                     new ArrayList<>(currentScopes), userId);
6126                         }
6127                     }
6128                 }
6129             }
6130             // Persist updates.
6131             saveSettingsLocked(userId);
6132         }
6133     }
6134 
sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes, int userId)6135     private void sendDelegationChangedBroadcast(String delegatePackage, ArrayList<String> scopes,
6136             int userId) {
6137         // Notify delegate package of updates.
6138         final Intent intent = new Intent(
6139                 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
6140         // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
6141         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
6142         // Limit components this intent resolves to to the delegate package.
6143         intent.setPackage(delegatePackage);
6144         // Include the list of delegated scopes as an extra.
6145         intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, scopes);
6146         // Send the broadcast.
6147         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
6148     }
6149 
6150     /**
6151      * Get the delegation scopes given to a delegate package by a device owner or profile owner.
6152      *
6153      * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
6154      * passing in {@code null} as the {@code who} parameter and its own name as the
6155      * {@code delegatepackage}.
6156      *
6157      * @param who the device owner or profile owner, or {@code null} if the caller is
6158      *            {@code delegatePackage}.
6159      * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
6160      * @return a list of the delegation scopes currently given to {@code delegatePackage}.
6161      */
6162     @Override
6163     @NonNull
getDelegatedScopes(ComponentName who, String delegatePackage)6164     public List<String> getDelegatedScopes(ComponentName who,
6165             String delegatePackage) throws SecurityException {
6166         Preconditions.checkNotNull(delegatePackage, "Delegate package is null");
6167 
6168         // Retrieve the user ID of the calling process.
6169         final int callingUid = mInjector.binderGetCallingUid();
6170         final int userId = UserHandle.getUserId(callingUid);
6171         synchronized (getLockObject()) {
6172             // Ensure calling process is device/profile owner.
6173             if (who != null) {
6174                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6175             // Or ensure calling process is delegatePackage itself.
6176             } else {
6177                 int uid = 0;
6178                 try {
6179                   uid = mInjector.getPackageManager()
6180                           .getPackageUidAsUser(delegatePackage, userId);
6181                 } catch(NameNotFoundException e) {
6182                 }
6183                 if (uid != callingUid) {
6184                     throw new SecurityException("Caller with uid " + callingUid + " is not "
6185                             + delegatePackage);
6186                 }
6187             }
6188             final DevicePolicyData policy = getUserData(userId);
6189             // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
6190             final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
6191             return scopes == null ? Collections.EMPTY_LIST : scopes;
6192         }
6193     }
6194 
6195     /**
6196      * Get a list of  packages that were given a specific delegation scopes by a device owner or
6197      * profile owner.
6198      *
6199      * @param who the device owner or profile owner.
6200      * @param scope the scope whose delegates are to be retrieved.
6201      * @return a list of the delegate packages currently given the {@code scope} delegation.
6202      */
6203     @NonNull
getDelegatePackages(ComponentName who, String scope)6204     public List<String> getDelegatePackages(ComponentName who, String scope)
6205             throws SecurityException {
6206         Preconditions.checkNotNull(who, "ComponentName is null");
6207         Preconditions.checkNotNull(scope, "Scope is null");
6208         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
6209             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
6210         }
6211 
6212         // Retrieve the user ID of the calling process.
6213         final int userId = mInjector.userHandleGetCallingUserId();
6214         synchronized (getLockObject()) {
6215             // Ensure calling process is device/profile owner.
6216             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6217             return getDelegatePackagesInternalLocked(scope, userId);
6218         }
6219     }
6220 
getDelegatePackagesInternalLocked(String scope, int userId)6221     private List<String> getDelegatePackagesInternalLocked(String scope, int userId) {
6222         final DevicePolicyData policy = getUserData(userId);
6223 
6224         // Create a list to hold the resulting delegate packages.
6225         final List<String> delegatePackagesWithScope = new ArrayList<>();
6226         // Add all delegations containing scope to the result list.
6227         for (int i = 0; i < policy.mDelegationMap.size(); i++) {
6228             if (policy.mDelegationMap.valueAt(i).contains(scope)) {
6229                 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
6230             }
6231         }
6232         return delegatePackagesWithScope;
6233     }
6234 
6235     /**
6236      * Return the ComponentName of the receiver that handles the given broadcast action, from
6237      * the app that holds the given delegation capability. If the app defines multiple receivers
6238      * with the same intent action filter, will return any one of them nondeterministically.
6239      *
6240      * @return ComponentName of the receiver or {@null} if none exists.
6241      */
resolveDelegateReceiver(String scope, String action, int userId)6242     private ComponentName resolveDelegateReceiver(String scope, String action, int userId) {
6243 
6244         final List<String> delegates;
6245         synchronized (getLockObject()) {
6246             delegates = getDelegatePackagesInternalLocked(scope, userId);
6247         }
6248         if (delegates.size() == 0) {
6249             return null;
6250         } else if (delegates.size() > 1) {
6251             Slog.wtf(LOG_TAG, "More than one delegate holds " + scope);
6252             return null;
6253         }
6254         final String pkg = delegates.get(0);
6255         Intent intent = new Intent(action);
6256         intent.setPackage(pkg);
6257         final List<ResolveInfo> receivers;
6258         try {
6259             receivers = mIPackageManager.queryIntentReceivers(
6260                     intent, null, 0, userId).getList();
6261         } catch (RemoteException e) {
6262             return null;
6263         }
6264         final int count = receivers.size();
6265         if (count >= 1) {
6266             if (count > 1) {
6267                 Slog.w(LOG_TAG, pkg + " defines more than one delegate receiver for " + action);
6268             }
6269             return receivers.get(0).activityInfo.getComponentName();
6270         } else {
6271             return null;
6272         }
6273     }
6274 
6275     /**
6276      * Check whether a caller application has been delegated a given scope via
6277      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
6278      * device owner.
6279      * <p>
6280      * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
6281      * then comparing the calling UID with the UID of {@code callerPackage} as reported by
6282      * {@link PackageManager#getPackageUidAsUser}.
6283      *
6284      * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
6285      * @param scope the delegation scope to be checked.
6286      * @return {@code true} if the calling process is a delegate of {@code scope}.
6287      */
isCallerDelegate(String callerPackage, int callerUid, String scope)6288     private boolean isCallerDelegate(String callerPackage, int callerUid, String scope) {
6289         Preconditions.checkNotNull(callerPackage, "callerPackage is null");
6290         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
6291             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
6292         }
6293 
6294         // Retrieve the UID and user ID of the calling process.
6295         final int userId = UserHandle.getUserId(callerUid);
6296         synchronized (getLockObject()) {
6297             // Retrieve user policy data.
6298             final DevicePolicyData policy = getUserData(userId);
6299             // Retrieve the list of delegation scopes granted to callerPackage.
6300             final List<String> scopes = policy.mDelegationMap.get(callerPackage);
6301             // Check callingUid only if callerPackage has the required scope delegation.
6302             if (scopes != null && scopes.contains(scope)) {
6303                 try {
6304                     // Retrieve the expected UID for callerPackage.
6305                     final int uid = mInjector.getPackageManager()
6306                             .getPackageUidAsUser(callerPackage, userId);
6307                     // Return true if the caller is actually callerPackage.
6308                     return uid == callerUid;
6309                 } catch (NameNotFoundException e) {
6310                     // Ignore.
6311                 }
6312             }
6313             return false;
6314         }
6315     }
6316 
6317     /**
6318      * Throw a security exception if a ComponentName is given and it is not a device/profile owner
6319      * or if the calling process is not a delegate of the given scope.
6320      *
6321      * @param who the device owner of profile owner, or null if {@code callerPackage} is a
6322      *            {@code scope} delegate.
6323      * @param callerPackage the name of the calling package. Required if {@code who} is
6324      *            {@code null}.
6325      * @param reqPolicy the policy used in the API whose access permission is being checked.
6326      * @param scope the delegation scope corresponding to the API being checked.
6327      * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy};
6328      *            or when {@code who} is {@code null} and {@code callerPackage} is not a delegate
6329      *            of {@code scope}.
6330      */
enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, String scope)6331     private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy,
6332             String scope) {
6333         enforceCanManageScopeOrCheckPermission(who, callerPackage, reqPolicy, scope, null);
6334     }
6335 
6336     /**
6337      * Throw a security exception if a ComponentName is given and it is not a device/profile owner
6338      * OR if the calling process is not a delegate of the given scope and does not hold the
6339      * required permission.
6340      */
enforceCanManageScopeOrCheckPermission(@ullable ComponentName who, @NonNull String callerPackage, int reqPolicy, @NonNull String scope, @Nullable String permission)6341     private void enforceCanManageScopeOrCheckPermission(@Nullable ComponentName who,
6342             @NonNull String callerPackage, int reqPolicy, @NonNull String scope,
6343             @Nullable String permission) {
6344         // If a ComponentName is given ensure it is a device or profile owner according to policy.
6345         if (who != null) {
6346             synchronized (getLockObject()) {
6347                 getActiveAdminForCallerLocked(who, reqPolicy);
6348             }
6349         } else {
6350             // If no ComponentName is given ensure calling process has scope delegation or required
6351             // permission
6352             if (isCallerDelegate(callerPackage, mInjector.binderGetCallingUid(), scope)) {
6353                 return;
6354             }
6355             if (permission == null) {
6356                 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid()
6357                         + " is not a delegate of scope " + scope + ".");
6358             } else {
6359                 mContext.enforceCallingOrSelfPermission(permission, null);
6360             }
6361         }
6362     }
6363 
6364     /**
6365      * Helper function to preserve delegation behavior pre-O when using the deprecated functions
6366      * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
6367      */
setDelegatedScopePreO(ComponentName who, String delegatePackage, String scope)6368     private void setDelegatedScopePreO(ComponentName who,
6369             String delegatePackage, String scope) {
6370         Preconditions.checkNotNull(who, "ComponentName is null");
6371 
6372         final int userId = mInjector.userHandleGetCallingUserId();
6373         synchronized (getLockObject()) {
6374             // Ensure calling process is device/profile owner.
6375             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6376             final DevicePolicyData policy = getUserData(userId);
6377 
6378             if (delegatePackage != null) {
6379                 // Set package as a delegate for scope if it is not already one.
6380                 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
6381                 if (scopes == null) {
6382                     scopes = new ArrayList<>();
6383                 }
6384                 if (!scopes.contains(scope)) {
6385                     scopes.add(scope);
6386                     setDelegatedScopes(who, delegatePackage, scopes);
6387                 }
6388             }
6389 
6390             // Clear any existing scope delegates.
6391             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
6392                 final String currentPackage = policy.mDelegationMap.keyAt(i);
6393                 final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
6394 
6395                 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
6396                     final List<String> newScopes = new ArrayList(currentScopes);
6397                     newScopes.remove(scope);
6398                     setDelegatedScopes(who, currentPackage, newScopes);
6399                 }
6400             }
6401         }
6402     }
6403 
6404     @Override
setCertInstallerPackage(ComponentName who, String installerPackage)6405     public void setCertInstallerPackage(ComponentName who, String installerPackage)
6406             throws SecurityException {
6407         setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
6408         DevicePolicyEventLogger
6409                 .createEvent(DevicePolicyEnums.SET_CERT_INSTALLER_PACKAGE)
6410                 .setAdmin(who)
6411                 .setStrings(installerPackage)
6412                 .write();
6413     }
6414 
6415     @Override
getCertInstallerPackage(ComponentName who)6416     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
6417         final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
6418         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
6419     }
6420 
6421     /**
6422      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
6423      * not installed and therefore not available.
6424      *
6425      * @throws SecurityException if the caller is not a profile or device owner.
6426      * @throws UnsupportedOperationException if the package does not support being set as always-on.
6427      */
6428     @Override
setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown, List<String> lockdownWhitelist)6429     public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown,
6430             List<String> lockdownWhitelist)
6431             throws SecurityException {
6432         enforceProfileOrDeviceOwner(admin);
6433 
6434         final int userId = mInjector.userHandleGetCallingUserId();
6435         final long token = mInjector.binderClearCallingIdentity();
6436         try {
6437             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
6438                 Slog.w(LOG_TAG, "Non-existent VPN package specified: " + vpnPackage);
6439                 throw new ServiceSpecificException(
6440                         DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, vpnPackage);
6441             }
6442 
6443             if (vpnPackage != null && lockdown && lockdownWhitelist != null) {
6444                 for (String packageName : lockdownWhitelist) {
6445                     if (!isPackageInstalledForUser(packageName, userId)) {
6446                         Slog.w(LOG_TAG, "Non-existent package in VPN whitelist: " + packageName);
6447                         throw new ServiceSpecificException(
6448                                 DevicePolicyManager.ERROR_VPN_PACKAGE_NOT_FOUND, packageName);
6449                     }
6450                 }
6451             }
6452             // If some package is uninstalled after the check above, it will be ignored by CM.
6453             if (!mInjector.getConnectivityManager().setAlwaysOnVpnPackageForUser(
6454                     userId, vpnPackage, lockdown, lockdownWhitelist)) {
6455                 throw new UnsupportedOperationException();
6456             }
6457             DevicePolicyEventLogger
6458                     .createEvent(DevicePolicyEnums.SET_ALWAYS_ON_VPN_PACKAGE)
6459                     .setAdmin(admin)
6460                     .setStrings(vpnPackage)
6461                     .setBoolean(lockdown)
6462                     .setInt(lockdownWhitelist != null ? lockdownWhitelist.size() : 0)
6463                     .write();
6464         } finally {
6465             mInjector.binderRestoreCallingIdentity(token);
6466         }
6467         return true;
6468     }
6469 
6470     @Override
getAlwaysOnVpnPackage(ComponentName admin)6471     public String getAlwaysOnVpnPackage(ComponentName admin) throws SecurityException {
6472         enforceProfileOrDeviceOwner(admin);
6473 
6474         final int userId = mInjector.userHandleGetCallingUserId();
6475         final long token = mInjector.binderClearCallingIdentity();
6476         try {
6477             return mInjector.getConnectivityManager().getAlwaysOnVpnPackageForUser(userId);
6478         } finally {
6479             mInjector.binderRestoreCallingIdentity(token);
6480         }
6481     }
6482 
6483     @Override
isAlwaysOnVpnLockdownEnabled(ComponentName admin)6484     public boolean isAlwaysOnVpnLockdownEnabled(ComponentName admin) throws SecurityException {
6485         enforceNetworkStackOrProfileOrDeviceOwner(admin);
6486 
6487         final int userId = mInjector.userHandleGetCallingUserId();
6488         final long token = mInjector.binderClearCallingIdentity();
6489         try {
6490             return mInjector.getConnectivityManager().isVpnLockdownEnabled(userId);
6491         } finally {
6492             mInjector.binderRestoreCallingIdentity(token);
6493         }
6494     }
6495 
6496     @Override
getAlwaysOnVpnLockdownWhitelist(ComponentName admin)6497     public List<String> getAlwaysOnVpnLockdownWhitelist(ComponentName admin)
6498             throws SecurityException {
6499         enforceProfileOrDeviceOwner(admin);
6500 
6501         final int userId = mInjector.userHandleGetCallingUserId();
6502         final long token = mInjector.binderClearCallingIdentity();
6503         try {
6504             return mInjector.getConnectivityManager().getVpnLockdownWhitelist(userId);
6505         } finally {
6506             mInjector.binderRestoreCallingIdentity(token);
6507         }
6508     }
6509 
forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc)6510     private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) {
6511         wtfIfInLock();
6512         boolean success = false;
6513         try {
6514             if (wipeExtRequested) {
6515                 StorageManager sm = (StorageManager) mContext.getSystemService(
6516                     Context.STORAGE_SERVICE);
6517                 sm.wipeAdoptableDisks();
6518             }
6519             mInjector.recoverySystemRebootWipeUserData(
6520                 /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc);
6521             success = true;
6522         } catch (IOException | SecurityException e) {
6523             Slog.w(LOG_TAG, "Failed requesting data wipe", e);
6524         } finally {
6525             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
6526         }
6527     }
6528 
forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently)6529     private void forceWipeUser(int userId, String wipeReasonForUser, boolean wipeSilently) {
6530         boolean success = false;
6531         try {
6532             IActivityManager am = mInjector.getIActivityManager();
6533             if (am.getCurrentUser().id == userId) {
6534                 am.switchUser(UserHandle.USER_SYSTEM);
6535             }
6536 
6537             success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
6538             if (!success) {
6539                 Slog.w(LOG_TAG, "Couldn't remove user " + userId);
6540             } else if (isManagedProfile(userId) && !wipeSilently) {
6541                 sendWipeProfileNotification(wipeReasonForUser);
6542             }
6543         } catch (RemoteException re) {
6544             // Shouldn't happen
6545         } finally {
6546             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
6547         }
6548     }
6549 
6550     @Override
wipeDataWithReason(int flags, String wipeReasonForUser)6551     public void wipeDataWithReason(int flags, String wipeReasonForUser) {
6552         if (!mHasFeature) {
6553             return;
6554         }
6555         Preconditions.checkStringNotEmpty(wipeReasonForUser, "wipeReasonForUser is null or empty");
6556         enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId());
6557 
6558         final ActiveAdmin admin;
6559         synchronized (getLockObject()) {
6560             admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA);
6561         }
6562         DevicePolicyEventLogger
6563                 .createEvent(DevicePolicyEnums.WIPE_DATA_WITH_REASON)
6564                 .setAdmin(admin.info.getComponent())
6565                 .setInt(flags)
6566                 .write();
6567         String internalReason = "DevicePolicyManager.wipeDataWithReason() from "
6568                 + admin.info.getComponent().flattenToShortString();
6569         wipeDataNoLock(
6570                 admin.info.getComponent(), flags, internalReason, wipeReasonForUser,
6571                 admin.getUserHandle().getIdentifier());
6572     }
6573 
wipeDataNoLock(ComponentName admin, int flags, String internalReason, String wipeReasonForUser, int userId)6574     private void wipeDataNoLock(ComponentName admin, int flags, String internalReason,
6575                                 String wipeReasonForUser, int userId) {
6576         wtfIfInLock();
6577 
6578         long ident = mInjector.binderClearCallingIdentity();
6579         try {
6580             // First check whether the admin is allowed to wipe the device/user/profile.
6581             final String restriction;
6582             if (userId == UserHandle.USER_SYSTEM) {
6583                 restriction = UserManager.DISALLOW_FACTORY_RESET;
6584             } else if (isManagedProfile(userId)) {
6585                 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
6586             } else {
6587                 restriction = UserManager.DISALLOW_REMOVE_USER;
6588             }
6589             if (isAdminAffectedByRestriction(admin, restriction, userId)) {
6590                 throw new SecurityException("Cannot wipe data. " + restriction
6591                         + " restriction is set for user " + userId);
6592             }
6593 
6594             if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
6595                 if (!isDeviceOwner(admin, userId)) {
6596                     throw new SecurityException(
6597                             "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
6598                 }
6599                 PersistentDataBlockManager manager = (PersistentDataBlockManager)
6600                         mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
6601                 if (manager != null) {
6602                     manager.wipe();
6603                 }
6604             }
6605 
6606             // TODO If split user is enabled and the device owner is set in the primary user
6607             // (rather than system), we should probably trigger factory reset. Current code just
6608             // removes that user (but still clears FRP...)
6609             if (userId == UserHandle.USER_SYSTEM) {
6610                 forceWipeDeviceNoLock(/*wipeExtRequested=*/ (
6611                         flags & WIPE_EXTERNAL_STORAGE) != 0,
6612                         internalReason,
6613                         /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0);
6614             } else {
6615                 forceWipeUser(userId, wipeReasonForUser, (flags & WIPE_SILENTLY) != 0);
6616             }
6617         } finally {
6618             mInjector.binderRestoreCallingIdentity(ident);
6619         }
6620     }
6621 
sendWipeProfileNotification(String wipeReasonForUser)6622     private void sendWipeProfileNotification(String wipeReasonForUser) {
6623         Notification notification =
6624                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
6625                         .setSmallIcon(android.R.drawable.stat_sys_warning)
6626                         .setContentTitle(mContext.getString(R.string.work_profile_deleted))
6627                         .setContentText(wipeReasonForUser)
6628                         .setColor(mContext.getColor(R.color.system_notification_accent_color))
6629                         .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
6630                         .build();
6631         mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification);
6632     }
6633 
clearWipeProfileNotification()6634     private void clearWipeProfileNotification() {
6635         mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
6636     }
6637 
6638     @Override
getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle)6639     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
6640         if (!mHasFeature) {
6641             return;
6642         }
6643         enforceFullCrossUsersPermission(userHandle);
6644         mContext.enforceCallingOrSelfPermission(
6645                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6646 
6647         synchronized (getLockObject()) {
6648             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
6649             if (admin == null) {
6650                 result.sendResult(null);
6651                 return;
6652             }
6653             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
6654             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
6655             intent.setComponent(admin.info.getComponent());
6656             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
6657                     null, new BroadcastReceiver() {
6658                 @Override
6659                 public void onReceive(Context context, Intent intent) {
6660                     result.sendResult(getResultExtras(false));
6661                 }
6662             }, null, Activity.RESULT_OK, null, null);
6663         }
6664     }
6665 
6666     /**
6667      * Notify DPMS regarding the metric of the current password. This happens when the user changes
6668      * the password, but also when the user just unlocks the keyguard. In comparison,
6669      * reportPasswordChanged() is only called when the user changes the password.
6670      */
6671     @Override
setActivePasswordState(PasswordMetrics metrics, int userHandle)6672     public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
6673         if (!mLockPatternUtils.hasSecureLockScreen()) {
6674             return;
6675         }
6676         enforceFullCrossUsersPermission(userHandle);
6677         mContext.enforceCallingOrSelfPermission(
6678                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6679 
6680         // If the managed profile doesn't have a separate password, set the metrics to default
6681         if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
6682             metrics = new PasswordMetrics();
6683         }
6684 
6685         validateQualityConstant(metrics.quality);
6686         synchronized (getLockObject()) {
6687             mUserPasswordMetrics.put(userHandle, metrics);
6688         }
6689     }
6690 
6691     @Override
reportPasswordChanged(@serIdInt int userId)6692     public void reportPasswordChanged(@UserIdInt int userId) {
6693         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
6694             return;
6695         }
6696         enforceFullCrossUsersPermission(userId);
6697 
6698         // Managed Profile password can only be changed when it has a separate challenge.
6699         if (!isSeparateProfileChallengeEnabled(userId)) {
6700             enforceNotManagedProfile(userId, "set the active password");
6701         }
6702 
6703         mContext.enforceCallingOrSelfPermission(
6704                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6705 
6706         DevicePolicyData policy = getUserData(userId);
6707 
6708         long ident = mInjector.binderClearCallingIdentity();
6709         try {
6710             synchronized (getLockObject()) {
6711                 policy.mFailedPasswordAttempts = 0;
6712                 updatePasswordValidityCheckpointLocked(userId, /* parent */ false);
6713                 saveSettingsLocked(userId);
6714                 updatePasswordExpirationsLocked(userId);
6715                 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
6716 
6717                 // Send a broadcast to each profile using this password as its primary unlock.
6718                 sendAdminCommandForLockscreenPoliciesLocked(
6719                         DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
6720                         DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
6721             }
6722             removeCaApprovalsIfNeeded(userId);
6723         } finally {
6724             mInjector.binderRestoreCallingIdentity(ident);
6725         }
6726     }
6727 
6728     /**
6729      * Called any time the device password is updated. Resets all password expiration clocks.
6730      */
updatePasswordExpirationsLocked(int userHandle)6731     private void updatePasswordExpirationsLocked(int userHandle) {
6732         ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
6733         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
6734                 userHandle, /* parent */ false);
6735         final int N = admins.size();
6736         for (int i = 0; i < N; i++) {
6737             ActiveAdmin admin = admins.get(i);
6738             if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
6739                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
6740                 long timeout = admin.passwordExpirationTimeout;
6741                 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
6742                 admin.passwordExpirationDate = expiration;
6743             }
6744         }
6745         for (int affectedUserId : affectedUserIds) {
6746             saveSettingsLocked(affectedUserId);
6747         }
6748     }
6749 
6750     @Override
reportFailedPasswordAttempt(int userHandle)6751     public void reportFailedPasswordAttempt(int userHandle) {
6752         enforceFullCrossUsersPermission(userHandle);
6753         if (!isSeparateProfileChallengeEnabled(userHandle)) {
6754             enforceNotManagedProfile(userHandle,
6755                     "report failed password attempt if separate profile challenge is not in place");
6756         }
6757         mContext.enforceCallingOrSelfPermission(
6758                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6759 
6760         boolean wipeData = false;
6761         ActiveAdmin strictestAdmin = null;
6762         final long ident = mInjector.binderClearCallingIdentity();
6763         try {
6764             synchronized (getLockObject()) {
6765                 DevicePolicyData policy = getUserData(userHandle);
6766                 policy.mFailedPasswordAttempts++;
6767                 saveSettingsLocked(userHandle);
6768                 if (mHasFeature) {
6769                     strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
6770                             userHandle, /* parent */ false);
6771                     int max = strictestAdmin != null
6772                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
6773                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
6774                         wipeData = true;
6775                     }
6776 
6777                     sendAdminCommandForLockscreenPoliciesLocked(
6778                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
6779                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
6780                 }
6781             }
6782         } finally {
6783             mInjector.binderRestoreCallingIdentity(ident);
6784         }
6785 
6786         if (wipeData && strictestAdmin != null) {
6787             final int userId = strictestAdmin.getUserHandle().getIdentifier();
6788             Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
6789                     + strictestAdmin.info.getComponent().flattenToShortString()
6790                     + ". Calling wipeData for user " + userId);
6791 
6792             // Attempt to wipe the device/user/profile associated with the admin, as if the
6793             // admin had called wipeData(). That way we can check whether the admin is actually
6794             // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
6795             // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
6796             // able to do so).
6797             // IMPORTANT: Call without holding the lock to prevent deadlock.
6798             try {
6799                 String wipeReasonForUser = mContext.getString(
6800                         R.string.work_profile_deleted_reason_maximum_password_failure);
6801                 wipeDataNoLock(strictestAdmin.info.getComponent(),
6802                         /*flags=*/ 0,
6803                         /*reason=*/ "reportFailedPasswordAttempt()",
6804                         wipeReasonForUser,
6805                         userId);
6806             } catch (SecurityException e) {
6807                 Slog.w(LOG_TAG, "Failed to wipe user " + userId
6808                         + " after max failed password attempts reached.", e);
6809             }
6810         }
6811 
6812         if (mInjector.securityLogIsLoggingEnabled()) {
6813             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
6814                     /*result*/ 0, /*method strength*/ 1);
6815         }
6816     }
6817 
6818     @Override
reportSuccessfulPasswordAttempt(int userHandle)6819     public void reportSuccessfulPasswordAttempt(int userHandle) {
6820         enforceFullCrossUsersPermission(userHandle);
6821         mContext.enforceCallingOrSelfPermission(
6822                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6823 
6824         synchronized (getLockObject()) {
6825             DevicePolicyData policy = getUserData(userHandle);
6826             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
6827                 long ident = mInjector.binderClearCallingIdentity();
6828                 try {
6829                     policy.mFailedPasswordAttempts = 0;
6830                     policy.mPasswordOwner = -1;
6831                     saveSettingsLocked(userHandle);
6832                     if (mHasFeature) {
6833                         sendAdminCommandForLockscreenPoliciesLocked(
6834                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
6835                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
6836                     }
6837                 } finally {
6838                     mInjector.binderRestoreCallingIdentity(ident);
6839                 }
6840             }
6841         }
6842 
6843         if (mInjector.securityLogIsLoggingEnabled()) {
6844             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
6845                     /*method strength*/ 1);
6846         }
6847     }
6848 
6849     @Override
reportFailedBiometricAttempt(int userHandle)6850     public void reportFailedBiometricAttempt(int userHandle) {
6851         enforceFullCrossUsersPermission(userHandle);
6852         mContext.enforceCallingOrSelfPermission(
6853                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6854         if (mInjector.securityLogIsLoggingEnabled()) {
6855             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
6856                     /*method strength*/ 0);
6857         }
6858     }
6859 
6860     @Override
reportSuccessfulBiometricAttempt(int userHandle)6861     public void reportSuccessfulBiometricAttempt(int userHandle) {
6862         enforceFullCrossUsersPermission(userHandle);
6863         mContext.enforceCallingOrSelfPermission(
6864                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6865         if (mInjector.securityLogIsLoggingEnabled()) {
6866             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
6867                     /*method strength*/ 0);
6868         }
6869     }
6870 
6871     @Override
reportKeyguardDismissed(int userHandle)6872     public void reportKeyguardDismissed(int userHandle) {
6873         enforceFullCrossUsersPermission(userHandle);
6874         mContext.enforceCallingOrSelfPermission(
6875                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6876 
6877         if (mInjector.securityLogIsLoggingEnabled()) {
6878             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
6879         }
6880     }
6881 
6882     @Override
reportKeyguardSecured(int userHandle)6883     public void reportKeyguardSecured(int userHandle) {
6884         enforceFullCrossUsersPermission(userHandle);
6885         mContext.enforceCallingOrSelfPermission(
6886                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6887 
6888         if (mInjector.securityLogIsLoggingEnabled()) {
6889             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
6890         }
6891     }
6892 
6893     @Override
setGlobalProxy(ComponentName who, String proxySpec, String exclusionList)6894     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
6895             String exclusionList) {
6896         if (!mHasFeature) {
6897             return null;
6898         }
6899         synchronized (getLockObject()) {
6900             Preconditions.checkNotNull(who, "ComponentName is null");
6901 
6902             // Only check if system user has set global proxy. We don't allow other users to set it.
6903             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6904             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6905                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
6906 
6907             // Scan through active admins and find if anyone has already
6908             // set the global proxy.
6909             Set<ComponentName> compSet = policy.mAdminMap.keySet();
6910             for (ComponentName component : compSet) {
6911                 ActiveAdmin ap = policy.mAdminMap.get(component);
6912                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
6913                     // Another admin already sets the global proxy
6914                     // Return it to the caller.
6915                     return component;
6916                 }
6917             }
6918 
6919             // If the user is not system, don't set the global proxy. Fail silently.
6920             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
6921                 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
6922                         + UserHandle.getCallingUserId() + " is not permitted.");
6923                 return null;
6924             }
6925             if (proxySpec == null) {
6926                 admin.specifiesGlobalProxy = false;
6927                 admin.globalProxySpec = null;
6928                 admin.globalProxyExclusionList = null;
6929             } else {
6930 
6931                 admin.specifiesGlobalProxy = true;
6932                 admin.globalProxySpec = proxySpec;
6933                 admin.globalProxyExclusionList = exclusionList;
6934             }
6935 
6936             // Reset the global proxy accordingly
6937             // Do this using system permissions, as apps cannot write to secure settings
6938             long origId = mInjector.binderClearCallingIdentity();
6939             try {
6940                 resetGlobalProxyLocked(policy);
6941             } finally {
6942                 mInjector.binderRestoreCallingIdentity(origId);
6943             }
6944             return null;
6945         }
6946     }
6947 
6948     @Override
getGlobalProxyAdmin(int userHandle)6949     public ComponentName getGlobalProxyAdmin(int userHandle) {
6950         if (!mHasFeature) {
6951             return null;
6952         }
6953         enforceFullCrossUsersPermission(userHandle);
6954         synchronized (getLockObject()) {
6955             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6956             // Scan through active admins and find if anyone has already
6957             // set the global proxy.
6958             final int N = policy.mAdminList.size();
6959             for (int i = 0; i < N; i++) {
6960                 ActiveAdmin ap = policy.mAdminList.get(i);
6961                 if (ap.specifiesGlobalProxy) {
6962                     // Device admin sets the global proxy
6963                     // Return it to the caller.
6964                     return ap.info.getComponent();
6965                 }
6966             }
6967         }
6968         // No device admin sets the global proxy.
6969         return null;
6970     }
6971 
6972     @Override
setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo)6973     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
6974         enforceDeviceOwner(who);
6975         long token = mInjector.binderClearCallingIdentity();
6976         try {
6977             mInjector.getConnectivityManager().setGlobalProxy(proxyInfo);
6978         } finally {
6979             mInjector.binderRestoreCallingIdentity(token);
6980         }
6981     }
6982 
resetGlobalProxyLocked(DevicePolicyData policy)6983     private void resetGlobalProxyLocked(DevicePolicyData policy) {
6984         final int N = policy.mAdminList.size();
6985         for (int i = 0; i < N; i++) {
6986             ActiveAdmin ap = policy.mAdminList.get(i);
6987             if (ap.specifiesGlobalProxy) {
6988                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
6989                 return;
6990             }
6991         }
6992         // No device admins defining global proxies - reset global proxy settings to none
6993         saveGlobalProxyLocked(null, null);
6994     }
6995 
saveGlobalProxyLocked(String proxySpec, String exclusionList)6996     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
6997         if (exclusionList == null) {
6998             exclusionList = "";
6999         }
7000         if (proxySpec == null) {
7001             proxySpec = "";
7002         }
7003         // Remove white spaces
7004         proxySpec = proxySpec.trim();
7005         String data[] = proxySpec.split(":");
7006         int proxyPort = 8080;
7007         if (data.length > 1) {
7008             try {
7009                 proxyPort = Integer.parseInt(data[1]);
7010             } catch (NumberFormatException e) {}
7011         }
7012         exclusionList = exclusionList.trim();
7013 
7014         ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
7015         if (!proxyProperties.isValid()) {
7016             Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
7017             return;
7018         }
7019         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
7020         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
7021         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
7022                 exclusionList);
7023     }
7024 
7025     /**
7026      * Called by an application that is administering the device to request that the storage system
7027      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
7028      *
7029      * @return the new total request status (for all admins), or {@link
7030      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user
7031      */
7032     @Override
setStorageEncryption(ComponentName who, boolean encrypt)7033     public int setStorageEncryption(ComponentName who, boolean encrypt) {
7034         if (!mHasFeature) {
7035             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7036         }
7037         Preconditions.checkNotNull(who, "ComponentName is null");
7038         final int userHandle = UserHandle.getCallingUserId();
7039         synchronized (getLockObject()) {
7040             // Check for permissions
7041             // Only system user can set storage encryption
7042             if (userHandle != UserHandle.USER_SYSTEM) {
7043                 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
7044                         + UserHandle.getCallingUserId() + " is not permitted.");
7045                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7046             }
7047 
7048             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7049                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
7050 
7051             // Quick exit:  If the filesystem does not support encryption, we can exit early.
7052             if (!isEncryptionSupported()) {
7053                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7054             }
7055 
7056             // (1) Record the value for the admin so it's sticky
7057             if (ap.encryptionRequested != encrypt) {
7058                 ap.encryptionRequested = encrypt;
7059                 saveSettingsLocked(userHandle);
7060             }
7061 
7062             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
7063             // (2) Compute "max" for all admins
7064             boolean newRequested = false;
7065             final int N = policy.mAdminList.size();
7066             for (int i = 0; i < N; i++) {
7067                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
7068             }
7069 
7070             // Notify OS of new request
7071             setEncryptionRequested(newRequested);
7072 
7073             // Return the new global request status
7074             return newRequested
7075                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
7076                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
7077         }
7078     }
7079 
7080     /**
7081      * Get the current storage encryption request status for a given admin, or aggregate of all
7082      * active admins.
7083      */
7084     @Override
getStorageEncryption(ComponentName who, int userHandle)7085     public boolean getStorageEncryption(ComponentName who, int userHandle) {
7086         if (!mHasFeature) {
7087             return false;
7088         }
7089         enforceFullCrossUsersPermission(userHandle);
7090         synchronized (getLockObject()) {
7091             // Check for permissions if a particular caller is specified
7092             if (who != null) {
7093                 // When checking for a single caller, status is based on caller's request
7094                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
7095                 return ap != null ? ap.encryptionRequested : false;
7096             }
7097 
7098             // If no particular caller is specified, return the aggregate set of requests.
7099             // This is short circuited by returning true on the first hit.
7100             DevicePolicyData policy = getUserData(userHandle);
7101             final int N = policy.mAdminList.size();
7102             for (int i = 0; i < N; i++) {
7103                 if (policy.mAdminList.get(i).encryptionRequested) {
7104                     return true;
7105                 }
7106             }
7107             return false;
7108         }
7109     }
7110 
7111     /**
7112      * Get the current encryption status of the device.
7113      */
7114     @Override
getStorageEncryptionStatus(@ullable String callerPackage, int userHandle)7115     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
7116         if (!mHasFeature) {
7117             // Ok to return current status.
7118         }
7119         enforceFullCrossUsersPermission(userHandle);
7120 
7121         // It's not critical here, but let's make sure the package name is correct, in case
7122         // we start using it for different purposes.
7123         ensureCallerPackage(callerPackage);
7124 
7125         final ApplicationInfo ai;
7126         try {
7127             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
7128         } catch (RemoteException e) {
7129             throw new SecurityException(e);
7130         }
7131 
7132         boolean legacyApp = false;
7133         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
7134             legacyApp = true;
7135         }
7136 
7137         final int rawStatus = getEncryptionStatus();
7138         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
7139             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
7140         }
7141         return rawStatus;
7142     }
7143 
7144     /**
7145      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
7146      */
isEncryptionSupported()7147     private boolean isEncryptionSupported() {
7148         // Note, this can be implemented as
7149         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7150         // But is provided as a separate internal method if there's a faster way to do a
7151         // simple check for supported-or-not.
7152         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7153     }
7154 
7155     /**
7156      * Hook to low-levels:  Reporting the current status of encryption.
7157      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
7158      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
7159      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
7160      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
7161      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
7162      */
getEncryptionStatus()7163     private int getEncryptionStatus() {
7164         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
7165             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
7166         } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
7167             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
7168         } else if (mInjector.storageManagerIsEncrypted()) {
7169             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
7170         } else if (mInjector.storageManagerIsEncryptable()) {
7171             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
7172         } else {
7173             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
7174         }
7175     }
7176 
7177     /**
7178      * Hook to low-levels:  If needed, record the new admin setting for encryption.
7179      */
setEncryptionRequested(boolean encrypt)7180     private void setEncryptionRequested(boolean encrypt) {
7181     }
7182 
7183     /**
7184      * Set whether the screen capture is disabled for the user managed by the specified admin.
7185      */
7186     @Override
setScreenCaptureDisabled(ComponentName who, boolean disabled)7187     public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
7188         if (!mHasFeature) {
7189             return;
7190         }
7191         Preconditions.checkNotNull(who, "ComponentName is null");
7192         final int userHandle = UserHandle.getCallingUserId();
7193         synchronized (getLockObject()) {
7194             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7195                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7196             if (ap.disableScreenCapture != disabled) {
7197                 ap.disableScreenCapture = disabled;
7198                 saveSettingsLocked(userHandle);
7199                 updateScreenCaptureDisabled(userHandle, disabled);
7200             }
7201         }
7202         DevicePolicyEventLogger
7203                 .createEvent(DevicePolicyEnums.SET_SCREEN_CAPTURE_DISABLED)
7204                 .setAdmin(who)
7205                 .setBoolean(disabled)
7206                 .write();
7207     }
7208 
7209     /**
7210      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
7211      * active admin (if given admin is null).
7212      */
7213     @Override
getScreenCaptureDisabled(ComponentName who, int userHandle)7214     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
7215         if (!mHasFeature) {
7216             return false;
7217         }
7218         synchronized (getLockObject()) {
7219             if (who != null) {
7220                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7221                 return (admin != null) ? admin.disableScreenCapture : false;
7222             }
7223 
7224             DevicePolicyData policy = getUserData(userHandle);
7225             final int N = policy.mAdminList.size();
7226             for (int i = 0; i < N; i++) {
7227                 ActiveAdmin admin = policy.mAdminList.get(i);
7228                 if (admin.disableScreenCapture) {
7229                     return true;
7230                 }
7231             }
7232             return false;
7233         }
7234     }
7235 
updateScreenCaptureDisabled(int userHandle, boolean disabled)7236     private void updateScreenCaptureDisabled(int userHandle, boolean disabled) {
7237         mPolicyCache.setScreenCaptureDisabled(userHandle, disabled);
7238         mHandler.post(new Runnable() {
7239             @Override
7240             public void run() {
7241                 try {
7242                     mInjector.getIWindowManager().refreshScreenCaptureDisabled(userHandle);
7243                 } catch (RemoteException e) {
7244                     Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
7245                 }
7246             }
7247         });
7248     }
7249 
7250     /**
7251      * Set whether auto time is required by the specified admin (must be device or profile owner).
7252      */
7253     @Override
setAutoTimeRequired(ComponentName who, boolean required)7254     public void setAutoTimeRequired(ComponentName who, boolean required) {
7255         if (!mHasFeature) {
7256             return;
7257         }
7258         Preconditions.checkNotNull(who, "ComponentName is null");
7259         final int userHandle = UserHandle.getCallingUserId();
7260         synchronized (getLockObject()) {
7261             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7262                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7263             if (admin.requireAutoTime != required) {
7264                 admin.requireAutoTime = required;
7265                 saveSettingsLocked(userHandle);
7266             }
7267         }
7268 
7269         // Turn AUTO_TIME on in settings if it is required
7270         if (required) {
7271             long ident = mInjector.binderClearCallingIdentity();
7272             try {
7273                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
7274             } finally {
7275                 mInjector.binderRestoreCallingIdentity(ident);
7276             }
7277         }
7278         DevicePolicyEventLogger
7279                 .createEvent(DevicePolicyEnums.SET_AUTO_TIME_REQUIRED)
7280                 .setAdmin(who)
7281                 .setBoolean(required)
7282                 .write();
7283     }
7284 
7285     /**
7286      * Returns whether or not auto time is required by the device owner or any profile owner.
7287      */
7288     @Override
getAutoTimeRequired()7289     public boolean getAutoTimeRequired() {
7290         if (!mHasFeature) {
7291             return false;
7292         }
7293         synchronized (getLockObject()) {
7294             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7295             if (deviceOwner != null && deviceOwner.requireAutoTime) {
7296                 // If the device owner enforces auto time, we don't need to check the PO's
7297                 return true;
7298             }
7299 
7300             // Now check to see if any profile owner on any user enforces auto time
7301             for (Integer userId : mOwners.getProfileOwnerKeys()) {
7302                 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7303                 if (profileOwner != null && profileOwner.requireAutoTime) {
7304                     return true;
7305                 }
7306             }
7307 
7308             return false;
7309         }
7310     }
7311 
7312     @Override
setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers)7313     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
7314         if (!mHasFeature) {
7315             return;
7316         }
7317         Preconditions.checkNotNull(who, "ComponentName is null");
7318         // Allow setting this policy to true only if there is a split system user.
7319         if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
7320             throw new UnsupportedOperationException(
7321                     "Cannot force ephemeral users on systems without split system user.");
7322         }
7323         boolean removeAllUsers = false;
7324         synchronized (getLockObject()) {
7325             final ActiveAdmin deviceOwner =
7326                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7327             if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
7328                 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
7329                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7330                 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
7331                 removeAllUsers = forceEphemeralUsers;
7332             }
7333         }
7334         if (removeAllUsers) {
7335             long identitity = mInjector.binderClearCallingIdentity();
7336             try {
7337                 mUserManagerInternal.removeAllUsers();
7338             } finally {
7339                 mInjector.binderRestoreCallingIdentity(identitity);
7340             }
7341         }
7342     }
7343 
7344     @Override
getForceEphemeralUsers(ComponentName who)7345     public boolean getForceEphemeralUsers(ComponentName who) {
7346         if (!mHasFeature) {
7347             return false;
7348         }
7349         Preconditions.checkNotNull(who, "ComponentName is null");
7350         synchronized (getLockObject()) {
7351             final ActiveAdmin deviceOwner =
7352                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7353             return deviceOwner.forceEphemeralUsers;
7354         }
7355     }
7356 
ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who)7357     private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who)
7358             throws SecurityException {
7359         synchronized (getLockObject()) {
7360             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7361         }
7362         ensureAllUsersAffiliated();
7363     }
7364 
ensureAllUsersAffiliated()7365     private void ensureAllUsersAffiliated() throws SecurityException {
7366         synchronized (getLockObject()) {
7367             if (!areAllUsersAffiliatedWithDeviceLocked()) {
7368                 throw new SecurityException("Not all users are affiliated.");
7369             }
7370         }
7371     }
7372 
7373     @Override
requestBugreport(ComponentName who)7374     public boolean requestBugreport(ComponentName who) {
7375         if (!mHasFeature) {
7376             return false;
7377         }
7378         Preconditions.checkNotNull(who, "ComponentName is null");
7379 
7380         // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
7381         // which could still contain data related to that user. Should we disallow that, e.g. until
7382         // next boot? Might not be needed given that this still requires user consent.
7383         ensureDeviceOwnerAndAllUsersAffiliated(who);
7384 
7385         if (mRemoteBugreportServiceIsActive.get()
7386                 || (getDeviceOwnerRemoteBugreportUri() != null)) {
7387             Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
7388             return false;
7389         }
7390 
7391         final long currentTime = System.currentTimeMillis();
7392         synchronized (getLockObject()) {
7393             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
7394             if (currentTime > policyData.mLastBugReportRequestTime) {
7395                 policyData.mLastBugReportRequestTime = currentTime;
7396                 saveSettingsLocked(UserHandle.USER_SYSTEM);
7397             }
7398         }
7399 
7400         final long callingIdentity = mInjector.binderClearCallingIdentity();
7401         try {
7402             mInjector.getIActivityManager().requestBugReport(
7403                     ActivityManager.BUGREPORT_OPTION_REMOTE);
7404 
7405             mRemoteBugreportServiceIsActive.set(true);
7406             mRemoteBugreportSharingAccepted.set(false);
7407             registerRemoteBugreportReceivers();
7408             mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
7409                     RemoteBugreportUtils.NOTIFICATION_ID,
7410                     RemoteBugreportUtils.buildNotification(mContext,
7411                             DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
7412             mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
7413                     RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
7414             DevicePolicyEventLogger
7415                     .createEvent(DevicePolicyEnums.REQUEST_BUGREPORT)
7416                     .setAdmin(who)
7417                     .write();
7418             return true;
7419         } catch (RemoteException re) {
7420             // should never happen
7421             Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
7422             return false;
7423         } finally {
7424             mInjector.binderRestoreCallingIdentity(callingIdentity);
7425         }
7426     }
7427 
sendDeviceOwnerCommand(String action, Bundle extras)7428     void sendDeviceOwnerCommand(String action, Bundle extras) {
7429         final int deviceOwnerUserId;
7430         synchronized (getLockObject()) {
7431             deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
7432         }
7433 
7434         ComponentName receiverComponent = null;
7435         if (action.equals(DeviceAdminReceiver.ACTION_NETWORK_LOGS_AVAILABLE)) {
7436             receiverComponent = resolveDelegateReceiver(DELEGATION_NETWORK_LOGGING, action,
7437                     deviceOwnerUserId);
7438         }
7439         if (receiverComponent == null) {
7440             synchronized (getLockObject()) {
7441                 receiverComponent = mOwners.getDeviceOwnerComponent();
7442             }
7443         }
7444         sendActiveAdminCommand(action, extras, deviceOwnerUserId, receiverComponent);
7445     }
7446 
sendProfileOwnerCommand(String action, Bundle extras, int userHandle)7447     private void sendProfileOwnerCommand(String action, Bundle extras, int userHandle) {
7448         sendActiveAdminCommand(action, extras, userHandle,
7449                 mOwners.getProfileOwnerComponent(userHandle));
7450     }
7451 
sendActiveAdminCommand(String action, Bundle extras, int userHandle, ComponentName receiverComponent)7452     private void sendActiveAdminCommand(String action, Bundle extras,
7453             int userHandle, ComponentName receiverComponent) {
7454         final Intent intent = new Intent(action);
7455         intent.setComponent(receiverComponent);
7456         if (extras != null) {
7457             intent.putExtras(extras);
7458         }
7459         mContext.sendBroadcastAsUser(intent, UserHandle.of(userHandle));
7460     }
7461 
sendOwnerChangedBroadcast(String broadcast, int userId)7462     private void sendOwnerChangedBroadcast(String broadcast, int userId) {
7463         final Intent intent = new Intent(broadcast)
7464                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
7465         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
7466     }
7467 
getDeviceOwnerRemoteBugreportUri()7468     private String getDeviceOwnerRemoteBugreportUri() {
7469         synchronized (getLockObject()) {
7470             return mOwners.getDeviceOwnerRemoteBugreportUri();
7471         }
7472     }
7473 
setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash)7474     private void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
7475             String bugreportHash) {
7476         synchronized (getLockObject()) {
7477             mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
7478         }
7479     }
7480 
registerRemoteBugreportReceivers()7481     private void registerRemoteBugreportReceivers() {
7482         try {
7483             IntentFilter filterFinished = new IntentFilter(
7484                     DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
7485                     RemoteBugreportUtils.BUGREPORT_MIMETYPE);
7486             mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
7487         } catch (IntentFilter.MalformedMimeTypeException e) {
7488             // should never happen, as setting a constant
7489             Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
7490         }
7491         IntentFilter filterConsent = new IntentFilter();
7492         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
7493         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
7494         mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
7495     }
7496 
onBugreportFinished(Intent intent)7497     private void onBugreportFinished(Intent intent) {
7498         mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
7499         mRemoteBugreportServiceIsActive.set(false);
7500         Uri bugreportUri = intent.getData();
7501         String bugreportUriString = null;
7502         if (bugreportUri != null) {
7503             bugreportUriString = bugreportUri.toString();
7504         }
7505         String bugreportHash = intent.getStringExtra(
7506                 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
7507         if (mRemoteBugreportSharingAccepted.get()) {
7508             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
7509             mInjector.getNotificationManager().cancel(LOG_TAG,
7510                     RemoteBugreportUtils.NOTIFICATION_ID);
7511         } else {
7512             setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
7513             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
7514                     RemoteBugreportUtils.buildNotification(mContext,
7515                             DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
7516                             UserHandle.ALL);
7517         }
7518         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
7519     }
7520 
onBugreportFailed()7521     private void onBugreportFailed() {
7522         mRemoteBugreportServiceIsActive.set(false);
7523         mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
7524                 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
7525         mRemoteBugreportSharingAccepted.set(false);
7526         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
7527         mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
7528         Bundle extras = new Bundle();
7529         extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
7530                 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
7531         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
7532         mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
7533         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
7534     }
7535 
onBugreportSharingAccepted()7536     private void onBugreportSharingAccepted() {
7537         mRemoteBugreportSharingAccepted.set(true);
7538         String bugreportUriString = null;
7539         String bugreportHash = null;
7540         synchronized (getLockObject()) {
7541             bugreportUriString = getDeviceOwnerRemoteBugreportUri();
7542             bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
7543         }
7544         if (bugreportUriString != null) {
7545             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
7546         } else if (mRemoteBugreportServiceIsActive.get()) {
7547             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
7548                     RemoteBugreportUtils.buildNotification(mContext,
7549                             DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
7550                             UserHandle.ALL);
7551         }
7552     }
7553 
onBugreportSharingDeclined()7554     private void onBugreportSharingDeclined() {
7555         if (mRemoteBugreportServiceIsActive.get()) {
7556             mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
7557                     RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
7558             mRemoteBugreportServiceIsActive.set(false);
7559             mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
7560             mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
7561         }
7562         mRemoteBugreportSharingAccepted.set(false);
7563         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
7564         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
7565     }
7566 
shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, String bugreportHash)7567     private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
7568             String bugreportHash) {
7569         ParcelFileDescriptor pfd = null;
7570         try {
7571             if (bugreportUriString == null) {
7572                 throw new FileNotFoundException();
7573             }
7574             Uri bugreportUri = Uri.parse(bugreportUriString);
7575             pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
7576 
7577             synchronized (getLockObject()) {
7578                 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
7579                 intent.setComponent(mOwners.getDeviceOwnerComponent());
7580                 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
7581                 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
7582                 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7583 
7584                 LocalServices.getService(UriGrantsManagerInternal.class)
7585                         .grantUriPermissionFromIntent(Process.SHELL_UID,
7586                                 mOwners.getDeviceOwnerComponent().getPackageName(),
7587                                 intent, mOwners.getDeviceOwnerUserId());
7588                 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
7589             }
7590         } catch (FileNotFoundException e) {
7591             Bundle extras = new Bundle();
7592             extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
7593                     DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
7594             sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
7595         } finally {
7596             try {
7597                 if (pfd != null) {
7598                     pfd.close();
7599                 }
7600             } catch (IOException ex) {
7601                 // Ignore
7602             }
7603             mRemoteBugreportSharingAccepted.set(false);
7604             setDeviceOwnerRemoteBugreportUriAndHash(null, null);
7605         }
7606     }
7607 
7608     /**
7609      * Disables all device cameras according to the specified admin.
7610      */
7611     @Override
setCameraDisabled(ComponentName who, boolean disabled)7612     public void setCameraDisabled(ComponentName who, boolean disabled) {
7613         if (!mHasFeature) {
7614             return;
7615         }
7616         Preconditions.checkNotNull(who, "ComponentName is null");
7617         final int userHandle = mInjector.userHandleGetCallingUserId();
7618         synchronized (getLockObject()) {
7619             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7620                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
7621             if (ap.disableCamera != disabled) {
7622                 ap.disableCamera = disabled;
7623                 saveSettingsLocked(userHandle);
7624             }
7625         }
7626         // Tell the user manager that the restrictions have changed.
7627         pushUserRestrictions(userHandle);
7628         DevicePolicyEventLogger
7629                 .createEvent(DevicePolicyEnums.SET_CAMERA_DISABLED)
7630                 .setAdmin(who)
7631                 .setBoolean(disabled)
7632                 .write();
7633     }
7634 
7635     /**
7636      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
7637      * active admins.
7638      */
7639     @Override
getCameraDisabled(ComponentName who, int userHandle)7640     public boolean getCameraDisabled(ComponentName who, int userHandle) {
7641         return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
7642     }
7643 
getCameraDisabled(ComponentName who, int userHandle, boolean mergeDeviceOwnerRestriction)7644     private boolean getCameraDisabled(ComponentName who, int userHandle,
7645             boolean mergeDeviceOwnerRestriction) {
7646         if (!mHasFeature) {
7647             return false;
7648         }
7649         synchronized (getLockObject()) {
7650             if (who != null) {
7651                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7652                 return (admin != null) ? admin.disableCamera : false;
7653             }
7654             // First, see if DO has set it.  If so, it's device-wide.
7655             if (mergeDeviceOwnerRestriction) {
7656                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7657                 if (deviceOwner != null && deviceOwner.disableCamera) {
7658                     return true;
7659                 }
7660             }
7661 
7662             // Then check each device admin on the user.
7663             DevicePolicyData policy = getUserData(userHandle);
7664             // Determine whether or not the device camera is disabled for any active admins.
7665             final int N = policy.mAdminList.size();
7666             for (int i = 0; i < N; i++) {
7667                 ActiveAdmin admin = policy.mAdminList.get(i);
7668                 if (admin.disableCamera) {
7669                     return true;
7670                 }
7671             }
7672             return false;
7673         }
7674     }
7675 
7676     @Override
setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent)7677     public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
7678         if (!mHasFeature) {
7679             return;
7680         }
7681         Preconditions.checkNotNull(who, "ComponentName is null");
7682         final int userHandle = mInjector.userHandleGetCallingUserId();
7683         if (isManagedProfile(userHandle)) {
7684             if (parent) {
7685                 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
7686             } else {
7687                 which = which & PROFILE_KEYGUARD_FEATURES;
7688             }
7689         }
7690         synchronized (getLockObject()) {
7691             ActiveAdmin ap = getActiveAdminForCallerLocked(
7692                     who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
7693             if (ap.disabledKeyguardFeatures != which) {
7694                 ap.disabledKeyguardFeatures = which;
7695                 saveSettingsLocked(userHandle);
7696             }
7697         }
7698         if (SecurityLog.isLoggingEnabled()) {
7699             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
7700             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET,
7701                     who.getPackageName(), userHandle, affectedUserId, which);
7702         }
7703         DevicePolicyEventLogger
7704                 .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED_FEATURES)
7705                 .setAdmin(who)
7706                 .setInt(which)
7707                 .setBoolean(parent)
7708                 .write();
7709     }
7710 
7711     /**
7712      * Gets the disabled state for features in keyguard for the given admin,
7713      * or the aggregate of all active admins if who is null.
7714      */
7715     @Override
getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent)7716     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
7717         if (!mHasFeature) {
7718             return 0;
7719         }
7720         enforceFullCrossUsersPermission(userHandle);
7721         final long ident = mInjector.binderClearCallingIdentity();
7722         try {
7723             synchronized (getLockObject()) {
7724                 if (who != null) {
7725                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
7726                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
7727                 }
7728 
7729                 final List<ActiveAdmin> admins;
7730                 if (!parent && isManagedProfile(userHandle)) {
7731                     // If we are being asked about a managed profile, just return keyguard features
7732                     // disabled by admins in the profile.
7733                     admins = getUserDataUnchecked(userHandle).mAdminList;
7734                 } else {
7735                     // Otherwise return those set by admins in the user and its profiles.
7736                     admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
7737                 }
7738 
7739                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
7740                 final int N = admins.size();
7741                 for (int i = 0; i < N; i++) {
7742                     ActiveAdmin admin = admins.get(i);
7743                     int userId = admin.getUserHandle().getIdentifier();
7744                     boolean isRequestedUser = !parent && (userId == userHandle);
7745                     if (isRequestedUser || !isManagedProfile(userId)) {
7746                         // If we are being asked explicitly about this user
7747                         // return all disabled features even if its a managed profile.
7748                         which |= admin.disabledKeyguardFeatures;
7749                     } else {
7750                         // Otherwise a managed profile is only allowed to disable
7751                         // some features on the parent user.
7752                         which |= (admin.disabledKeyguardFeatures
7753                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
7754                     }
7755                 }
7756                 return which;
7757             }
7758         } finally {
7759             mInjector.binderRestoreCallingIdentity(ident);
7760         }
7761     }
7762 
7763     @Override
setKeepUninstalledPackages(ComponentName who, String callerPackage, List<String> packageList)7764     public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
7765             List<String> packageList) {
7766         if (!mHasFeature) {
7767             return;
7768         }
7769         Preconditions.checkNotNull(packageList, "packageList is null");
7770         final int userHandle = UserHandle.getCallingUserId();
7771         synchronized (getLockObject()) {
7772             // Ensure the caller is a DO or a keep uninstalled packages delegate.
7773             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7774                     DELEGATION_KEEP_UNINSTALLED_PACKAGES);
7775             // Get the device owner
7776             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7777             // Set list of packages to be kept even if uninstalled.
7778             deviceOwner.keepUninstalledPackages = packageList;
7779             // Save settings.
7780             saveSettingsLocked(userHandle);
7781             // Notify package manager.
7782             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
7783         }
7784         final boolean isDelegate = (who == null);
7785         DevicePolicyEventLogger
7786                 .createEvent(DevicePolicyEnums.SET_KEEP_UNINSTALLED_PACKAGES)
7787                 .setAdmin(callerPackage)
7788                 .setBoolean(isDelegate)
7789                 .setStrings(packageList.toArray(new String[0]))
7790                 .write();
7791     }
7792 
7793     @Override
getKeepUninstalledPackages(ComponentName who, String callerPackage)7794     public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
7795         if (!mHasFeature) {
7796             return null;
7797         }
7798         // TODO In split system user mode, allow apps on user 0 to query the list
7799         synchronized (getLockObject()) {
7800             // Ensure the caller is a DO or a keep uninstalled packages delegate.
7801             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7802                     DELEGATION_KEEP_UNINSTALLED_PACKAGES);
7803             return getKeepUninstalledPackagesLocked();
7804         }
7805     }
7806 
getKeepUninstalledPackagesLocked()7807     private List<String> getKeepUninstalledPackagesLocked() {
7808         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7809         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
7810     }
7811 
7812     @Override
setDeviceOwner(ComponentName admin, String ownerName, int userId)7813     public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
7814         if (!mHasFeature) {
7815             return false;
7816         }
7817         if (admin == null
7818                 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
7819             throw new IllegalArgumentException("Invalid component " + admin
7820                     + " for device owner");
7821         }
7822         final boolean hasIncompatibleAccountsOrNonAdb =
7823                 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
7824         synchronized (getLockObject()) {
7825             enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
7826             final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
7827             if (activeAdmin == null
7828                     || getUserData(userId).mRemovingAdmins.contains(admin)) {
7829                 throw new IllegalArgumentException("Not active admin: " + admin);
7830             }
7831 
7832             // Shutting down backup manager service permanently.
7833             toggleBackupServiceActive(UserHandle.USER_SYSTEM, /* makeActive= */ false);
7834             if (isAdb()) {
7835                 // Log device owner provisioning was started using adb.
7836                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
7837                 DevicePolicyEventLogger
7838                         .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
7839                         .setAdmin(admin)
7840                         .setStrings(LOG_TAG_DEVICE_OWNER)
7841                         .write();
7842             }
7843 
7844             mOwners.setDeviceOwner(admin, ownerName, userId);
7845             mOwners.writeDeviceOwner();
7846             updateDeviceOwnerLocked();
7847             setDeviceOwnerSystemPropertyLocked();
7848 
7849             final Set<String> restrictions =
7850                     UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
7851             if (!restrictions.isEmpty()) {
7852                 for (String restriction : restrictions) {
7853                     activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
7854                 }
7855                 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
7856                 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
7857 
7858                 saveUserRestrictionsLocked(userId);
7859             }
7860 
7861             long ident = mInjector.binderClearCallingIdentity();
7862             try {
7863                 // TODO Send to system too?
7864                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId);
7865             } finally {
7866                 mInjector.binderRestoreCallingIdentity(ident);
7867             }
7868             mDeviceAdminServiceController.startServiceForOwner(
7869                     admin.getPackageName(), userId, "set-device-owner");
7870 
7871             Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
7872             return true;
7873         }
7874     }
7875 
7876     @Override
hasDeviceOwner()7877     public boolean hasDeviceOwner() {
7878         enforceDeviceOwnerOrManageUsers();
7879         return mOwners.hasDeviceOwner();
7880     }
7881 
isDeviceOwner(ActiveAdmin admin)7882     boolean isDeviceOwner(ActiveAdmin admin) {
7883         return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
7884     }
7885 
isDeviceOwner(ComponentName who, int userId)7886     public boolean isDeviceOwner(ComponentName who, int userId) {
7887         synchronized (getLockObject()) {
7888             return mOwners.hasDeviceOwner()
7889                     && mOwners.getDeviceOwnerUserId() == userId
7890                     && mOwners.getDeviceOwnerComponent().equals(who);
7891         }
7892     }
7893 
isDeviceOwnerPackage(String packageName, int userId)7894     private boolean isDeviceOwnerPackage(String packageName, int userId) {
7895         synchronized (getLockObject()) {
7896             return mOwners.hasDeviceOwner()
7897                     && mOwners.getDeviceOwnerUserId() == userId
7898                     && mOwners.getDeviceOwnerPackageName().equals(packageName);
7899         }
7900     }
7901 
isProfileOwnerPackage(String packageName, int userId)7902     private boolean isProfileOwnerPackage(String packageName, int userId) {
7903         synchronized (getLockObject()) {
7904             return mOwners.hasProfileOwner(userId)
7905                     && mOwners.getProfileOwnerPackage(userId).equals(packageName);
7906         }
7907     }
7908 
isProfileOwner(ComponentName who, int userId)7909     public boolean isProfileOwner(ComponentName who, int userId) {
7910         final ComponentName profileOwner = getProfileOwner(userId);
7911         return who != null && who.equals(profileOwner);
7912     }
7913 
hasProfileOwner(int userId)7914     private boolean hasProfileOwner(int userId) {
7915         synchronized (getLockObject()) {
7916             return mOwners.hasProfileOwner(userId);
7917         }
7918     }
7919 
canProfileOwnerAccessDeviceIds(int userId)7920     private boolean canProfileOwnerAccessDeviceIds(int userId) {
7921         synchronized (getLockObject()) {
7922             return mOwners.canProfileOwnerAccessDeviceIds(userId);
7923         }
7924     }
7925 
7926     @Override
getDeviceOwnerComponent(boolean callingUserOnly)7927     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
7928         if (!mHasFeature) {
7929             return null;
7930         }
7931         if (!callingUserOnly) {
7932             enforceManageUsers();
7933         }
7934         synchronized (getLockObject()) {
7935             if (!mOwners.hasDeviceOwner()) {
7936                 return null;
7937             }
7938             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
7939                     mOwners.getDeviceOwnerUserId()) {
7940                 return null;
7941             }
7942             return mOwners.getDeviceOwnerComponent();
7943         }
7944     }
7945 
7946     @Override
getDeviceOwnerUserId()7947     public int getDeviceOwnerUserId() {
7948         if (!mHasFeature) {
7949             return UserHandle.USER_NULL;
7950         }
7951         enforceManageUsers();
7952         synchronized (getLockObject()) {
7953             return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
7954         }
7955     }
7956 
7957     /**
7958      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
7959      * MANAGE_USERS.
7960      */
7961     @Override
getDeviceOwnerName()7962     public String getDeviceOwnerName() {
7963         if (!mHasFeature) {
7964             return null;
7965         }
7966         enforceManageUsers();
7967         synchronized (getLockObject()) {
7968             if (!mOwners.hasDeviceOwner()) {
7969                 return null;
7970             }
7971             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
7972             // Should setDeviceOwner/ProfileOwner still take a name?
7973             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
7974             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
7975         }
7976     }
7977 
7978     /** Returns the active device owner or {@code null} if there is no device owner. */
7979     @VisibleForTesting
getDeviceOwnerAdminLocked()7980     ActiveAdmin getDeviceOwnerAdminLocked() {
7981         ensureLocked();
7982         ComponentName component = mOwners.getDeviceOwnerComponent();
7983         if (component == null) {
7984             return null;
7985         }
7986 
7987         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
7988         final int n = policy.mAdminList.size();
7989         for (int i = 0; i < n; i++) {
7990             ActiveAdmin admin = policy.mAdminList.get(i);
7991             if (component.equals(admin.info.getComponent())) {
7992                 return admin;
7993             }
7994         }
7995         Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
7996         return null;
7997     }
7998 
7999     @Override
clearDeviceOwner(String packageName)8000     public void clearDeviceOwner(String packageName) {
8001         Preconditions.checkNotNull(packageName, "packageName is null");
8002         final int callingUid = mInjector.binderGetCallingUid();
8003         try {
8004             int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
8005                     UserHandle.getUserId(callingUid));
8006             if (uid != callingUid) {
8007                 throw new SecurityException("Invalid packageName");
8008             }
8009         } catch (NameNotFoundException e) {
8010             throw new SecurityException(e);
8011         }
8012         synchronized (getLockObject()) {
8013             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
8014             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
8015             if (!mOwners.hasDeviceOwner()
8016                     || !deviceOwnerComponent.getPackageName().equals(packageName)
8017                     || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
8018                 throw new SecurityException(
8019                         "clearDeviceOwner can only be called by the device owner");
8020             }
8021             enforceUserUnlocked(deviceOwnerUserId);
8022 
8023             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
8024             long ident = mInjector.binderClearCallingIdentity();
8025             try {
8026                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
8027                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
8028                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED,
8029                         deviceOwnerUserId);
8030             } finally {
8031                 mInjector.binderRestoreCallingIdentity(ident);
8032             }
8033             Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
8034         }
8035     }
8036 
clearOverrideApnUnchecked()8037     private void clearOverrideApnUnchecked() {
8038         // Disable Override APNs and remove them from database.
8039         setOverrideApnsEnabledUnchecked(false);
8040         final List<ApnSetting> apns = getOverrideApnsUnchecked();
8041         for (int i = 0; i < apns.size(); i ++) {
8042             removeOverrideApnUnchecked(apns.get(i).getId());
8043         }
8044     }
8045 
clearDeviceOwnerLocked(ActiveAdmin admin, int userId)8046     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
8047         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
8048 
8049         if (admin != null) {
8050             admin.disableCamera = false;
8051             admin.userRestrictions = null;
8052             admin.defaultEnabledRestrictionsAlreadySet.clear();
8053             admin.forceEphemeralUsers = false;
8054             admin.isNetworkLoggingEnabled = false;
8055             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
8056         }
8057         final DevicePolicyData policyData = getUserData(userId);
8058         policyData.mCurrentInputMethodSet = false;
8059         saveSettingsLocked(userId);
8060         final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
8061         systemPolicyData.mLastSecurityLogRetrievalTime = -1;
8062         systemPolicyData.mLastBugReportRequestTime = -1;
8063         systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
8064         saveSettingsLocked(UserHandle.USER_SYSTEM);
8065         clearUserPoliciesLocked(userId);
8066         clearOverrideApnUnchecked();
8067 
8068         mOwners.clearDeviceOwner();
8069         mOwners.writeDeviceOwner();
8070         updateDeviceOwnerLocked();
8071 
8072         clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId));
8073         mInjector.securityLogSetLoggingEnabledProperty(false);
8074         mSecurityLogMonitor.stop();
8075         setNetworkLoggingActiveInternal(false);
8076         deleteTransferOwnershipBundleLocked(userId);
8077         toggleBackupServiceActive(UserHandle.USER_SYSTEM, true);
8078     }
8079 
8080     @Override
setProfileOwner(ComponentName who, String ownerName, int userHandle)8081     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
8082         if (!mHasFeature) {
8083             return false;
8084         }
8085         if (who == null
8086                 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
8087             throw new IllegalArgumentException("Component " + who
8088                     + " not installed for userId:" + userHandle);
8089         }
8090 
8091         final boolean hasIncompatibleAccountsOrNonAdb =
8092                 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
8093         synchronized (getLockObject()) {
8094             enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
8095 
8096             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8097             if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) {
8098                 throw new IllegalArgumentException("Not active admin: " + who);
8099             }
8100 
8101             if (isAdb()) {
8102                 // Log profile owner provisioning was started using adb.
8103                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
8104                 DevicePolicyEventLogger
8105                         .createEvent(DevicePolicyEnums.PROVISIONING_ENTRY_POINT_ADB)
8106                         .setAdmin(who)
8107                         .setStrings(LOG_TAG_PROFILE_OWNER)
8108                         .write();
8109             }
8110 
8111             // Shutting down backup manager service permanently.
8112             toggleBackupServiceActive(userHandle, /* makeActive= */ false);
8113 
8114             mOwners.setProfileOwner(who, ownerName, userHandle);
8115             mOwners.writeProfileOwner(userHandle);
8116             Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
8117 
8118             final long id = mInjector.binderClearCallingIdentity();
8119             try {
8120                 if (mUserManager.isManagedProfile(userHandle)) {
8121                     maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin,
8122                             UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
8123                     ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
8124                             true /* newOwner */);
8125                 }
8126                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
8127                         userHandle);
8128             } finally {
8129                 mInjector.binderRestoreCallingIdentity(id);
8130             }
8131             mDeviceAdminServiceController.startServiceForOwner(
8132                     who.getPackageName(), userHandle, "set-profile-owner");
8133             return true;
8134         }
8135     }
8136 
toggleBackupServiceActive(int userId, boolean makeActive)8137     private void toggleBackupServiceActive(int userId, boolean makeActive) {
8138         long ident = mInjector.binderClearCallingIdentity();
8139         try {
8140             if (mInjector.getIBackupManager() != null) {
8141                 mInjector.getIBackupManager()
8142                         .setBackupServiceActive(userId, makeActive);
8143             }
8144         } catch (RemoteException e) {
8145             throw new IllegalStateException(String.format("Failed %s backup service.",
8146                     makeActive ? "activating" : "deactivating"), e);
8147         } finally {
8148             mInjector.binderRestoreCallingIdentity(ident);
8149         }
8150 
8151     }
8152 
8153     @Override
clearProfileOwner(ComponentName who)8154     public void clearProfileOwner(ComponentName who) {
8155         if (!mHasFeature) {
8156             return;
8157         }
8158         Preconditions.checkNotNull(who, "ComponentName is null");
8159 
8160         final int userId = mInjector.userHandleGetCallingUserId();
8161         enforceNotManagedProfile(userId, "clear profile owner");
8162         enforceUserUnlocked(userId);
8163         synchronized (getLockObject()) {
8164             // Check if this is the profile owner who is calling
8165             final ActiveAdmin admin =
8166                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8167 
8168             final long ident = mInjector.binderClearCallingIdentity();
8169             try {
8170                 clearProfileOwnerLocked(admin, userId);
8171                 removeActiveAdminLocked(who, userId);
8172                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
8173                         userId);
8174             } finally {
8175                 mInjector.binderRestoreCallingIdentity(ident);
8176             }
8177             Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
8178         }
8179     }
8180 
clearProfileOwnerLocked(ActiveAdmin admin, int userId)8181     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
8182         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner");
8183 
8184         if (admin != null) {
8185             admin.disableCamera = false;
8186             admin.userRestrictions = null;
8187             admin.defaultEnabledRestrictionsAlreadySet.clear();
8188         }
8189         final DevicePolicyData policyData = getUserData(userId);
8190         policyData.mCurrentInputMethodSet = false;
8191         policyData.mOwnerInstalledCaCerts.clear();
8192         saveSettingsLocked(userId);
8193         clearUserPoliciesLocked(userId);
8194         mOwners.removeProfileOwner(userId);
8195         mOwners.writeProfileOwner(userId);
8196         deleteTransferOwnershipBundleLocked(userId);
8197         toggleBackupServiceActive(userId, true);
8198     }
8199 
8200     @Override
setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info)8201     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
8202         Preconditions.checkNotNull(who, "ComponentName is null");
8203         if (!mHasFeature) {
8204             return;
8205         }
8206 
8207         synchronized (getLockObject()) {
8208             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8209             long token = mInjector.binderClearCallingIdentity();
8210             try {
8211                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
8212             } finally {
8213                 mInjector.binderRestoreCallingIdentity(token);
8214             }
8215         }
8216         DevicePolicyEventLogger
8217                 .createEvent(DevicePolicyEnums.SET_DEVICE_OWNER_LOCK_SCREEN_INFO)
8218                 .setAdmin(who)
8219                 .write();
8220     }
8221 
8222     @Override
getDeviceOwnerLockScreenInfo()8223     public CharSequence getDeviceOwnerLockScreenInfo() {
8224         return mLockPatternUtils.getDeviceOwnerInfo();
8225     }
8226 
clearUserPoliciesLocked(int userId)8227     private void clearUserPoliciesLocked(int userId) {
8228         // Reset some of the user-specific policies.
8229         final DevicePolicyData policy = getUserData(userId);
8230         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
8231         // Clear delegations.
8232         policy.mDelegationMap.clear();
8233         policy.mStatusBarDisabled = false;
8234         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
8235         policy.mAffiliationIds.clear();
8236         policy.mLockTaskPackages.clear();
8237         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId);
8238         policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
8239         saveSettingsLocked(userId);
8240 
8241         try {
8242             mIPackageManager.updatePermissionFlagsForAllApps(
8243                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8244                     0  /* flagValues */, userId);
8245             pushUserRestrictions(userId);
8246         } catch (RemoteException re) {
8247             // Shouldn't happen.
8248         }
8249     }
8250 
8251     @Override
hasUserSetupCompleted()8252     public boolean hasUserSetupCompleted() {
8253         return hasUserSetupCompleted(UserHandle.getCallingUserId());
8254     }
8255 
8256     // This checks only if the Setup Wizard has run.  Since Wear devices pair before
8257     // completing Setup Wizard, and pairing involves transferring user data, calling
8258     // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
hasUserSetupCompleted(int userHandle)8259     private boolean hasUserSetupCompleted(int userHandle) {
8260         if (!mHasFeature) {
8261             return true;
8262         }
8263         return getUserData(userHandle).mUserSetupComplete;
8264     }
8265 
hasPaired(int userHandle)8266     private boolean hasPaired(int userHandle) {
8267         if (!mHasFeature) {
8268             return true;
8269         }
8270         return getUserData(userHandle).mPaired;
8271     }
8272 
8273     @Override
getUserProvisioningState()8274     public int getUserProvisioningState() {
8275         if (!mHasFeature) {
8276             return DevicePolicyManager.STATE_USER_UNMANAGED;
8277         }
8278         enforceManageUsers();
8279         int userHandle = mInjector.userHandleGetCallingUserId();
8280         return getUserProvisioningState(userHandle);
8281     }
8282 
getUserProvisioningState(int userHandle)8283     private int getUserProvisioningState(int userHandle) {
8284         return getUserData(userHandle).mUserProvisioningState;
8285     }
8286 
8287     @Override
setUserProvisioningState(int newState, int userHandle)8288     public void setUserProvisioningState(int newState, int userHandle) {
8289         if (!mHasFeature) {
8290             return;
8291         }
8292 
8293         if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
8294                 && getManagedUserId(userHandle) == -1) {
8295             // No managed device, user or profile, so setting provisioning state makes no sense.
8296             throw new IllegalStateException("Not allowed to change provisioning state unless a "
8297                       + "device or profile owner is set.");
8298         }
8299 
8300         synchronized (getLockObject()) {
8301             boolean transitionCheckNeeded = true;
8302 
8303             // Calling identity/permission checks.
8304             if (isAdb()) {
8305                 // ADB shell can only move directly from un-managed to finalized as part of directly
8306                 // setting profile-owner or device-owner.
8307                 if (getUserProvisioningState(userHandle) !=
8308                         DevicePolicyManager.STATE_USER_UNMANAGED
8309                         || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
8310                     throw new IllegalStateException("Not allowed to change provisioning state "
8311                             + "unless current provisioning state is unmanaged, and new state is "
8312                             + "finalized.");
8313                 }
8314                 transitionCheckNeeded = false;
8315             } else {
8316                 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
8317                 enforceCanManageProfileAndDeviceOwners();
8318             }
8319 
8320             final DevicePolicyData policyData = getUserData(userHandle);
8321             if (transitionCheckNeeded) {
8322                 // Optional state transition check for non-ADB case.
8323                 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
8324             }
8325             policyData.mUserProvisioningState = newState;
8326             saveSettingsLocked(userHandle);
8327         }
8328     }
8329 
checkUserProvisioningStateTransition(int currentState, int newState)8330     private void checkUserProvisioningStateTransition(int currentState, int newState) {
8331         // Valid transitions for normal use-cases.
8332         switch (currentState) {
8333             case DevicePolicyManager.STATE_USER_UNMANAGED:
8334                 // Can move to any state from unmanaged (except itself as an edge case)..
8335                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
8336                     return;
8337                 }
8338                 break;
8339             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
8340             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
8341                 // Can only move to finalized from these states.
8342                 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
8343                     return;
8344                 }
8345                 break;
8346             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
8347                 // Current user has a managed-profile, but current user is not managed, so
8348                 // rather than moving to finalized state, go back to unmanaged once
8349                 // profile provisioning is complete.
8350                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
8351                     return;
8352                 }
8353                 break;
8354             case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
8355                 // Cannot transition out of finalized.
8356                 break;
8357         }
8358 
8359         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
8360         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
8361                 + "from state [" + currentState + "]");
8362     }
8363 
8364     @Override
setProfileEnabled(ComponentName who)8365     public void setProfileEnabled(ComponentName who) {
8366         if (!mHasFeature) {
8367             return;
8368         }
8369         Preconditions.checkNotNull(who, "ComponentName is null");
8370         synchronized (getLockObject()) {
8371             // Check if this is the profile owner who is calling
8372             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8373             final int userId = UserHandle.getCallingUserId();
8374             enforceManagedProfile(userId, "enable the profile");
8375             // Check if the profile is already enabled.
8376             UserInfo managedProfile = getUserInfo(userId);
8377             if (managedProfile.isEnabled()) {
8378                 Slog.e(LOG_TAG,
8379                         "setProfileEnabled is called when the profile is already enabled");
8380                 return;
8381             }
8382             long id = mInjector.binderClearCallingIdentity();
8383             try {
8384                 mUserManager.setUserEnabled(userId);
8385                 UserInfo parent = mUserManager.getProfileParent(userId);
8386                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
8387                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
8388                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
8389                         Intent.FLAG_RECEIVER_FOREGROUND);
8390                 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
8391             } finally {
8392                 mInjector.binderRestoreCallingIdentity(id);
8393             }
8394         }
8395     }
8396 
8397     @Override
setProfileName(ComponentName who, String profileName)8398     public void setProfileName(ComponentName who, String profileName) {
8399         Preconditions.checkNotNull(who, "ComponentName is null");
8400         enforceProfileOrDeviceOwner(who);
8401 
8402         final int userId = UserHandle.getCallingUserId();
8403         final long id = mInjector.binderClearCallingIdentity();
8404         try {
8405             mUserManager.setUserName(userId, profileName);
8406             DevicePolicyEventLogger
8407                     .createEvent(DevicePolicyEnums.SET_PROFILE_NAME)
8408                     .setAdmin(who)
8409                     .write();
8410         } finally {
8411             mInjector.binderRestoreCallingIdentity(id);
8412         }
8413     }
8414 
8415     @Override
getProfileOwnerAsUser(int userHandle)8416     public ComponentName getProfileOwnerAsUser(int userHandle) {
8417         enforceCrossUsersPermission(userHandle);
8418 
8419         return getProfileOwner(userHandle);
8420     }
8421 
8422     @Override
getProfileOwner(int userHandle)8423     public ComponentName getProfileOwner(int userHandle) {
8424         if (!mHasFeature) {
8425             return null;
8426         }
8427 
8428         synchronized (getLockObject()) {
8429             return mOwners.getProfileOwnerComponent(userHandle);
8430         }
8431     }
8432 
8433     // Returns the active profile owner for this user or null if the current user has no
8434     // profile owner.
8435     @VisibleForTesting
getProfileOwnerAdminLocked(int userHandle)8436     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
8437         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
8438         if (profileOwner == null) {
8439             return null;
8440         }
8441         DevicePolicyData policy = getUserData(userHandle);
8442         final int n = policy.mAdminList.size();
8443         for (int i = 0; i < n; i++) {
8444             ActiveAdmin admin = policy.mAdminList.get(i);
8445             if (profileOwner.equals(admin.info.getComponent())) {
8446                 return admin;
8447             }
8448         }
8449         return null;
8450     }
8451 
8452     @Override
getProfileOwnerName(int userHandle)8453     public String getProfileOwnerName(int userHandle) {
8454         if (!mHasFeature) {
8455             return null;
8456         }
8457         enforceManageUsers();
8458         ComponentName profileOwner = getProfileOwner(userHandle);
8459         if (profileOwner == null) {
8460             return null;
8461         }
8462         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
8463     }
8464 
8465     @Override
checkDeviceIdentifierAccess(String packageName, int pid, int uid)8466     public boolean checkDeviceIdentifierAccess(String packageName, int pid, int uid) {
8467         // If the caller is not a system app then it should only be able to check its own device
8468         // identifier access.
8469         int callingUid = mInjector.binderGetCallingUid();
8470         int callingPid = mInjector.binderGetCallingPid();
8471         if (UserHandle.getAppId(callingUid) >= Process.FIRST_APPLICATION_UID
8472                 && (callingUid != uid || callingPid != pid)) {
8473             String message = String.format(
8474                     "Calling uid %d, pid %d cannot check device identifier access for package %s "
8475                             + "(uid=%d, pid=%d)", callingUid, callingPid, packageName, uid, pid);
8476             Log.w(LOG_TAG, message);
8477             throw new SecurityException(message);
8478         }
8479         // Verify that the specified packages matches the provided uid.
8480         int userId = UserHandle.getUserId(uid);
8481         try {
8482             ApplicationInfo appInfo = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8483             // Since this call goes directly to PackageManagerService a NameNotFoundException is not
8484             // thrown but null data can be returned; if the appInfo for the specified package cannot
8485             // be found then return false to prevent crashing the app.
8486             if (appInfo == null) {
8487                 Log.w(LOG_TAG,
8488                         String.format("appInfo could not be found for package %s", packageName));
8489                 return false;
8490             } else if (uid != appInfo.uid) {
8491                 String message = String.format("Package %s (uid=%d) does not match provided uid %d",
8492                         packageName, appInfo.uid, uid);
8493                 Log.w(LOG_TAG, message);
8494                 throw new SecurityException(message);
8495             }
8496         } catch (RemoteException e) {
8497             // If an exception is caught obtaining the appInfo just return false to prevent crashing
8498             // apps due to an internal error.
8499             Log.e(LOG_TAG, "Exception caught obtaining appInfo for package " + packageName, e);
8500             return false;
8501         }
8502         // A device or profile owner must also have the READ_PHONE_STATE permission to access device
8503         // identifiers. If the package being checked does not have this permission then deny access.
8504         if (mContext.checkPermission(android.Manifest.permission.READ_PHONE_STATE, pid, uid)
8505                 != PackageManager.PERMISSION_GRANTED) {
8506             return false;
8507         }
8508 
8509         // Allow access to the device owner or delegate cert installer.
8510         ComponentName deviceOwner = getDeviceOwnerComponent(true);
8511         if (deviceOwner != null && (deviceOwner.getPackageName().equals(packageName)
8512                     || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) {
8513             return true;
8514         }
8515         // Allow access to the profile owner for the specified user, or delegate cert installer
8516         ComponentName profileOwner = getProfileOwnerAsUser(userId);
8517         if (profileOwner != null && (profileOwner.getPackageName().equals(packageName)
8518                     || isCallerDelegate(packageName, uid, DELEGATION_CERT_INSTALL))) {
8519             return true;
8520         }
8521 
8522         Log.w(LOG_TAG, String.format("Package %s (uid=%d, pid=%d) cannot access Device IDs",
8523                     packageName, uid, pid));
8524         return false;
8525     }
8526 
8527     /**
8528      * Canonical name for a given package.
8529      */
getApplicationLabel(String packageName, int userHandle)8530     private String getApplicationLabel(String packageName, int userHandle) {
8531         long token = mInjector.binderClearCallingIdentity();
8532         try {
8533             final Context userContext;
8534             try {
8535                 UserHandle handle = new UserHandle(userHandle);
8536                 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
8537             } catch (PackageManager.NameNotFoundException nnfe) {
8538                 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
8539                 return null;
8540             }
8541             ApplicationInfo appInfo = userContext.getApplicationInfo();
8542             CharSequence result = null;
8543             if (appInfo != null) {
8544                 result = appInfo.loadUnsafeLabel(userContext.getPackageManager());
8545             }
8546             return result != null ? result.toString() : null;
8547         } finally {
8548             mInjector.binderRestoreCallingIdentity(token);
8549         }
8550     }
8551 
8552     /**
8553      * Calls wtfStack() if called with the DPMS lock held.
8554      */
wtfIfInLock()8555     private void wtfIfInLock() {
8556         if (Thread.holdsLock(this)) {
8557             Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
8558         }
8559     }
8560 
8561     /**
8562      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
8563      * permission.
8564      * The profile owner can only be set before the user setup phase has completed,
8565      * except for:
8566      * - SYSTEM_UID
8567      * - adb unless hasIncompatibleAccountsOrNonAdb is true.
8568      */
enforceCanSetProfileOwnerLocked(@ullable ComponentName owner, int userHandle, boolean hasIncompatibleAccountsOrNonAdb)8569     private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
8570             boolean hasIncompatibleAccountsOrNonAdb) {
8571         UserInfo info = getUserInfo(userHandle);
8572         if (info == null) {
8573             // User doesn't exist.
8574             throw new IllegalArgumentException(
8575                     "Attempted to set profile owner for invalid userId: " + userHandle);
8576         }
8577         if (info.isGuest()) {
8578             throw new IllegalStateException("Cannot set a profile owner on a guest");
8579         }
8580         if (mOwners.hasProfileOwner(userHandle)) {
8581             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
8582                     + "is already set.");
8583         }
8584         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
8585             throw new IllegalStateException("Trying to set the profile owner, but the user "
8586                     + "already has a device owner.");
8587         }
8588         if (isAdb()) {
8589             if ((mIsWatch || hasUserSetupCompleted(userHandle))
8590                     && hasIncompatibleAccountsOrNonAdb) {
8591                 throw new IllegalStateException("Not allowed to set the profile owner because "
8592                         + "there are already some accounts on the profile");
8593             }
8594             return;
8595         }
8596         enforceCanManageProfileAndDeviceOwners();
8597 
8598         if ((mIsWatch || hasUserSetupCompleted(userHandle))) {
8599             if (!isCallerWithSystemUid()) {
8600                 throw new IllegalStateException("Cannot set the profile owner on a user which is "
8601                         + "already set-up");
8602             }
8603 
8604             if (!mIsWatch) {
8605                 // Only the default supervision profile owner can be set as profile owner after SUW
8606                 final String supervisor = mContext.getResources().getString(
8607                         com.android.internal.R.string
8608                                 .config_defaultSupervisionProfileOwnerComponent);
8609                 if (supervisor == null) {
8610                     throw new IllegalStateException("Unable to set profile owner post-setup, no"
8611                             + "default supervisor profile owner defined");
8612                 }
8613 
8614                 final ComponentName supervisorComponent = ComponentName.unflattenFromString(
8615                         supervisor);
8616                 if (!owner.equals(supervisorComponent)) {
8617                     throw new IllegalStateException("Unable to set non-default profile owner"
8618                             + " post-setup " + owner);
8619                 }
8620             }
8621         }
8622     }
8623 
8624     /**
8625      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
8626      * permission.
8627      */
enforceCanSetDeviceOwnerLocked(@ullable ComponentName owner, int userId, boolean hasIncompatibleAccountsOrNonAdb)8628     private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
8629             boolean hasIncompatibleAccountsOrNonAdb) {
8630         if (!isAdb()) {
8631             enforceCanManageProfileAndDeviceOwners();
8632         }
8633 
8634         final int code = checkDeviceOwnerProvisioningPreConditionLocked(
8635                 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb);
8636         switch (code) {
8637             case CODE_OK:
8638                 return;
8639             case CODE_HAS_DEVICE_OWNER:
8640                 throw new IllegalStateException(
8641                         "Trying to set the device owner, but device owner is already set.");
8642             case CODE_USER_HAS_PROFILE_OWNER:
8643                 throw new IllegalStateException("Trying to set the device owner, but the user "
8644                         + "already has a profile owner.");
8645             case CODE_USER_NOT_RUNNING:
8646                 throw new IllegalStateException("User not running: " + userId);
8647             case CODE_NOT_SYSTEM_USER:
8648                 throw new IllegalStateException("User is not system user");
8649             case CODE_USER_SETUP_COMPLETED:
8650                 throw new IllegalStateException(
8651                         "Cannot set the device owner if the device is already set-up");
8652             case CODE_NONSYSTEM_USER_EXISTS:
8653                 throw new IllegalStateException("Not allowed to set the device owner because there "
8654                         + "are already several users on the device");
8655             case CODE_ACCOUNTS_NOT_EMPTY:
8656                 throw new IllegalStateException("Not allowed to set the device owner because there "
8657                         + "are already some accounts on the device");
8658             case CODE_HAS_PAIRED:
8659                 throw new IllegalStateException("Not allowed to set the device owner because this "
8660                         + "device has already paired");
8661             default:
8662                 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code);
8663         }
8664     }
8665 
enforceUserUnlocked(int userId)8666     private void enforceUserUnlocked(int userId) {
8667         // Since we're doing this operation on behalf of an app, we only
8668         // want to use the actual "unlocked" state.
8669         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
8670                 "User must be running and unlocked");
8671     }
8672 
enforceUserUnlocked(@serIdInt int userId, boolean parent)8673     private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
8674         if (parent) {
8675             enforceUserUnlocked(getProfileParentId(userId));
8676         } else {
8677             enforceUserUnlocked(userId);
8678         }
8679     }
8680 
enforceManageUsers()8681     private void enforceManageUsers() {
8682         final int callingUid = mInjector.binderGetCallingUid();
8683         if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
8684             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8685         }
8686     }
8687 
enforceFullCrossUsersPermission(int userHandle)8688     private void enforceFullCrossUsersPermission(int userHandle) {
8689         enforceSystemUserOrPermissionIfCrossUser(userHandle,
8690                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
8691     }
8692 
enforceCrossUsersPermission(int userHandle)8693     private void enforceCrossUsersPermission(int userHandle) {
8694         enforceSystemUserOrPermissionIfCrossUser(userHandle,
8695                 android.Manifest.permission.INTERACT_ACROSS_USERS);
8696     }
8697 
enforceSystemUserOrPermission(String permission)8698     private void enforceSystemUserOrPermission(String permission) {
8699         if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) {
8700             mContext.enforceCallingOrSelfPermission(permission,
8701                     "Must be system or have " + permission + " permission");
8702         }
8703     }
8704 
enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission)8705     private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) {
8706         if (userHandle < 0) {
8707             throw new IllegalArgumentException("Invalid userId " + userHandle);
8708         }
8709         if (userHandle == mInjector.userHandleGetCallingUserId()) {
8710             return;
8711         }
8712         enforceSystemUserOrPermission(permission);
8713     }
8714 
enforceManagedProfile(int userHandle, String message)8715     private void enforceManagedProfile(int userHandle, String message) {
8716         if(!isManagedProfile(userHandle)) {
8717             throw new SecurityException("You can not " + message + " outside a managed profile.");
8718         }
8719     }
8720 
enforceNotManagedProfile(int userHandle, String message)8721     private void enforceNotManagedProfile(int userHandle, String message) {
8722         if(isManagedProfile(userHandle)) {
8723             throw new SecurityException("You can not " + message + " for a managed profile.");
8724         }
8725     }
8726 
enforceDeviceOwnerOrManageUsers()8727     private void enforceDeviceOwnerOrManageUsers() {
8728         synchronized (getLockObject()) {
8729             if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
8730                     mInjector.binderGetCallingUid()) != null) {
8731                 return;
8732             }
8733         }
8734         enforceManageUsers();
8735     }
8736 
enforceProfileOwnerOrSystemUser()8737     private void enforceProfileOwnerOrSystemUser() {
8738         synchronized (getLockObject()) {
8739             if (getActiveAdminWithPolicyForUidLocked(null,
8740                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
8741                             != null) {
8742                 return;
8743             }
8744         }
8745         Preconditions.checkState(isCallerWithSystemUid(),
8746                 "Only profile owner, device owner and system may call this method.");
8747     }
8748 
enforceProfileOwnerOrFullCrossUsersPermission(int userId)8749     private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) {
8750         if (userId == mInjector.userHandleGetCallingUserId()) {
8751             synchronized (getLockObject()) {
8752                 if (getActiveAdminWithPolicyForUidLocked(null,
8753                         DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
8754                                 != null) {
8755                     // Device Owner/Profile Owner may access the user it runs on.
8756                     return;
8757                 }
8758             }
8759         }
8760         // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required.
8761         enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
8762     }
8763 
canUserUseLockTaskLocked(int userId)8764     private boolean canUserUseLockTaskLocked(int userId) {
8765         if (isUserAffiliatedWithDeviceLocked(userId)) {
8766             return true;
8767         }
8768 
8769         // Unaffiliated profile owners are not allowed to use lock when there is a device owner.
8770         if (mOwners.hasDeviceOwner()) {
8771             return false;
8772         }
8773 
8774         final ComponentName profileOwner = getProfileOwner(userId);
8775         if (profileOwner == null) {
8776             return false;
8777         }
8778 
8779         // Managed profiles are not allowed to use lock task
8780         if (isManagedProfile(userId)) {
8781             return false;
8782         }
8783 
8784         return true;
8785     }
8786 
enforceCanCallLockTaskLocked(ComponentName who)8787     private void enforceCanCallLockTaskLocked(ComponentName who) {
8788         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8789         final int userId =  mInjector.userHandleGetCallingUserId();
8790         if (!canUserUseLockTaskLocked(userId)) {
8791             throw new SecurityException("User " + userId + " is not allowed to use lock task");
8792         }
8793     }
8794 
ensureCallerPackage(@ullable String packageName)8795     private void ensureCallerPackage(@Nullable String packageName) {
8796         if (packageName == null) {
8797             Preconditions.checkState(isCallerWithSystemUid(),
8798                     "Only caller can omit package name");
8799         } else {
8800             final int callingUid = mInjector.binderGetCallingUid();
8801             final int userId = mInjector.userHandleGetCallingUserId();
8802             try {
8803                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
8804                         packageName, 0, userId);
8805                 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
8806             } catch (RemoteException e) {
8807                 // Shouldn't happen
8808             }
8809         }
8810     }
8811 
isCallerWithSystemUid()8812     private boolean isCallerWithSystemUid() {
8813         return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
8814     }
8815 
getProfileParentId(int userHandle)8816     protected int getProfileParentId(int userHandle) {
8817         final long ident = mInjector.binderClearCallingIdentity();
8818         try {
8819             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
8820             return parentUser != null ? parentUser.id : userHandle;
8821         } finally {
8822             mInjector.binderRestoreCallingIdentity(ident);
8823         }
8824     }
8825 
getCredentialOwner(int userHandle, boolean parent)8826     private int getCredentialOwner(int userHandle, boolean parent) {
8827         final long ident = mInjector.binderClearCallingIdentity();
8828         try {
8829             if (parent) {
8830                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
8831                 if (parentProfile != null) {
8832                     userHandle = parentProfile.id;
8833                 }
8834             }
8835             return mUserManager.getCredentialOwnerProfile(userHandle);
8836         } finally {
8837             mInjector.binderRestoreCallingIdentity(ident);
8838         }
8839     }
8840 
isManagedProfile(int userHandle)8841     private boolean isManagedProfile(int userHandle) {
8842         final UserInfo user = getUserInfo(userHandle);
8843         return user != null && user.isManagedProfile();
8844     }
8845 
enableIfNecessary(String packageName, int userId)8846     private void enableIfNecessary(String packageName, int userId) {
8847         try {
8848             final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
8849                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
8850             if (ai.enabledSetting
8851                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
8852                 mIPackageManager.setApplicationEnabledSetting(packageName,
8853                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
8854                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
8855             }
8856         } catch (RemoteException e) {
8857         }
8858     }
8859 
8860     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)8861     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8862         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
8863 
8864         synchronized (getLockObject()) {
8865             pw.println("Current Device Policy Manager state:");
8866 
8867             mOwners.dump("  ", pw);
8868             mDeviceAdminServiceController.dump("  ", pw);
8869             int userCount = mUserData.size();
8870             for (int u = 0; u < userCount; u++) {
8871                 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
8872                 pw.println();
8873                 pw.println("  Enabled Device Admins (User " + policy.mUserHandle
8874                         + ", provisioningState: " + policy.mUserProvisioningState + "):");
8875                 final int N = policy.mAdminList.size();
8876                 for (int i=0; i<N; i++) {
8877                     ActiveAdmin ap = policy.mAdminList.get(i);
8878                     if (ap != null) {
8879                         pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
8880                                 pw.println(":");
8881                         ap.dump("      ", pw);
8882                     }
8883                 }
8884                 if (!policy.mRemovingAdmins.isEmpty()) {
8885                     pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
8886                             + policy.mRemovingAdmins);
8887                 }
8888 
8889                 pw.println(" ");
8890                 pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
8891             }
8892             pw.println();
8893             mConstants.dump("  ", pw);
8894             pw.println();
8895             mStatLogger.dump(pw, "  ");
8896             pw.println();
8897             pw.println("  Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
8898             pw.println();
8899             mPolicyCache.dump("  ", pw);
8900         }
8901     }
8902 
getEncryptionStatusName(int encryptionStatus)8903     private String getEncryptionStatusName(int encryptionStatus) {
8904         switch (encryptionStatus) {
8905             case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
8906                 return "inactive";
8907             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
8908                 return "block default key";
8909             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
8910                 return "block";
8911             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
8912                 return "per-user";
8913             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
8914                 return "unsupported";
8915             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
8916                 return "activating";
8917             default:
8918                 return "unknown";
8919         }
8920     }
8921 
8922     @Override
addPersistentPreferredActivity(ComponentName who, IntentFilter filter, ComponentName activity)8923     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
8924             ComponentName activity) {
8925         Preconditions.checkNotNull(who, "ComponentName is null");
8926         final int userHandle = UserHandle.getCallingUserId();
8927         synchronized (getLockObject()) {
8928             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8929 
8930             long id = mInjector.binderClearCallingIdentity();
8931             try {
8932                 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
8933                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
8934             } catch (RemoteException re) {
8935                 // Shouldn't happen
8936             } finally {
8937                 mInjector.binderRestoreCallingIdentity(id);
8938             }
8939         }
8940         final String activityPackage =
8941                 (activity != null ? activity.getPackageName() : null);
8942         DevicePolicyEventLogger
8943                 .createEvent(DevicePolicyEnums.ADD_PERSISTENT_PREFERRED_ACTIVITY)
8944                 .setAdmin(who)
8945                 .setStrings(activityPackage, getIntentFilterActions(filter))
8946                 .write();
8947     }
8948 
8949     @Override
clearPackagePersistentPreferredActivities(ComponentName who, String packageName)8950     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
8951         Preconditions.checkNotNull(who, "ComponentName is null");
8952         final int userHandle = UserHandle.getCallingUserId();
8953         synchronized (getLockObject()) {
8954             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8955 
8956             long id = mInjector.binderClearCallingIdentity();
8957             try {
8958                 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
8959                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
8960             } catch (RemoteException re) {
8961                 // Shouldn't happen
8962             } finally {
8963                 mInjector.binderRestoreCallingIdentity(id);
8964             }
8965         }
8966     }
8967 
8968     @Override
setDefaultSmsApplication(ComponentName admin, String packageName)8969     public void setDefaultSmsApplication(ComponentName admin, String packageName) {
8970         Preconditions.checkNotNull(admin, "ComponentName is null");
8971         enforceDeviceOwner(admin);
8972         mInjector.binderWithCleanCallingIdentity(() ->
8973                 SmsApplication.setDefaultApplication(packageName, mContext));
8974     }
8975 
8976     @Override
setApplicationRestrictionsManagingPackage(ComponentName admin, String packageName)8977     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
8978             String packageName) {
8979         try {
8980             setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
8981         } catch (IllegalArgumentException e) {
8982             return false;
8983         }
8984         return true;
8985     }
8986 
8987     @Override
getApplicationRestrictionsManagingPackage(ComponentName admin)8988     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
8989         final List<String> delegatePackages = getDelegatePackages(admin,
8990                 DELEGATION_APP_RESTRICTIONS);
8991         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
8992     }
8993 
8994     @Override
isCallerApplicationRestrictionsManagingPackage(String callerPackage)8995     public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
8996         return isCallerDelegate(callerPackage, mInjector.binderGetCallingUid(),
8997                 DELEGATION_APP_RESTRICTIONS);
8998     }
8999 
9000     @Override
setApplicationRestrictions(ComponentName who, String callerPackage, String packageName, Bundle settings)9001     public void setApplicationRestrictions(ComponentName who, String callerPackage,
9002             String packageName, Bundle settings) {
9003         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9004                 DELEGATION_APP_RESTRICTIONS);
9005 
9006         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
9007         final long id = mInjector.binderClearCallingIdentity();
9008         try {
9009             mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
9010             final boolean isDelegate = (who == null);
9011             DevicePolicyEventLogger
9012                     .createEvent(DevicePolicyEnums.SET_APPLICATION_RESTRICTIONS)
9013                     .setAdmin(callerPackage)
9014                     .setBoolean(isDelegate)
9015                     .setStrings(packageName)
9016                     .write();
9017         } finally {
9018             mInjector.binderRestoreCallingIdentity(id);
9019         }
9020     }
9021 
9022     @Override
setTrustAgentConfiguration(ComponentName admin, ComponentName agent, PersistableBundle args, boolean parent)9023     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
9024             PersistableBundle args, boolean parent) {
9025         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
9026             return;
9027         }
9028         Preconditions.checkNotNull(admin, "admin is null");
9029         Preconditions.checkNotNull(agent, "agent is null");
9030         final int userHandle = UserHandle.getCallingUserId();
9031         synchronized (getLockObject()) {
9032             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
9033                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
9034             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
9035             saveSettingsLocked(userHandle);
9036         }
9037     }
9038 
9039     @Override
getTrustAgentConfiguration(ComponentName admin, ComponentName agent, int userHandle, boolean parent)9040     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
9041             ComponentName agent, int userHandle, boolean parent) {
9042         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
9043             return null;
9044         }
9045         Preconditions.checkNotNull(agent, "agent null");
9046         enforceFullCrossUsersPermission(userHandle);
9047 
9048         synchronized (getLockObject()) {
9049             final String componentName = agent.flattenToString();
9050             if (admin != null) {
9051                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
9052                 if (ap == null) return null;
9053                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
9054                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
9055                 List<PersistableBundle> result = new ArrayList<>();
9056                 result.add(trustAgentInfo.options);
9057                 return result;
9058             }
9059 
9060             // Return strictest policy for this user and profiles that are visible from this user.
9061             List<PersistableBundle> result = null;
9062             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
9063             // of the options. If any admin doesn't have options, discard options for the rest
9064             // and return null.
9065             List<ActiveAdmin> admins =
9066                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
9067             boolean allAdminsHaveOptions = true;
9068             final int N = admins.size();
9069             for (int i = 0; i < N; i++) {
9070                 final ActiveAdmin active = admins.get(i);
9071 
9072                 final boolean disablesTrust = (active.disabledKeyguardFeatures
9073                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
9074                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
9075                 if (info != null && info.options != null && !info.options.isEmpty()) {
9076                     if (disablesTrust) {
9077                         if (result == null) {
9078                             result = new ArrayList<>();
9079                         }
9080                         result.add(info.options);
9081                     } else {
9082                         Log.w(LOG_TAG, "Ignoring admin " + active.info
9083                                 + " because it has trust options but doesn't declare "
9084                                 + "KEYGUARD_DISABLE_TRUST_AGENTS");
9085                     }
9086                 } else if (disablesTrust) {
9087                     allAdminsHaveOptions = false;
9088                     break;
9089                 }
9090             }
9091             return allAdminsHaveOptions ? result : null;
9092         }
9093     }
9094 
9095     @Override
setRestrictionsProvider(ComponentName who, ComponentName permissionProvider)9096     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
9097         Preconditions.checkNotNull(who, "ComponentName is null");
9098         synchronized (getLockObject()) {
9099             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9100 
9101             int userHandle = UserHandle.getCallingUserId();
9102             DevicePolicyData userData = getUserData(userHandle);
9103             userData.mRestrictionsProvider = permissionProvider;
9104             saveSettingsLocked(userHandle);
9105         }
9106     }
9107 
9108     @Override
getRestrictionsProvider(int userHandle)9109     public ComponentName getRestrictionsProvider(int userHandle) {
9110         synchronized (getLockObject()) {
9111             if (!isCallerWithSystemUid()) {
9112                 throw new SecurityException("Only the system can query the permission provider");
9113             }
9114             DevicePolicyData userData = getUserData(userHandle);
9115             return userData != null ? userData.mRestrictionsProvider : null;
9116         }
9117     }
9118 
9119     @Override
addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags)9120     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
9121         Preconditions.checkNotNull(who, "ComponentName is null");
9122         int callingUserId = UserHandle.getCallingUserId();
9123         synchronized (getLockObject()) {
9124             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9125 
9126             long id = mInjector.binderClearCallingIdentity();
9127             try {
9128                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
9129                 if (parent == null) {
9130                     Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
9131                             + "parent");
9132                     return;
9133                 }
9134                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
9135                     mIPackageManager.addCrossProfileIntentFilter(
9136                             filter, who.getPackageName(), callingUserId, parent.id, 0);
9137                 }
9138                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
9139                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
9140                             parent.id, callingUserId, 0);
9141                 }
9142             } catch (RemoteException re) {
9143                 // Shouldn't happen
9144             } finally {
9145                 mInjector.binderRestoreCallingIdentity(id);
9146             }
9147         }
9148         DevicePolicyEventLogger
9149                 .createEvent(DevicePolicyEnums.ADD_CROSS_PROFILE_INTENT_FILTER)
9150                 .setAdmin(who)
9151                 .setStrings(getIntentFilterActions(filter))
9152                 .setInt(flags)
9153                 .write();
9154     }
9155 
getIntentFilterActions(IntentFilter filter)9156     private static String[] getIntentFilterActions(IntentFilter filter) {
9157         if (filter == null) {
9158             return null;
9159         }
9160         final int actionsCount = filter.countActions();
9161         final String[] actions = new String[actionsCount];
9162         for (int i = 0; i < actionsCount; i++) {
9163             actions[i] = filter.getAction(i);
9164         }
9165         return actions;
9166     }
9167 
9168     @Override
clearCrossProfileIntentFilters(ComponentName who)9169     public void clearCrossProfileIntentFilters(ComponentName who) {
9170         Preconditions.checkNotNull(who, "ComponentName is null");
9171         int callingUserId = UserHandle.getCallingUserId();
9172         synchronized (getLockObject()) {
9173             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9174             long id = mInjector.binderClearCallingIdentity();
9175             try {
9176                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
9177                 if (parent == null) {
9178                     Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
9179                             + "parent");
9180                     return;
9181                 }
9182                 // Removing those that go from the managed profile to the parent.
9183                 mIPackageManager.clearCrossProfileIntentFilters(
9184                         callingUserId, who.getPackageName());
9185                 // And those that go from the parent to the managed profile.
9186                 // If we want to support multiple managed profiles, we will have to only remove
9187                 // those that have callingUserId as their target.
9188                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
9189             } catch (RemoteException re) {
9190                 // Shouldn't happen
9191             } finally {
9192                 mInjector.binderRestoreCallingIdentity(id);
9193             }
9194         }
9195     }
9196 
9197     /**
9198      * @return true if all packages in enabledPackages are either in the list
9199      * permittedList or are a system app.
9200      */
checkPackagesInPermittedListOrSystem(List<String> enabledPackages, List<String> permittedList, int userIdToCheck)9201     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
9202             List<String> permittedList, int userIdToCheck) {
9203         long id = mInjector.binderClearCallingIdentity();
9204         try {
9205             // If we have an enabled packages list for a managed profile the packages
9206             // we should check are installed for the parent user.
9207             UserInfo user = getUserInfo(userIdToCheck);
9208             if (user.isManagedProfile()) {
9209                 userIdToCheck = user.profileGroupId;
9210             }
9211 
9212             for (String enabledPackage : enabledPackages) {
9213                 boolean systemService = false;
9214                 try {
9215                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
9216                             enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
9217                             userIdToCheck);
9218                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9219                 } catch (RemoteException e) {
9220                     Log.i(LOG_TAG, "Can't talk to package managed", e);
9221                 }
9222                 if (!systemService && !permittedList.contains(enabledPackage)) {
9223                     return false;
9224                 }
9225             }
9226         } finally {
9227             mInjector.binderRestoreCallingIdentity(id);
9228         }
9229         return true;
9230     }
9231 
getAccessibilityManagerForUser(int userId)9232     private AccessibilityManager getAccessibilityManagerForUser(int userId) {
9233         // Not using AccessibilityManager.getInstance because that guesses
9234         // at the user you require based on callingUid and caches for a given
9235         // process.
9236         IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
9237         IAccessibilityManager service = iBinder == null
9238                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
9239         return new AccessibilityManager(mContext, service, userId);
9240     }
9241 
9242     @Override
setPermittedAccessibilityServices(ComponentName who, List packageList)9243     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
9244         if (!mHasFeature) {
9245             return false;
9246         }
9247         Preconditions.checkNotNull(who, "ComponentName is null");
9248 
9249         if (packageList != null) {
9250             int userId = UserHandle.getCallingUserId();
9251             List<AccessibilityServiceInfo> enabledServices = null;
9252             long id = mInjector.binderClearCallingIdentity();
9253             try {
9254                 UserInfo user = getUserInfo(userId);
9255                 if (user.isManagedProfile()) {
9256                     userId = user.profileGroupId;
9257                 }
9258                 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
9259                 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
9260                         AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
9261             } finally {
9262                 mInjector.binderRestoreCallingIdentity(id);
9263             }
9264 
9265             if (enabledServices != null) {
9266                 List<String> enabledPackages = new ArrayList<String>();
9267                 for (AccessibilityServiceInfo service : enabledServices) {
9268                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
9269                 }
9270                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
9271                         userId)) {
9272                     Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
9273                             + "because it contains already enabled accesibility services.");
9274                     return false;
9275                 }
9276             }
9277         }
9278 
9279         synchronized (getLockObject()) {
9280             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9281                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9282             admin.permittedAccessiblityServices = packageList;
9283             saveSettingsLocked(UserHandle.getCallingUserId());
9284         }
9285         final String[] packageArray =
9286                 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null;
9287         DevicePolicyEventLogger
9288                 .createEvent(DevicePolicyEnums.SET_PERMITTED_ACCESSIBILITY_SERVICES)
9289                 .setAdmin(who)
9290                 .setStrings(packageArray)
9291                 .write();
9292         return true;
9293     }
9294 
9295     @Override
getPermittedAccessibilityServices(ComponentName who)9296     public List getPermittedAccessibilityServices(ComponentName who) {
9297         if (!mHasFeature) {
9298             return null;
9299         }
9300         Preconditions.checkNotNull(who, "ComponentName is null");
9301 
9302         synchronized (getLockObject()) {
9303             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9304                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9305             return admin.permittedAccessiblityServices;
9306         }
9307     }
9308 
9309     @Override
getPermittedAccessibilityServicesForUser(int userId)9310     public List getPermittedAccessibilityServicesForUser(int userId) {
9311         if (!mHasFeature) {
9312             return null;
9313         }
9314         enforceManageUsers();
9315         synchronized (getLockObject()) {
9316             List<String> result = null;
9317             // If we have multiple profiles we return the intersection of the
9318             // permitted lists. This can happen in cases where we have a device
9319             // and profile owner.
9320             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
9321             for (int profileId : profileIds) {
9322                 // Just loop though all admins, only device or profiles
9323                 // owners can have permitted lists set.
9324                 DevicePolicyData policy = getUserDataUnchecked(profileId);
9325                 final int N = policy.mAdminList.size();
9326                 for (int j = 0; j < N; j++) {
9327                     ActiveAdmin admin = policy.mAdminList.get(j);
9328                     List<String> fromAdmin = admin.permittedAccessiblityServices;
9329                     if (fromAdmin != null) {
9330                         if (result == null) {
9331                             result = new ArrayList<>(fromAdmin);
9332                         } else {
9333                             result.retainAll(fromAdmin);
9334                         }
9335                     }
9336                 }
9337             }
9338 
9339             // If we have a permitted list add all system accessibility services.
9340             if (result != null) {
9341                 long id = mInjector.binderClearCallingIdentity();
9342                 try {
9343                     UserInfo user = getUserInfo(userId);
9344                     if (user.isManagedProfile()) {
9345                         userId = user.profileGroupId;
9346                     }
9347                     AccessibilityManager accessibilityManager =
9348                             getAccessibilityManagerForUser(userId);
9349                     List<AccessibilityServiceInfo> installedServices =
9350                             accessibilityManager.getInstalledAccessibilityServiceList();
9351 
9352                     if (installedServices != null) {
9353                         for (AccessibilityServiceInfo service : installedServices) {
9354                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
9355                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
9356                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9357                                 result.add(serviceInfo.packageName);
9358                             }
9359                         }
9360                     }
9361                 } finally {
9362                     mInjector.binderRestoreCallingIdentity(id);
9363                 }
9364             }
9365 
9366             return result;
9367         }
9368     }
9369 
9370     @Override
isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, int userHandle)9371     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
9372             int userHandle) {
9373         if (!mHasFeature) {
9374             return true;
9375         }
9376         Preconditions.checkNotNull(who, "ComponentName is null");
9377         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
9378         if (!isCallerWithSystemUid()){
9379             throw new SecurityException(
9380                     "Only the system can query if an accessibility service is disabled by admin");
9381         }
9382         synchronized (getLockObject()) {
9383             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9384             if (admin == null) {
9385                 return false;
9386             }
9387             if (admin.permittedAccessiblityServices == null) {
9388                 return true;
9389             }
9390             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
9391                     admin.permittedAccessiblityServices, userHandle);
9392         }
9393     }
9394 
checkCallerIsCurrentUserOrProfile()9395     private boolean checkCallerIsCurrentUserOrProfile() {
9396         final int callingUserId = UserHandle.getCallingUserId();
9397         final long token = mInjector.binderClearCallingIdentity();
9398         try {
9399             UserInfo currentUser;
9400             UserInfo callingUser = getUserInfo(callingUserId);
9401             try {
9402                 currentUser = mInjector.getIActivityManager().getCurrentUser();
9403             } catch (RemoteException e) {
9404                 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
9405                 return false;
9406             }
9407 
9408             if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
9409                 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
9410                         + "of a user that isn't the foreground user.");
9411                 return false;
9412             }
9413             if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
9414                 Slog.e(LOG_TAG, "Cannot set permitted input methods "
9415                         + "of a user that isn't the foreground user.");
9416                 return false;
9417             }
9418         } finally {
9419             mInjector.binderRestoreCallingIdentity(token);
9420         }
9421         return true;
9422     }
9423 
9424     @Override
setPermittedInputMethods(ComponentName who, List packageList)9425     public boolean setPermittedInputMethods(ComponentName who, List packageList) {
9426         if (!mHasFeature) {
9427             return false;
9428         }
9429         Preconditions.checkNotNull(who, "ComponentName is null");
9430 
9431         // TODO When InputMethodManager supports per user calls remove this restriction.
9432         if (!InputMethodSystemProperty.PER_PROFILE_IME_ENABLED
9433                 && !checkCallerIsCurrentUserOrProfile()) {
9434             return false;
9435         }
9436         final int callingUserId = mInjector.userHandleGetCallingUserId();
9437         if (packageList != null) {
9438             List<InputMethodInfo> enabledImes = InputMethodManagerInternal.get()
9439                     .getEnabledInputMethodListAsUser(callingUserId);
9440             if (enabledImes != null) {
9441                 List<String> enabledPackages = new ArrayList<String>();
9442                 for (InputMethodInfo ime : enabledImes) {
9443                     enabledPackages.add(ime.getPackageName());
9444                 }
9445                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
9446                         callingUserId)) {
9447                     Slog.e(LOG_TAG, "Cannot set permitted input methods, "
9448                             + "because it contains already enabled input method.");
9449                     return false;
9450                 }
9451             }
9452         }
9453 
9454         synchronized (getLockObject()) {
9455             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9456                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9457             admin.permittedInputMethods = packageList;
9458             saveSettingsLocked(callingUserId);
9459         }
9460         final String[] packageArray =
9461                 packageList != null ? ((List<String>) packageList).toArray(new String[0]) : null;
9462         DevicePolicyEventLogger
9463                 .createEvent(DevicePolicyEnums.SET_PERMITTED_INPUT_METHODS)
9464                 .setAdmin(who)
9465                 .setStrings(packageArray)
9466                 .write();
9467         return true;
9468     }
9469 
9470     @Override
getPermittedInputMethods(ComponentName who)9471     public List getPermittedInputMethods(ComponentName who) {
9472         if (!mHasFeature) {
9473             return null;
9474         }
9475         Preconditions.checkNotNull(who, "ComponentName is null");
9476 
9477         synchronized (getLockObject()) {
9478             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9479                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9480             return admin.permittedInputMethods;
9481         }
9482     }
9483 
9484     @Override
getPermittedInputMethodsForCurrentUser()9485     public List getPermittedInputMethodsForCurrentUser() {
9486         enforceManageUsers();
9487 
9488         final int callingUserId = mInjector.userHandleGetCallingUserId();
9489         synchronized (getLockObject()) {
9490             List<String> result = null;
9491             // If we have multiple profiles we return the intersection of the
9492             // permitted lists. This can happen in cases where we have a device
9493             // and profile owner.
9494             int[] profileIds = InputMethodSystemProperty.PER_PROFILE_IME_ENABLED
9495                     ? new int[]{callingUserId}
9496                     : mUserManager.getProfileIdsWithDisabled(callingUserId);
9497             for (int profileId : profileIds) {
9498                 // Just loop though all admins, only device or profiles
9499                 // owners can have permitted lists set.
9500                 DevicePolicyData policy = getUserDataUnchecked(profileId);
9501                 final int N = policy.mAdminList.size();
9502                 for (int j = 0; j < N; j++) {
9503                     ActiveAdmin admin = policy.mAdminList.get(j);
9504                     List<String> fromAdmin = admin.permittedInputMethods;
9505                     if (fromAdmin != null) {
9506                         if (result == null) {
9507                             result = new ArrayList<String>(fromAdmin);
9508                         } else {
9509                             result.retainAll(fromAdmin);
9510                         }
9511                     }
9512                 }
9513             }
9514 
9515             // If we have a permitted list add all system input methods.
9516             if (result != null) {
9517                 List<InputMethodInfo> imes =
9518                         InputMethodManagerInternal.get().getInputMethodListAsUser(callingUserId);
9519                 if (imes != null) {
9520                     for (InputMethodInfo ime : imes) {
9521                         ServiceInfo serviceInfo = ime.getServiceInfo();
9522                         ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
9523                         if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9524                             result.add(serviceInfo.packageName);
9525                         }
9526                     }
9527                 }
9528             }
9529             return result;
9530         }
9531     }
9532 
9533     @Override
isInputMethodPermittedByAdmin(ComponentName who, String packageName, int userHandle)9534     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
9535             int userHandle) {
9536         if (!mHasFeature) {
9537             return true;
9538         }
9539         Preconditions.checkNotNull(who, "ComponentName is null");
9540         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
9541         if (!isCallerWithSystemUid()) {
9542             throw new SecurityException(
9543                     "Only the system can query if an input method is disabled by admin");
9544         }
9545         synchronized (getLockObject()) {
9546             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9547             if (admin == null) {
9548                 return false;
9549             }
9550             if (admin.permittedInputMethods == null) {
9551                 return true;
9552             }
9553             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
9554                     admin.permittedInputMethods, userHandle);
9555         }
9556     }
9557 
9558     @Override
setPermittedCrossProfileNotificationListeners( ComponentName who, List<String> packageList)9559     public boolean setPermittedCrossProfileNotificationListeners(
9560             ComponentName who, List<String> packageList) {
9561         if (!mHasFeature) {
9562             return false;
9563         }
9564         Preconditions.checkNotNull(who, "ComponentName is null");
9565 
9566         final int callingUserId = mInjector.userHandleGetCallingUserId();
9567         if (!isManagedProfile(callingUserId)) {
9568             return false;
9569         }
9570 
9571         synchronized (getLockObject()) {
9572             ActiveAdmin admin = getActiveAdminForCallerLocked(
9573                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9574             admin.permittedNotificationListeners = packageList;
9575             saveSettingsLocked(callingUserId);
9576         }
9577         return true;
9578     }
9579 
9580     @Override
getPermittedCrossProfileNotificationListeners(ComponentName who)9581     public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
9582         if (!mHasFeature) {
9583             return null;
9584         }
9585         Preconditions.checkNotNull(who, "ComponentName is null");
9586 
9587         synchronized (getLockObject()) {
9588             ActiveAdmin admin = getActiveAdminForCallerLocked(
9589                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9590             return admin.permittedNotificationListeners;
9591         }
9592     }
9593 
9594     @Override
isNotificationListenerServicePermitted(String packageName, int userId)9595     public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
9596         if (!mHasFeature) {
9597             return true;
9598         }
9599 
9600         Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
9601         if (!isCallerWithSystemUid()) {
9602             throw new SecurityException(
9603                     "Only the system can query if a notification listener service is permitted");
9604         }
9605         synchronized (getLockObject()) {
9606             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
9607             if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
9608                 return true;
9609             }
9610             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
9611                     profileOwner.permittedNotificationListeners, userId);
9612 
9613         }
9614     }
9615 
maybeSendAdminEnabledBroadcastLocked(int userHandle)9616     private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
9617         DevicePolicyData policyData = getUserData(userHandle);
9618         if (policyData.mAdminBroadcastPending) {
9619             // Send the initialization data to profile owner and delete the data
9620             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
9621             boolean clearInitBundle = true;
9622             if (admin != null) {
9623                 PersistableBundle initBundle = policyData.mInitBundle;
9624                 clearInitBundle = sendAdminCommandLocked(admin,
9625                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
9626                         initBundle == null ? null : new Bundle(initBundle),
9627                         null /* result receiver */,
9628                         true /* send in foreground */);
9629             }
9630             if (clearInitBundle) {
9631                 // If there's no admin or we've successfully called the admin, clear the init bundle
9632                 // otherwise, keep it around
9633                 policyData.mInitBundle = null;
9634                 policyData.mAdminBroadcastPending = false;
9635                 saveSettingsLocked(userHandle);
9636             }
9637         }
9638     }
9639 
9640     @Override
createAndManageUser(ComponentName admin, String name, ComponentName profileOwner, PersistableBundle adminExtras, int flags)9641     public UserHandle createAndManageUser(ComponentName admin, String name,
9642             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
9643         Preconditions.checkNotNull(admin, "admin is null");
9644         Preconditions.checkNotNull(profileOwner, "profileOwner is null");
9645         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
9646             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
9647                     + admin + " are not in the same package");
9648         }
9649         // Only allow the system user to use this method
9650         if (!mInjector.binderGetCallingUserHandle().isSystem()) {
9651             throw new SecurityException("createAndManageUser was called from non-system user");
9652         }
9653         final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
9654         final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
9655                 && UserManager.isDeviceInDemoMode(mContext);
9656         final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
9657         final int targetSdkVersion;
9658 
9659         // Create user.
9660         UserHandle user = null;
9661         synchronized (getLockObject()) {
9662             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9663 
9664             final int callingUid = mInjector.binderGetCallingUid();
9665             final long id = mInjector.binderClearCallingIdentity();
9666             try {
9667                 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion(
9668                         callingUid);
9669 
9670                 // Return detail error code for checks inside
9671                 // UserManagerService.createUserInternalUnchecked.
9672                 DeviceStorageMonitorInternal deviceStorageMonitorInternal =
9673                         LocalServices.getService(DeviceStorageMonitorInternal.class);
9674                 if (deviceStorageMonitorInternal.isMemoryLow()) {
9675                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
9676                         throw new ServiceSpecificException(
9677                                 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage");
9678                     } else {
9679                         return null;
9680                     }
9681                 }
9682                 if (!mUserManager.canAddMoreUsers()) {
9683                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
9684                         throw new ServiceSpecificException(
9685                                 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached");
9686                     } else {
9687                         return null;
9688                     }
9689                 }
9690 
9691                 int userInfoFlags = 0;
9692                 if (ephemeral) {
9693                     userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
9694                 }
9695                 if (demo) {
9696                     userInfoFlags |= UserInfo.FLAG_DEMO;
9697                 }
9698                 String[] disallowedPackages = null;
9699                 if (!leaveAllSystemAppsEnabled) {
9700                     disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
9701                             UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
9702                             new String[0]);
9703                 }
9704                 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
9705                         userInfoFlags, disallowedPackages);
9706                 if (userInfo != null) {
9707                     user = userInfo.getUserHandle();
9708                 }
9709             } finally {
9710                 mInjector.binderRestoreCallingIdentity(id);
9711             }
9712         }
9713         if (user == null) {
9714             if (targetSdkVersion >= Build.VERSION_CODES.P) {
9715                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
9716                         "failed to create user");
9717             } else {
9718                 return null;
9719             }
9720         }
9721 
9722         final int userHandle = user.getIdentifier();
9723         final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED)
9724                 .putExtra(Intent.EXTRA_USER_HANDLE, userHandle)
9725                 .putExtra(
9726                         DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
9727                         leaveAllSystemAppsEnabled)
9728                 .setPackage(getManagedProvisioningPackage(mContext))
9729                 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9730         mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
9731 
9732         final long id = mInjector.binderClearCallingIdentity();
9733         try {
9734             final String adminPkg = admin.getPackageName();
9735             try {
9736                 // Install the profile owner if not present.
9737                 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
9738                     mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle,
9739                             PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
9740                             PackageManager.INSTALL_REASON_POLICY, null);
9741                 }
9742             } catch (RemoteException e) {
9743                 // Does not happen, same process
9744             }
9745 
9746             // Set admin.
9747             setActiveAdmin(profileOwner, true, userHandle);
9748             final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
9749             setProfileOwner(profileOwner, ownerName, userHandle);
9750 
9751             synchronized (getLockObject()) {
9752                 DevicePolicyData policyData = getUserData(userHandle);
9753                 policyData.mInitBundle = adminExtras;
9754                 policyData.mAdminBroadcastPending = true;
9755                 saveSettingsLocked(userHandle);
9756             }
9757 
9758             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
9759                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
9760                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
9761             }
9762 
9763             return user;
9764         } catch (Throwable re) {
9765             mUserManager.removeUser(userHandle);
9766             if (targetSdkVersion >= Build.VERSION_CODES.P) {
9767                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
9768                         re.getMessage());
9769             } else {
9770                 return null;
9771             }
9772         } finally {
9773             mInjector.binderRestoreCallingIdentity(id);
9774         }
9775     }
9776 
9777     @Override
removeUser(ComponentName who, UserHandle userHandle)9778     public boolean removeUser(ComponentName who, UserHandle userHandle) {
9779         Preconditions.checkNotNull(who, "ComponentName is null");
9780         Preconditions.checkNotNull(userHandle, "UserHandle is null");
9781         enforceDeviceOwner(who);
9782 
9783         final int callingUserId = mInjector.userHandleGetCallingUserId();
9784         final long id = mInjector.binderClearCallingIdentity();
9785         try {
9786             String restriction = isManagedProfile(userHandle.getIdentifier())
9787                     ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
9788                     : UserManager.DISALLOW_REMOVE_USER;
9789             if (isAdminAffectedByRestriction(who, restriction, callingUserId)) {
9790                 Log.w(LOG_TAG, "The device owner cannot remove a user because "
9791                         + restriction + " is enabled, and was not set by the device owner");
9792                 return false;
9793             }
9794             return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
9795         } finally {
9796             mInjector.binderRestoreCallingIdentity(id);
9797         }
9798     }
9799 
isAdminAffectedByRestriction( ComponentName admin, String userRestriction, int userId)9800     private boolean isAdminAffectedByRestriction(
9801             ComponentName admin, String userRestriction, int userId) {
9802         switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
9803             case UserManager.RESTRICTION_NOT_SET:
9804                 return false;
9805             case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
9806                 return !isDeviceOwner(admin, userId);
9807             case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
9808                 return !isProfileOwner(admin, userId);
9809             default:
9810                 return true;
9811         }
9812     }
9813 
9814     @Override
switchUser(ComponentName who, UserHandle userHandle)9815     public boolean switchUser(ComponentName who, UserHandle userHandle) {
9816         Preconditions.checkNotNull(who, "ComponentName is null");
9817 
9818         synchronized (getLockObject()) {
9819             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9820 
9821             long id = mInjector.binderClearCallingIdentity();
9822             try {
9823                 int userId = UserHandle.USER_SYSTEM;
9824                 if (userHandle != null) {
9825                     userId = userHandle.getIdentifier();
9826                 }
9827                 return mInjector.getIActivityManager().switchUser(userId);
9828             } catch (RemoteException e) {
9829                 Log.e(LOG_TAG, "Couldn't switch user", e);
9830                 return false;
9831             } finally {
9832                 mInjector.binderRestoreCallingIdentity(id);
9833             }
9834         }
9835     }
9836 
9837     @Override
startUserInBackground(ComponentName who, UserHandle userHandle)9838     public int startUserInBackground(ComponentName who, UserHandle userHandle) {
9839         Preconditions.checkNotNull(who, "ComponentName is null");
9840         Preconditions.checkNotNull(userHandle, "UserHandle is null");
9841         enforceDeviceOwner(who);
9842 
9843         final int userId = userHandle.getIdentifier();
9844         if (isManagedProfile(userId)) {
9845             Log.w(LOG_TAG, "Managed profile cannot be started in background");
9846             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9847         }
9848 
9849         final long id = mInjector.binderClearCallingIdentity();
9850         try {
9851             if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) {
9852                 Log.w(LOG_TAG, "Cannot start more users in background");
9853                 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS;
9854             }
9855 
9856             if (mInjector.getIActivityManager().startUserInBackground(userId)) {
9857                 return UserManager.USER_OPERATION_SUCCESS;
9858             } else {
9859                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9860             }
9861         } catch (RemoteException e) {
9862             // Same process, should not happen.
9863             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9864         } finally {
9865             mInjector.binderRestoreCallingIdentity(id);
9866         }
9867     }
9868 
9869     @Override
stopUser(ComponentName who, UserHandle userHandle)9870     public int stopUser(ComponentName who, UserHandle userHandle) {
9871         Preconditions.checkNotNull(who, "ComponentName is null");
9872         Preconditions.checkNotNull(userHandle, "UserHandle is null");
9873         enforceDeviceOwner(who);
9874 
9875         final int userId = userHandle.getIdentifier();
9876         if (isManagedProfile(userId)) {
9877             Log.w(LOG_TAG, "Managed profile cannot be stopped");
9878             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9879         }
9880 
9881         return stopUserUnchecked(userId);
9882     }
9883 
9884     @Override
logoutUser(ComponentName who)9885     public int logoutUser(ComponentName who) {
9886         Preconditions.checkNotNull(who, "ComponentName is null");
9887 
9888         final int callingUserId = mInjector.userHandleGetCallingUserId();
9889         synchronized (getLockObject()) {
9890             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9891             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
9892                 throw new SecurityException("Admin " + who +
9893                         " is neither the device owner or affiliated user's profile owner.");
9894             }
9895         }
9896 
9897         if (isManagedProfile(callingUserId)) {
9898             Log.w(LOG_TAG, "Managed profile cannot be logout");
9899             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9900         }
9901 
9902         final long id = mInjector.binderClearCallingIdentity();
9903         try {
9904             if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) {
9905                 Log.w(LOG_TAG, "Failed to switch to primary user");
9906                 // This should never happen as target user is UserHandle.USER_SYSTEM
9907                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9908             }
9909         } catch (RemoteException e) {
9910             // Same process, should not happen.
9911             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9912         } finally {
9913             mInjector.binderRestoreCallingIdentity(id);
9914         }
9915 
9916         return stopUserUnchecked(callingUserId);
9917     }
9918 
stopUserUnchecked(int userId)9919     private int stopUserUnchecked(int userId) {
9920         final long id = mInjector.binderClearCallingIdentity();
9921         try {
9922             switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) {
9923                 case ActivityManager.USER_OP_SUCCESS:
9924                     return UserManager.USER_OPERATION_SUCCESS;
9925                 case ActivityManager.USER_OP_IS_CURRENT:
9926                     return UserManager.USER_OPERATION_ERROR_CURRENT_USER;
9927                 default:
9928                     return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9929             }
9930         } catch (RemoteException e) {
9931             // Same process, should not happen.
9932             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9933         } finally {
9934             mInjector.binderRestoreCallingIdentity(id);
9935         }
9936     }
9937 
9938     @Override
getSecondaryUsers(ComponentName who)9939     public List<UserHandle> getSecondaryUsers(ComponentName who) {
9940         Preconditions.checkNotNull(who, "ComponentName is null");
9941         enforceDeviceOwner(who);
9942 
9943         final long id = mInjector.binderClearCallingIdentity();
9944         try {
9945             final List<UserInfo> userInfos = mInjector.getUserManager().getUsers(true
9946                     /*excludeDying*/);
9947             final List<UserHandle> userHandles = new ArrayList<>();
9948             for (UserInfo userInfo : userInfos) {
9949                 UserHandle userHandle = userInfo.getUserHandle();
9950                 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
9951                     userHandles.add(userInfo.getUserHandle());
9952                 }
9953             }
9954             return userHandles;
9955         } finally {
9956             mInjector.binderRestoreCallingIdentity(id);
9957         }
9958     }
9959 
9960     @Override
isEphemeralUser(ComponentName who)9961     public boolean isEphemeralUser(ComponentName who) {
9962         Preconditions.checkNotNull(who, "ComponentName is null");
9963         enforceProfileOrDeviceOwner(who);
9964 
9965         final int callingUserId = mInjector.userHandleGetCallingUserId();
9966         final long id = mInjector.binderClearCallingIdentity();
9967         try {
9968             return mInjector.getUserManager().isUserEphemeral(callingUserId);
9969         } finally {
9970             mInjector.binderRestoreCallingIdentity(id);
9971         }
9972     }
9973 
9974     @Override
getApplicationRestrictions(ComponentName who, String callerPackage, String packageName)9975     public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
9976             String packageName) {
9977         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9978                 DELEGATION_APP_RESTRICTIONS);
9979 
9980         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
9981         final long id = mInjector.binderClearCallingIdentity();
9982         try {
9983            Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
9984            // if no restrictions were saved, mUserManager.getApplicationRestrictions
9985            // returns null, but DPM method should return an empty Bundle as per JavaDoc
9986            return bundle != null ? bundle : Bundle.EMPTY;
9987         } finally {
9988             mInjector.binderRestoreCallingIdentity(id);
9989         }
9990     }
9991 
9992     @Override
setPackagesSuspended(ComponentName who, String callerPackage, String[] packageNames, boolean suspended)9993     public String[] setPackagesSuspended(ComponentName who, String callerPackage,
9994             String[] packageNames, boolean suspended) {
9995         int callingUserId = UserHandle.getCallingUserId();
9996         String[] result = null;
9997         synchronized (getLockObject()) {
9998             // Ensure the caller is a DO/PO or a package access delegate.
9999             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10000                     DELEGATION_PACKAGE_ACCESS);
10001 
10002             long id = mInjector.binderClearCallingIdentity();
10003             try {
10004                 result = mIPackageManager
10005                         .setPackagesSuspendedAsUser(packageNames, suspended,
10006                         null, null, null, PLATFORM_PACKAGE_NAME, callingUserId);
10007             } catch (RemoteException re) {
10008                 // Shouldn't happen.
10009                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
10010             } finally {
10011                 mInjector.binderRestoreCallingIdentity(id);
10012             }
10013         }
10014         final boolean isDelegate = (who == null);
10015         DevicePolicyEventLogger
10016                 .createEvent(DevicePolicyEnums.SET_PACKAGES_SUSPENDED)
10017                 .setAdmin(callerPackage)
10018                 .setBoolean(isDelegate)
10019                 .setStrings(packageNames)
10020                 .write();
10021         if (result != null) {
10022             return result;
10023         }
10024         return packageNames;
10025     }
10026 
10027     @Override
isPackageSuspended(ComponentName who, String callerPackage, String packageName)10028     public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
10029         int callingUserId = UserHandle.getCallingUserId();
10030         synchronized (getLockObject()) {
10031             // Ensure the caller is a DO/PO or a package access delegate.
10032             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10033                     DELEGATION_PACKAGE_ACCESS);
10034 
10035             long id = mInjector.binderClearCallingIdentity();
10036             try {
10037                 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
10038             } catch (RemoteException re) {
10039                 // Shouldn't happen.
10040                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
10041             } finally {
10042                 mInjector.binderRestoreCallingIdentity(id);
10043             }
10044             return false;
10045         }
10046     }
10047 
10048     @Override
setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner)10049     public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
10050         Preconditions.checkNotNull(who, "ComponentName is null");
10051         if (!UserRestrictionsUtils.isValidRestriction(key)) {
10052             return;
10053         }
10054 
10055         final int userHandle = mInjector.userHandleGetCallingUserId();
10056         synchronized (getLockObject()) {
10057             final ActiveAdmin activeAdmin =
10058                     getActiveAdminForCallerLocked(who,
10059                             DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10060             final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
10061             if (isDeviceOwner) {
10062                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
10063                     throw new SecurityException("Device owner cannot set user restriction " + key);
10064                 }
10065             } else { // profile owner
10066                 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
10067                     throw new SecurityException("Profile owner cannot set user restriction " + key);
10068                 }
10069             }
10070 
10071             // Save the restriction to ActiveAdmin.
10072             final Bundle restrictions = activeAdmin.ensureUserRestrictions();
10073             if (enabledFromThisOwner) {
10074                 restrictions.putBoolean(key, true);
10075             } else {
10076                 restrictions.remove(key);
10077             }
10078             saveUserRestrictionsLocked(userHandle);
10079         }
10080         final int eventId = enabledFromThisOwner
10081                 ? DevicePolicyEnums.ADD_USER_RESTRICTION
10082                 : DevicePolicyEnums.REMOVE_USER_RESTRICTION;
10083         DevicePolicyEventLogger
10084                 .createEvent(eventId)
10085                 .setAdmin(who)
10086                 .setStrings(key)
10087                 .write();
10088         if (SecurityLog.isLoggingEnabled()) {
10089             final int eventTag = enabledFromThisOwner
10090                     ? SecurityLog.TAG_USER_RESTRICTION_ADDED
10091                     : SecurityLog.TAG_USER_RESTRICTION_REMOVED;
10092             SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key);
10093         }
10094     }
10095 
saveUserRestrictionsLocked(int userId)10096     private void saveUserRestrictionsLocked(int userId) {
10097         saveSettingsLocked(userId);
10098         pushUserRestrictions(userId);
10099         sendChangedNotification(userId);
10100     }
10101 
pushUserRestrictions(int userId)10102     private void pushUserRestrictions(int userId) {
10103         synchronized (getLockObject()) {
10104             final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
10105             final Bundle userRestrictions;
10106             // Whether device owner enforces camera restriction.
10107             boolean disallowCameraGlobally = false;
10108 
10109             if (isDeviceOwner) {
10110                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10111                 if (deviceOwner == null) {
10112                     return; // Shouldn't happen.
10113                 }
10114                 userRestrictions = deviceOwner.userRestrictions;
10115                 // DO can disable camera globally.
10116                 disallowCameraGlobally = deviceOwner.disableCamera;
10117             } else {
10118                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
10119                 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null;
10120             }
10121 
10122             // Whether any admin enforces camera restriction.
10123             final int cameraRestrictionScope =
10124                     getCameraRestrictionScopeLocked(userId, disallowCameraGlobally);
10125 
10126             mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
10127                     isDeviceOwner, cameraRestrictionScope);
10128         }
10129     }
10130 
10131     /**
10132      * Get the scope of camera restriction for a given user if any.
10133      */
getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally)10134     private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) {
10135         if (disallowCameraGlobally) {
10136             return UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
10137         } else if (getCameraDisabled(
10138                 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) {
10139             return UserManagerInternal.CAMERA_DISABLED_LOCALLY;
10140         }
10141         return UserManagerInternal.CAMERA_NOT_DISABLED;
10142     }
10143 
10144     @Override
getUserRestrictions(ComponentName who)10145     public Bundle getUserRestrictions(ComponentName who) {
10146         if (!mHasFeature) {
10147             return null;
10148         }
10149         Preconditions.checkNotNull(who, "ComponentName is null");
10150         synchronized (getLockObject()) {
10151             final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
10152                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10153             return activeAdmin.userRestrictions;
10154         }
10155     }
10156 
10157     @Override
setApplicationHidden(ComponentName who, String callerPackage, String packageName, boolean hidden)10158     public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
10159             boolean hidden) {
10160         int callingUserId = UserHandle.getCallingUserId();
10161         boolean result = false;
10162         synchronized (getLockObject()) {
10163             // Ensure the caller is a DO/PO or a package access delegate.
10164             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10165                     DELEGATION_PACKAGE_ACCESS);
10166 
10167             long id = mInjector.binderClearCallingIdentity();
10168             try {
10169                 result = mIPackageManager
10170                         .setApplicationHiddenSettingAsUser(packageName, hidden, callingUserId);
10171             } catch (RemoteException re) {
10172                 // shouldn't happen
10173                 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
10174             } finally {
10175                 mInjector.binderRestoreCallingIdentity(id);
10176             }
10177         }
10178         final boolean isDelegate = (who == null);
10179         DevicePolicyEventLogger
10180                 .createEvent(DevicePolicyEnums.SET_APPLICATION_HIDDEN)
10181                 .setAdmin(callerPackage)
10182                 .setBoolean(isDelegate)
10183                 .setStrings(packageName, hidden ? "hidden" : "not_hidden")
10184                 .write();
10185         return result;
10186     }
10187 
10188     @Override
isApplicationHidden(ComponentName who, String callerPackage, String packageName)10189     public boolean isApplicationHidden(ComponentName who, String callerPackage,
10190             String packageName) {
10191         int callingUserId = UserHandle.getCallingUserId();
10192         synchronized (getLockObject()) {
10193             // Ensure the caller is a DO/PO or a package access delegate.
10194             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10195                     DELEGATION_PACKAGE_ACCESS);
10196 
10197             long id = mInjector.binderClearCallingIdentity();
10198             try {
10199                 return mIPackageManager.getApplicationHiddenSettingAsUser(
10200                         packageName, callingUserId);
10201             } catch (RemoteException re) {
10202                 // shouldn't happen
10203                 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
10204             } finally {
10205                 mInjector.binderRestoreCallingIdentity(id);
10206             }
10207             return false;
10208         }
10209     }
10210 
10211     @Override
enableSystemApp(ComponentName who, String callerPackage, String packageName)10212     public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
10213         synchronized (getLockObject()) {
10214             // Ensure the caller is a DO/PO or an enable system app delegate.
10215             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10216                     DELEGATION_ENABLE_SYSTEM_APP);
10217 
10218             final boolean isDemo = isCurrentUserDemo();
10219 
10220             int userId = UserHandle.getCallingUserId();
10221             long id = mInjector.binderClearCallingIdentity();
10222 
10223             try {
10224                 if (VERBOSE_LOG) {
10225                     Slog.v(LOG_TAG, "installing " + packageName + " for "
10226                             + userId);
10227                 }
10228 
10229                 int parentUserId = getProfileParentId(userId);
10230                 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) {
10231                     throw new IllegalArgumentException("Only system apps can be enabled this way.");
10232                 }
10233 
10234                 // Install the app.
10235                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
10236                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
10237                         PackageManager.INSTALL_REASON_POLICY, null);
10238                 if (isDemo) {
10239                     // Ensure the app is also ENABLED for demo users.
10240                     mIPackageManager.setApplicationEnabledSetting(packageName,
10241                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
10242                             PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
10243                 }
10244             } catch (RemoteException re) {
10245                 // shouldn't happen
10246                 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
10247             } finally {
10248                 mInjector.binderRestoreCallingIdentity(id);
10249             }
10250         }
10251         final boolean isDelegate = (who == null);
10252         DevicePolicyEventLogger
10253                 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP)
10254                 .setAdmin(callerPackage)
10255                 .setBoolean(isDelegate)
10256                 .setStrings(packageName)
10257                 .write();
10258     }
10259 
10260     @Override
enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent)10261     public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
10262         int numberOfAppsInstalled = 0;
10263         synchronized (getLockObject()) {
10264             // Ensure the caller is a DO/PO or an enable system app delegate.
10265             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10266                     DELEGATION_ENABLE_SYSTEM_APP);
10267 
10268             int userId = UserHandle.getCallingUserId();
10269             long id = mInjector.binderClearCallingIdentity();
10270 
10271             try {
10272                 int parentUserId = getProfileParentId(userId);
10273                 List<ResolveInfo> activitiesToEnable = mIPackageManager
10274                         .queryIntentActivities(intent,
10275                                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10276                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
10277                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
10278                                 parentUserId)
10279                         .getList();
10280 
10281                 if (VERBOSE_LOG) {
10282                     Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
10283                 }
10284                 if (activitiesToEnable != null) {
10285                     for (ResolveInfo info : activitiesToEnable) {
10286                         if (info.activityInfo != null) {
10287                             String packageName = info.activityInfo.packageName;
10288                             if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
10289                                 numberOfAppsInstalled++;
10290                                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
10291                                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
10292                                         PackageManager.INSTALL_REASON_POLICY, null);
10293                             } else {
10294                                 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
10295                                         + " system app");
10296                             }
10297                         }
10298                     }
10299                 }
10300             } catch (RemoteException e) {
10301                 // shouldn't happen
10302                 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
10303                 return 0;
10304             } finally {
10305                 mInjector.binderRestoreCallingIdentity(id);
10306             }
10307         }
10308         final boolean isDelegate = (who == null);
10309         DevicePolicyEventLogger
10310                 .createEvent(DevicePolicyEnums.ENABLE_SYSTEM_APP_WITH_INTENT)
10311                 .setAdmin(callerPackage)
10312                 .setBoolean(isDelegate)
10313                 .setStrings(intent.getAction())
10314                 .write();
10315         return numberOfAppsInstalled;
10316     }
10317 
isSystemApp(IPackageManager pm, String packageName, int userId)10318     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
10319             throws RemoteException {
10320         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
10321                 userId);
10322         if (appInfo == null) {
10323             throw new IllegalArgumentException("The application " + packageName +
10324                     " is not present on this device");
10325         }
10326         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10327     }
10328 
10329     @Override
installExistingPackage(ComponentName who, String callerPackage, String packageName)10330     public boolean installExistingPackage(ComponentName who, String callerPackage,
10331             String packageName) {
10332         boolean result;
10333         synchronized (getLockObject()) {
10334             // Ensure the caller is a PO or an install existing package delegate
10335             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10336                     DELEGATION_INSTALL_EXISTING_PACKAGE);
10337             final int callingUserId = mInjector.userHandleGetCallingUserId();
10338             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
10339                 throw new SecurityException("Admin " + who +
10340                         " is neither the device owner or affiliated user's profile owner.");
10341             }
10342 
10343             final long id = mInjector.binderClearCallingIdentity();
10344             try {
10345                 if (VERBOSE_LOG) {
10346                     Slog.v(LOG_TAG, "installing " + packageName + " for "
10347                             + callingUserId);
10348                 }
10349 
10350                 // Install the package.
10351                 result = mIPackageManager.installExistingPackageAsUser(packageName, callingUserId,
10352                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
10353                         PackageManager.INSTALL_REASON_POLICY, null)
10354                         == PackageManager.INSTALL_SUCCEEDED;
10355             } catch (RemoteException re) {
10356                 // shouldn't happen
10357                 return false;
10358             } finally {
10359                 mInjector.binderRestoreCallingIdentity(id);
10360             }
10361         }
10362         if (result) {
10363             final boolean isDelegate = (who == null);
10364             DevicePolicyEventLogger
10365                     .createEvent(DevicePolicyEnums.INSTALL_EXISTING_PACKAGE)
10366                     .setAdmin(callerPackage)
10367                     .setBoolean(isDelegate)
10368                     .setStrings(packageName)
10369                     .write();
10370         }
10371         return result;
10372     }
10373 
10374     @Override
setAccountManagementDisabled(ComponentName who, String accountType, boolean disabled)10375     public void setAccountManagementDisabled(ComponentName who, String accountType,
10376             boolean disabled) {
10377         if (!mHasFeature) {
10378             return;
10379         }
10380         Preconditions.checkNotNull(who, "ComponentName is null");
10381         synchronized (getLockObject()) {
10382             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
10383                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10384             if (disabled) {
10385                 ap.accountTypesWithManagementDisabled.add(accountType);
10386             } else {
10387                 ap.accountTypesWithManagementDisabled.remove(accountType);
10388             }
10389             saveSettingsLocked(UserHandle.getCallingUserId());
10390         }
10391     }
10392 
10393     @Override
getAccountTypesWithManagementDisabled()10394     public String[] getAccountTypesWithManagementDisabled() {
10395         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
10396     }
10397 
10398     @Override
getAccountTypesWithManagementDisabledAsUser(int userId)10399     public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
10400         enforceFullCrossUsersPermission(userId);
10401         if (!mHasFeature) {
10402             return null;
10403         }
10404         synchronized (getLockObject()) {
10405             DevicePolicyData policy = getUserData(userId);
10406             final int N = policy.mAdminList.size();
10407             ArraySet<String> resultSet = new ArraySet<>();
10408             for (int i = 0; i < N; i++) {
10409                 ActiveAdmin admin = policy.mAdminList.get(i);
10410                 resultSet.addAll(admin.accountTypesWithManagementDisabled);
10411             }
10412             return resultSet.toArray(new String[resultSet.size()]);
10413         }
10414     }
10415 
10416     @Override
setUninstallBlocked(ComponentName who, String callerPackage, String packageName, boolean uninstallBlocked)10417     public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
10418             boolean uninstallBlocked) {
10419         final int userId = UserHandle.getCallingUserId();
10420         synchronized (getLockObject()) {
10421             // Ensure the caller is a DO/PO or a block uninstall delegate
10422             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10423                     DELEGATION_BLOCK_UNINSTALL);
10424 
10425             long id = mInjector.binderClearCallingIdentity();
10426             try {
10427                 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
10428             } catch (RemoteException re) {
10429                 // Shouldn't happen.
10430                 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
10431             } finally {
10432                 mInjector.binderRestoreCallingIdentity(id);
10433             }
10434         }
10435         final boolean isDelegate = (who == null);
10436         DevicePolicyEventLogger
10437                 .createEvent(DevicePolicyEnums.SET_UNINSTALL_BLOCKED)
10438                 .setAdmin(callerPackage)
10439                 .setBoolean(isDelegate)
10440                 .setStrings(packageName)
10441                 .write();
10442     }
10443 
10444     @Override
isUninstallBlocked(ComponentName who, String packageName)10445     public boolean isUninstallBlocked(ComponentName who, String packageName) {
10446         // This function should return true if and only if the package is blocked by
10447         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
10448         // when the package is a system app, or when it is an active device admin.
10449         final int userId = UserHandle.getCallingUserId();
10450 
10451         synchronized (getLockObject()) {
10452             if (who != null) {
10453                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10454             }
10455 
10456             long id = mInjector.binderClearCallingIdentity();
10457             try {
10458                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
10459             } catch (RemoteException re) {
10460                 // Shouldn't happen.
10461                 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
10462             } finally {
10463                 mInjector.binderRestoreCallingIdentity(id);
10464             }
10465         }
10466         return false;
10467     }
10468 
10469     @Override
setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled)10470     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
10471         if (!mHasFeature) {
10472             return;
10473         }
10474         Preconditions.checkNotNull(who, "ComponentName is null");
10475         synchronized (getLockObject()) {
10476             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10477                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10478             if (admin.disableCallerId != disabled) {
10479                 admin.disableCallerId = disabled;
10480                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
10481             }
10482         }
10483         DevicePolicyEventLogger
10484                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALLER_ID_DISABLED)
10485                 .setAdmin(who)
10486                 .setBoolean(disabled)
10487                 .write();
10488     }
10489 
10490     @Override
getCrossProfileCallerIdDisabled(ComponentName who)10491     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
10492         if (!mHasFeature) {
10493             return false;
10494         }
10495         Preconditions.checkNotNull(who, "ComponentName is null");
10496         synchronized (getLockObject()) {
10497             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10498                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10499             return admin.disableCallerId;
10500         }
10501     }
10502 
10503     @Override
getCrossProfileCallerIdDisabledForUser(int userId)10504     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
10505         enforceCrossUsersPermission(userId);
10506         synchronized (getLockObject()) {
10507             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
10508             return (admin != null) ? admin.disableCallerId : false;
10509         }
10510     }
10511 
10512     @Override
setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled)10513     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
10514         if (!mHasFeature) {
10515             return;
10516         }
10517         Preconditions.checkNotNull(who, "ComponentName is null");
10518         synchronized (getLockObject()) {
10519             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10520                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10521             if (admin.disableContactsSearch != disabled) {
10522                 admin.disableContactsSearch = disabled;
10523                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
10524             }
10525         }
10526         DevicePolicyEventLogger
10527                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CONTACTS_SEARCH_DISABLED)
10528                 .setAdmin(who)
10529                 .setBoolean(disabled)
10530                 .write();
10531     }
10532 
10533     @Override
getCrossProfileContactsSearchDisabled(ComponentName who)10534     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
10535         if (!mHasFeature) {
10536             return false;
10537         }
10538         Preconditions.checkNotNull(who, "ComponentName is null");
10539         synchronized (getLockObject()) {
10540             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10541                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10542             return admin.disableContactsSearch;
10543         }
10544     }
10545 
10546     @Override
getCrossProfileContactsSearchDisabledForUser(int userId)10547     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
10548         enforceCrossUsersPermission(userId);
10549         synchronized (getLockObject()) {
10550             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
10551             return (admin != null) ? admin.disableContactsSearch : false;
10552         }
10553     }
10554 
10555     @Override
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent)10556     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
10557             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
10558         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
10559                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
10560         final int callingUserId = UserHandle.getCallingUserId();
10561 
10562         final long ident = mInjector.binderClearCallingIdentity();
10563         try {
10564             synchronized (getLockObject()) {
10565                 final int managedUserId = getManagedUserId(callingUserId);
10566                 if (managedUserId < 0) {
10567                     return;
10568                 }
10569                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
10570                     if (VERBOSE_LOG) {
10571                         Log.v(LOG_TAG,
10572                                 "Cross-profile contacts access disabled for user " + managedUserId);
10573                     }
10574                     return;
10575                 }
10576                 ContactsInternal.startQuickContactWithErrorToastForUser(
10577                         mContext, intent, new UserHandle(managedUserId));
10578             }
10579         } finally {
10580             mInjector.binderRestoreCallingIdentity(ident);
10581         }
10582     }
10583 
10584     /**
10585      * @return true if cross-profile QuickContact is disabled
10586      */
isCrossProfileQuickContactDisabled(int userId)10587     private boolean isCrossProfileQuickContactDisabled(int userId) {
10588         return getCrossProfileCallerIdDisabledForUser(userId)
10589                 && getCrossProfileContactsSearchDisabledForUser(userId);
10590     }
10591 
10592     /**
10593      * @return the user ID of the managed user that is linked to the current user, if any.
10594      * Otherwise -1.
10595      */
getManagedUserId(int callingUserId)10596     public int getManagedUserId(int callingUserId) {
10597         if (VERBOSE_LOG) {
10598             Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
10599         }
10600 
10601         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
10602             if (ui.id == callingUserId || !ui.isManagedProfile()) {
10603                 continue; // Caller user self, or not a managed profile.  Skip.
10604             }
10605             if (VERBOSE_LOG) {
10606                 Log.v(LOG_TAG, "Managed user=" + ui.id);
10607             }
10608             return ui.id;
10609         }
10610         if (VERBOSE_LOG) {
10611             Log.v(LOG_TAG, "Managed user not found.");
10612         }
10613         return -1;
10614     }
10615 
10616     @Override
setBluetoothContactSharingDisabled(ComponentName who, boolean disabled)10617     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
10618         if (!mHasFeature) {
10619             return;
10620         }
10621         Preconditions.checkNotNull(who, "ComponentName is null");
10622         synchronized (getLockObject()) {
10623             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10624                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10625             if (admin.disableBluetoothContactSharing != disabled) {
10626                 admin.disableBluetoothContactSharing = disabled;
10627                 saveSettingsLocked(UserHandle.getCallingUserId());
10628             }
10629         }
10630         DevicePolicyEventLogger
10631                 .createEvent(DevicePolicyEnums.SET_BLUETOOTH_CONTACT_SHARING_DISABLED)
10632                 .setAdmin(who)
10633                 .setBoolean(disabled)
10634                 .write();
10635     }
10636 
10637     @Override
getBluetoothContactSharingDisabled(ComponentName who)10638     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
10639         if (!mHasFeature) {
10640             return false;
10641         }
10642         Preconditions.checkNotNull(who, "ComponentName is null");
10643         synchronized (getLockObject()) {
10644             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10645                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10646             return admin.disableBluetoothContactSharing;
10647         }
10648     }
10649 
10650     @Override
getBluetoothContactSharingDisabledForUser(int userId)10651     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
10652         // TODO: Should there be a check to make sure this relationship is
10653         // within a profile group?
10654         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
10655         synchronized (getLockObject()) {
10656             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
10657             return (admin != null) ? admin.disableBluetoothContactSharing : false;
10658         }
10659     }
10660 
10661     @Override
setLockTaskPackages(ComponentName who, String[] packages)10662     public void setLockTaskPackages(ComponentName who, String[] packages)
10663             throws SecurityException {
10664         Preconditions.checkNotNull(who, "ComponentName is null");
10665         Preconditions.checkNotNull(packages, "packages is null");
10666 
10667         synchronized (getLockObject()) {
10668             enforceCanCallLockTaskLocked(who);
10669             final int userHandle = mInjector.userHandleGetCallingUserId();
10670             setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
10671         }
10672     }
10673 
setLockTaskPackagesLocked(int userHandle, List<String> packages)10674     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
10675         DevicePolicyData policy = getUserData(userHandle);
10676         policy.mLockTaskPackages = packages;
10677 
10678         // Store the settings persistently.
10679         saveSettingsLocked(userHandle);
10680         updateLockTaskPackagesLocked(packages, userHandle);
10681     }
10682 
10683     @Override
getLockTaskPackages(ComponentName who)10684     public String[] getLockTaskPackages(ComponentName who) {
10685         Preconditions.checkNotNull(who, "ComponentName is null");
10686 
10687         final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
10688         synchronized (getLockObject()) {
10689             enforceCanCallLockTaskLocked(who);
10690             final List<String> packages = getUserData(userHandle).mLockTaskPackages;
10691             return packages.toArray(new String[packages.size()]);
10692         }
10693     }
10694 
10695     @Override
isLockTaskPermitted(String pkg)10696     public boolean isLockTaskPermitted(String pkg) {
10697         final int userHandle = mInjector.userHandleGetCallingUserId();
10698         synchronized (getLockObject()) {
10699             return getUserData(userHandle).mLockTaskPackages.contains(pkg);
10700         }
10701     }
10702 
10703     @Override
setLockTaskFeatures(ComponentName who, int flags)10704     public void setLockTaskFeatures(ComponentName who, int flags) {
10705         Preconditions.checkNotNull(who, "ComponentName is null");
10706 
10707         // Throw if Overview is used without Home.
10708         boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0;
10709         boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0;
10710         Preconditions.checkArgument(hasHome || !hasOverview,
10711                 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME");
10712         boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0;
10713         Preconditions.checkArgument(hasHome || !hasNotification,
10714             "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");
10715 
10716         final int userHandle = mInjector.userHandleGetCallingUserId();
10717         synchronized (getLockObject()) {
10718             enforceCanCallLockTaskLocked(who);
10719             setLockTaskFeaturesLocked(userHandle, flags);
10720         }
10721     }
10722 
setLockTaskFeaturesLocked(int userHandle, int flags)10723     private void setLockTaskFeaturesLocked(int userHandle, int flags) {
10724         DevicePolicyData policy = getUserData(userHandle);
10725         policy.mLockTaskFeatures = flags;
10726         saveSettingsLocked(userHandle);
10727         updateLockTaskFeaturesLocked(flags, userHandle);
10728     }
10729 
10730     @Override
getLockTaskFeatures(ComponentName who)10731     public int getLockTaskFeatures(ComponentName who) {
10732         Preconditions.checkNotNull(who, "ComponentName is null");
10733         final int userHandle = mInjector.userHandleGetCallingUserId();
10734         synchronized (getLockObject()) {
10735             enforceCanCallLockTaskLocked(who);
10736             return getUserData(userHandle).mLockTaskFeatures;
10737         }
10738     }
10739 
maybeClearLockTaskPolicyLocked()10740     private void maybeClearLockTaskPolicyLocked() {
10741         final long ident = mInjector.binderClearCallingIdentity();
10742         try {
10743             final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
10744             for (int i = userInfos.size() - 1; i >= 0; i--) {
10745                 int userId = userInfos.get(i).id;
10746                 if (canUserUseLockTaskLocked(userId)) {
10747                     continue;
10748                 }
10749 
10750                 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
10751                 if (!lockTaskPackages.isEmpty()) {
10752                     Slog.d(LOG_TAG,
10753                             "User id " + userId + " not affiliated. Clearing lock task packages");
10754                     setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
10755                 }
10756                 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
10757                 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){
10758                     Slog.d(LOG_TAG,
10759                             "User id " + userId + " not affiliated. Clearing lock task features");
10760                     setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
10761                 }
10762             }
10763         } finally {
10764             mInjector.binderRestoreCallingIdentity(ident);
10765         }
10766     }
10767 
10768     @Override
notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle)10769     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
10770         if (!isCallerWithSystemUid()) {
10771             throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
10772         }
10773         synchronized (getLockObject()) {
10774             final DevicePolicyData policy = getUserData(userHandle);
10775 
10776             if (policy.mStatusBarDisabled) {
10777                 // Status bar is managed by LockTaskController during LockTask, so we cancel this
10778                 // policy when LockTask starts, and reapply it when LockTask ends
10779                 setStatusBarDisabledInternal(!isEnabled, userHandle);
10780             }
10781 
10782             Bundle adminExtras = new Bundle();
10783             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
10784             for (ActiveAdmin admin : policy.mAdminList) {
10785                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
10786                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
10787                 if (ownsDevice || ownsProfile) {
10788                     if (isEnabled) {
10789                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
10790                                 adminExtras, null);
10791                     } else {
10792                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
10793                     }
10794                     DevicePolicyEventLogger
10795                             .createEvent(DevicePolicyEnums.SET_LOCKTASK_MODE_ENABLED)
10796                             .setAdmin(admin.info.getPackageName())
10797                             .setBoolean(isEnabled)
10798                             .setStrings(pkg)
10799                             .write();
10800                 }
10801             }
10802         }
10803     }
10804 
10805     @Override
setGlobalSetting(ComponentName who, String setting, String value)10806     public void setGlobalSetting(ComponentName who, String setting, String value) {
10807         Preconditions.checkNotNull(who, "ComponentName is null");
10808 
10809         synchronized (getLockObject()) {
10810             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10811 
10812             // Some settings are no supported any more. However we do not want to throw a
10813             // SecurityException to avoid breaking apps.
10814             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
10815                 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
10816                 return;
10817             }
10818 
10819             if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)
10820                     && !UserManager.isDeviceInDemoMode(mContext)) {
10821                 throw new SecurityException(String.format(
10822                         "Permission denial: device owners cannot update %1$s", setting));
10823             }
10824 
10825             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
10826                 // ignore if it contradicts an existing policy
10827                 long timeMs = getMaximumTimeToLock(
10828                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
10829                 if (timeMs > 0 && timeMs < Long.MAX_VALUE) {
10830                     return;
10831                 }
10832             }
10833 
10834             long id = mInjector.binderClearCallingIdentity();
10835             try {
10836                 mInjector.settingsGlobalPutString(setting, value);
10837             } finally {
10838                 mInjector.binderRestoreCallingIdentity(id);
10839             }
10840         }
10841     }
10842 
10843     @Override
setSystemSetting(ComponentName who, String setting, String value)10844     public void setSystemSetting(ComponentName who, String setting, String value) {
10845         Preconditions.checkNotNull(who, "ComponentName is null");
10846         Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
10847 
10848         synchronized (getLockObject()) {
10849             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10850 
10851             if (!SYSTEM_SETTINGS_WHITELIST.contains(setting)) {
10852                 throw new SecurityException(String.format(
10853                         "Permission denial: device owners cannot update %1$s", setting));
10854             }
10855 
10856             final int callingUserId = mInjector.userHandleGetCallingUserId();
10857 
10858             mInjector.binderWithCleanCallingIdentity(() ->
10859                 mInjector.settingsSystemPutStringForUser(setting, value, callingUserId));
10860         }
10861     }
10862 
10863     @Override
setTime(ComponentName who, long millis)10864     public boolean setTime(ComponentName who, long millis) {
10865         Preconditions.checkNotNull(who, "ComponentName is null in setTime");
10866         enforceDeviceOwner(who);
10867         // Don't allow set time when auto time is on.
10868         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
10869             return false;
10870         }
10871         mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
10872         return true;
10873     }
10874 
10875     @Override
setTimeZone(ComponentName who, String timeZone)10876     public boolean setTimeZone(ComponentName who, String timeZone) {
10877         Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone");
10878         enforceDeviceOwner(who);
10879         // Don't allow set timezone when auto timezone is on.
10880         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
10881             return false;
10882         }
10883         mInjector.binderWithCleanCallingIdentity(() ->
10884                 mInjector.getAlarmManager().setTimeZone(timeZone));
10885         return true;
10886     }
10887 
10888     @Override
setSecureSetting(ComponentName who, String setting, String value)10889     public void setSecureSetting(ComponentName who, String setting, String value) {
10890         Preconditions.checkNotNull(who, "ComponentName is null");
10891         int callingUserId = mInjector.userHandleGetCallingUserId();
10892 
10893         synchronized (getLockObject()) {
10894             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10895 
10896             if (isDeviceOwner(who, callingUserId)) {
10897                 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)
10898                         && !isCurrentUserDemo()) {
10899                     throw new SecurityException(String.format(
10900                             "Permission denial: Device owners cannot update %1$s", setting));
10901                 }
10902             } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) {
10903                 throw new SecurityException(String.format(
10904                         "Permission denial: Profile owners cannot update %1$s", setting));
10905             }
10906             if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
10907                 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
10908                     throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
10909                             + " is deprecated. Please use one of the user restrictions "
10910                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
10911                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY + " instead.");
10912                 }
10913                 if (!mUserManager.isManagedProfile(callingUserId)) {
10914                     Slog.e(LOG_TAG, "Ignoring setSecureSetting request for "
10915                             + setting + ". User restriction "
10916                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " or "
10917                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY
10918                             + " should be used instead.");
10919                 } else {
10920                     try {
10921                         setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
10922                                 (Integer.parseInt(value) == 0) ? true : false);
10923                         DevicePolicyEventLogger
10924                                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
10925                                 .setAdmin(who)
10926                                 .setStrings(setting, value)
10927                                 .write();
10928                     } catch (NumberFormatException exc) {
10929                         Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
10930                     }
10931                 }
10932                 return;
10933             }
10934             long id = mInjector.binderClearCallingIdentity();
10935             try {
10936                 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
10937                     final String currentValue = mInjector.settingsSecureGetStringForUser(
10938                             Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
10939                     if (!TextUtils.equals(currentValue, value)) {
10940                         // Tell the content observer that the next change will be due to the owner
10941                         // changing the value. There is a small race condition here that we cannot
10942                         // avoid: Change notifications are sent asynchronously, so it is possible
10943                         // that there are prior notifications queued up before the one we are about
10944                         // to trigger. This is a corner case that will have no impact in practice.
10945                         mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
10946                     }
10947                     getUserData(callingUserId).mCurrentInputMethodSet = true;
10948                     saveSettingsLocked(callingUserId);
10949                 }
10950                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
10951             } finally {
10952                 mInjector.binderRestoreCallingIdentity(id);
10953             }
10954         }
10955         DevicePolicyEventLogger
10956                 .createEvent(DevicePolicyEnums.SET_SECURE_SETTING)
10957                 .setAdmin(who)
10958                 .setStrings(setting, value)
10959                 .write();
10960     }
10961 
10962     @Override
setMasterVolumeMuted(ComponentName who, boolean on)10963     public void setMasterVolumeMuted(ComponentName who, boolean on) {
10964         Preconditions.checkNotNull(who, "ComponentName is null");
10965         synchronized (getLockObject()) {
10966             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10967             setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
10968             DevicePolicyEventLogger
10969                     .createEvent(DevicePolicyEnums.SET_MASTER_VOLUME_MUTED)
10970                     .setAdmin(who)
10971                     .setBoolean(on)
10972                     .write();
10973         }
10974     }
10975 
10976     @Override
isMasterVolumeMuted(ComponentName who)10977     public boolean isMasterVolumeMuted(ComponentName who) {
10978         Preconditions.checkNotNull(who, "ComponentName is null");
10979         synchronized (getLockObject()) {
10980             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10981 
10982             AudioManager audioManager =
10983                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
10984             return audioManager.isMasterMute();
10985         }
10986     }
10987 
10988     @Override
setUserIcon(ComponentName who, Bitmap icon)10989     public void setUserIcon(ComponentName who, Bitmap icon) {
10990         synchronized (getLockObject()) {
10991             Preconditions.checkNotNull(who, "ComponentName is null");
10992             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10993 
10994             int userId = UserHandle.getCallingUserId();
10995             long id = mInjector.binderClearCallingIdentity();
10996             try {
10997                 mUserManagerInternal.setUserIcon(userId, icon);
10998             } finally {
10999                 mInjector.binderRestoreCallingIdentity(id);
11000             }
11001         }
11002         DevicePolicyEventLogger
11003                 .createEvent(DevicePolicyEnums.SET_USER_ICON)
11004                 .setAdmin(who)
11005                 .write();
11006     }
11007 
11008     @Override
setKeyguardDisabled(ComponentName who, boolean disabled)11009     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
11010         Preconditions.checkNotNull(who, "ComponentName is null");
11011         final int userId = mInjector.userHandleGetCallingUserId();
11012         synchronized (getLockObject()) {
11013             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11014             if (!isUserAffiliatedWithDeviceLocked(userId)) {
11015                 throw new SecurityException("Admin " + who +
11016                         " is neither the device owner or affiliated user's profile owner.");
11017             }
11018         }
11019         if (isManagedProfile(userId)) {
11020             throw new SecurityException("Managed profile cannot disable keyguard");
11021         }
11022 
11023         long ident = mInjector.binderClearCallingIdentity();
11024         try {
11025             // disallow disabling the keyguard if a password is currently set
11026             if (disabled && mLockPatternUtils.isSecure(userId)) {
11027                 return false;
11028             }
11029             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
11030             if (disabled) {
11031                 mInjector
11032                         .getIWindowManager()
11033                         .dismissKeyguard(null /* callback */, null /* message */);
11034             }
11035             DevicePolicyEventLogger
11036                     .createEvent(DevicePolicyEnums.SET_KEYGUARD_DISABLED)
11037                     .setAdmin(who)
11038                     .setBoolean(disabled)
11039                     .write();
11040         } catch (RemoteException e) {
11041             // Same process, does not happen.
11042         } finally {
11043             mInjector.binderRestoreCallingIdentity(ident);
11044         }
11045         return true;
11046     }
11047 
11048     @Override
setStatusBarDisabled(ComponentName who, boolean disabled)11049     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
11050         int userId = UserHandle.getCallingUserId();
11051         synchronized (getLockObject()) {
11052             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11053             if (!isUserAffiliatedWithDeviceLocked(userId)) {
11054                 throw new SecurityException("Admin " + who +
11055                         " is neither the device owner or affiliated user's profile owner.");
11056             }
11057             if (isManagedProfile(userId)) {
11058                 throw new SecurityException("Managed profile cannot disable status bar");
11059             }
11060             DevicePolicyData policy = getUserData(userId);
11061             if (policy.mStatusBarDisabled != disabled) {
11062                 boolean isLockTaskMode = false;
11063                 try {
11064                     isLockTaskMode = mInjector.getIActivityTaskManager().getLockTaskModeState()
11065                             != LOCK_TASK_MODE_NONE;
11066                 } catch (RemoteException e) {
11067                     Slog.e(LOG_TAG, "Failed to get LockTask mode");
11068                 }
11069                 if (!isLockTaskMode) {
11070                     if (!setStatusBarDisabledInternal(disabled, userId)) {
11071                         return false;
11072                     }
11073                 }
11074                 policy.mStatusBarDisabled = disabled;
11075                 saveSettingsLocked(userId);
11076             }
11077         }
11078         DevicePolicyEventLogger
11079                 .createEvent(DevicePolicyEnums.SET_STATUS_BAR_DISABLED)
11080                 .setAdmin(who)
11081                 .setBoolean(disabled)
11082                 .write();
11083         return true;
11084     }
11085 
setStatusBarDisabledInternal(boolean disabled, int userId)11086     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
11087         long ident = mInjector.binderClearCallingIdentity();
11088         try {
11089             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
11090                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
11091             if (statusBarService != null) {
11092                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
11093                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
11094                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
11095                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
11096                 return true;
11097             }
11098         } catch (RemoteException e) {
11099             Slog.e(LOG_TAG, "Failed to disable the status bar", e);
11100         } finally {
11101             mInjector.binderRestoreCallingIdentity(ident);
11102         }
11103         return false;
11104     }
11105 
11106     /**
11107      * We need to update the internal state of whether a user has completed setup or a
11108      * device has paired once. After that, we ignore any changes that reset the
11109      * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
11110      * as we don't trust any apps that might try to reset them.
11111      * <p>
11112      * Unfortunately, we don't know which user's setup state was changed, so we write all of
11113      * them.
11114      */
updateUserSetupCompleteAndPaired()11115     void updateUserSetupCompleteAndPaired() {
11116         List<UserInfo> users = mUserManager.getUsers(true);
11117         final int N = users.size();
11118         for (int i = 0; i < N; i++) {
11119             int userHandle = users.get(i).id;
11120             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
11121                     userHandle) != 0) {
11122                 DevicePolicyData policy = getUserData(userHandle);
11123                 if (!policy.mUserSetupComplete) {
11124                     policy.mUserSetupComplete = true;
11125                     synchronized (getLockObject()) {
11126                         saveSettingsLocked(userHandle);
11127                     }
11128                 }
11129             }
11130             if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
11131                     userHandle) != 0) {
11132                 DevicePolicyData policy = getUserData(userHandle);
11133                 if (!policy.mPaired) {
11134                     policy.mPaired = true;
11135                     synchronized (getLockObject()) {
11136                         saveSettingsLocked(userHandle);
11137                     }
11138                 }
11139             }
11140         }
11141     }
11142 
11143     private class SetupContentObserver extends ContentObserver {
11144         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
11145                 Settings.Secure.USER_SETUP_COMPLETE);
11146         private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
11147                 Settings.Global.DEVICE_PROVISIONED);
11148         private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
11149         private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
11150                 Settings.Secure.DEFAULT_INPUT_METHOD);
11151 
11152         @GuardedBy("getLockObject()")
11153         private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
11154 
SetupContentObserver(Handler handler)11155         public SetupContentObserver(Handler handler) {
11156             super(handler);
11157         }
11158 
register()11159         void register() {
11160             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
11161             mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
11162             if (mIsWatch) {
11163                 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
11164             }
11165             mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
11166         }
11167 
11168         @GuardedBy("getLockObject()")
addPendingChangeByOwnerLocked(int userId)11169         private void addPendingChangeByOwnerLocked(int userId) {
11170             mUserIdsWithPendingChangesByOwner.add(userId);
11171         }
11172 
11173         @Override
onChange(boolean selfChange, Uri uri, int userId)11174         public void onChange(boolean selfChange, Uri uri, int userId) {
11175             if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
11176                 updateUserSetupCompleteAndPaired();
11177             } else if (mDeviceProvisioned.equals(uri)) {
11178                 synchronized (getLockObject()) {
11179                     // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
11180                     // is delayed until device is marked as provisioned.
11181                     setDeviceOwnerSystemPropertyLocked();
11182                 }
11183             } else if (mDefaultImeChanged.equals(uri)) {
11184                 synchronized (getLockObject()) {
11185                     if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
11186                         // This change notification was triggered by the owner changing the current
11187                         // IME. Ignore it.
11188                         mUserIdsWithPendingChangesByOwner.remove(userId);
11189                     } else {
11190                         // This change notification was triggered by the user manually changing the
11191                         // current IME.
11192                         getUserData(userId).mCurrentInputMethodSet = false;
11193                         saveSettingsLocked(userId);
11194                     }
11195                 }
11196             }
11197         }
11198     }
11199 
11200     private class DevicePolicyConstantsObserver extends ContentObserver {
11201         final Uri mConstantsUri =
11202                 Settings.Global.getUriFor(Settings.Global.DEVICE_POLICY_CONSTANTS);
11203 
DevicePolicyConstantsObserver(Handler handler)11204         DevicePolicyConstantsObserver(Handler handler) {
11205             super(handler);
11206         }
11207 
register()11208         void register() {
11209             mInjector.registerContentObserver(
11210                     mConstantsUri, /* notifyForDescendents= */ false, this, UserHandle.USER_ALL);
11211         }
11212 
11213         @Override
onChange(boolean selfChange, Uri uri, int userId)11214         public void onChange(boolean selfChange, Uri uri, int userId) {
11215             mConstants = loadConstants();
11216         }
11217     }
11218 
11219     @VisibleForTesting
11220     final class LocalService extends DevicePolicyManagerInternal {
11221         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
11222 
11223         @Override
getCrossProfileWidgetProviders(int profileId)11224         public List<String> getCrossProfileWidgetProviders(int profileId) {
11225             synchronized (getLockObject()) {
11226                 if (mOwners == null) {
11227                     return Collections.emptyList();
11228                 }
11229                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
11230                 if (ownerComponent == null) {
11231                     return Collections.emptyList();
11232                 }
11233 
11234                 DevicePolicyData policy = getUserDataUnchecked(profileId);
11235                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
11236 
11237                 if (admin == null || admin.crossProfileWidgetProviders == null
11238                         || admin.crossProfileWidgetProviders.isEmpty()) {
11239                     return Collections.emptyList();
11240                 }
11241 
11242                 return admin.crossProfileWidgetProviders;
11243             }
11244         }
11245 
11246         @Override
addOnCrossProfileWidgetProvidersChangeListener( OnCrossProfileWidgetProvidersChangeListener listener)11247         public void addOnCrossProfileWidgetProvidersChangeListener(
11248                 OnCrossProfileWidgetProvidersChangeListener listener) {
11249             synchronized (getLockObject()) {
11250                 if (mWidgetProviderListeners == null) {
11251                     mWidgetProviderListeners = new ArrayList<>();
11252                 }
11253                 if (!mWidgetProviderListeners.contains(listener)) {
11254                     mWidgetProviderListeners.add(listener);
11255                 }
11256             }
11257         }
11258 
11259         @Override
isActiveAdminWithPolicy(int uid, int reqPolicy)11260         public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
11261             synchronized (getLockObject()) {
11262                 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
11263             }
11264         }
11265 
notifyCrossProfileProvidersChanged(int userId, List<String> packages)11266         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
11267             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
11268             synchronized (getLockObject()) {
11269                 listeners = new ArrayList<>(mWidgetProviderListeners);
11270             }
11271             final int listenerCount = listeners.size();
11272             for (int i = 0; i < listenerCount; i++) {
11273                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
11274                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
11275             }
11276         }
11277 
11278         @Override
createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin)11279         public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
11280             // This method is called from AM with its lock held, so don't take the DPMS lock.
11281             // b/29242568
11282 
11283             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
11284             if (profileOwner != null) {
11285                 return DevicePolicyManagerService.this
11286                         .createShowAdminSupportIntent(profileOwner, userId);
11287             }
11288 
11289             final Pair<Integer, ComponentName> deviceOwner =
11290                     mOwners.getDeviceOwnerUserIdAndComponent();
11291             if (deviceOwner != null && deviceOwner.first == userId) {
11292                 return DevicePolicyManagerService.this
11293                         .createShowAdminSupportIntent(deviceOwner.second, userId);
11294             }
11295 
11296             // We're not specifying the device admin because there isn't one.
11297             if (useDefaultIfNoAdmin) {
11298                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
11299             }
11300             return null;
11301         }
11302 
11303         @Override
createUserRestrictionSupportIntent(int userId, String userRestriction)11304         public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
11305             final long ident = mInjector.binderClearCallingIdentity();
11306             try {
11307                 final List<UserManager.EnforcingUser> sources = mUserManager
11308                         .getUserRestrictionSources(userRestriction, UserHandle.of(userId));
11309                 if (sources == null || sources.isEmpty()) {
11310                     // The restriction is not enforced.
11311                     return null;
11312                 } else if (sources.size() > 1) {
11313                     // In this case, we'll show an admin support dialog that does not
11314                     // specify the admin.
11315                     // TODO(b/128928355): if this restriction is enforced by multiple DPCs, return
11316                     // the admin for the calling user.
11317                     return DevicePolicyManagerService.this.createShowAdminSupportIntent(
11318                             null, userId);
11319                 }
11320                 final UserManager.EnforcingUser enforcingUser = sources.get(0);
11321                 final int sourceType = enforcingUser.getUserRestrictionSource();
11322                 final int enforcingUserId = enforcingUser.getUserHandle().getIdentifier();
11323                 if (sourceType == UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) {
11324                     // Restriction was enforced by PO
11325                     final ComponentName profileOwner = mOwners.getProfileOwnerComponent(
11326                             enforcingUserId);
11327                     if (profileOwner != null) {
11328                         return DevicePolicyManagerService.this.createShowAdminSupportIntent(
11329                                 profileOwner, enforcingUserId);
11330                     }
11331                 } else if (sourceType == UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) {
11332                     // Restriction was enforced by DO
11333                     final Pair<Integer, ComponentName> deviceOwner =
11334                             mOwners.getDeviceOwnerUserIdAndComponent();
11335                     if (deviceOwner != null) {
11336                         return DevicePolicyManagerService.this.createShowAdminSupportIntent(
11337                                 deviceOwner.second, deviceOwner.first);
11338                     }
11339                 } else if (sourceType == UserManager.RESTRICTION_SOURCE_SYSTEM) {
11340                     /*
11341                      * In this case, the user restriction is enforced by the system.
11342                      * So we won't show an admin support intent, even if it is also
11343                      * enforced by a profile/device owner.
11344                      */
11345                     return null;
11346                 }
11347             } finally {
11348                 mInjector.binderRestoreCallingIdentity(ident);
11349             }
11350             return null;
11351         }
11352 
11353         @Override
isUserAffiliatedWithDevice(int userId)11354         public boolean isUserAffiliatedWithDevice(int userId) {
11355             return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
11356         }
11357 
11358         @Override
canSilentlyInstallPackage(String callerPackage, int callerUid)11359         public boolean canSilentlyInstallPackage(String callerPackage, int callerUid) {
11360             if (callerPackage == null) {
11361                 return false;
11362             }
11363             if (isUserAffiliatedWithDevice(UserHandle.getUserId(callerUid))
11364                     && isActiveAdminWithPolicy(callerUid,
11365                             DeviceAdminInfo.USES_POLICY_PROFILE_OWNER)) {
11366                 // device owner or a profile owner affiliated with the device owner
11367                 return true;
11368             }
11369             return false;
11370         }
11371 
11372         @Override
reportSeparateProfileChallengeChanged(@serIdInt int userId)11373         public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) {
11374             final long ident = mInjector.binderClearCallingIdentity();
11375             try {
11376                 synchronized (getLockObject()) {
11377                     updateMaximumTimeToLockLocked(userId);
11378                     updatePasswordQualityCacheForUserGroup(userId);
11379                 }
11380             } finally {
11381                 mInjector.binderRestoreCallingIdentity(ident);
11382             }
11383             DevicePolicyEventLogger
11384                     .createEvent(DevicePolicyEnums.SEPARATE_PROFILE_CHALLENGE_CHANGED)
11385                     .setBoolean(isSeparateProfileChallengeEnabled(userId))
11386                     .write();
11387         }
11388 
11389         @Override
canUserHaveUntrustedCredentialReset(@serIdInt int userId)11390         public boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) {
11391             return DevicePolicyManagerService.this.canUserHaveUntrustedCredentialReset(userId);
11392         }
11393 
11394         @Override
getPrintingDisabledReasonForUser(@serIdInt int userId)11395         public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) {
11396             synchronized (getLockObject()) {
11397                 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING,
11398                         UserHandle.of(userId))) {
11399                     Log.e(LOG_TAG, "printing is enabled");
11400                     return null;
11401                 }
11402                 String ownerPackage = mOwners.getProfileOwnerPackage(userId);
11403                 if (ownerPackage == null) {
11404                     ownerPackage = mOwners.getDeviceOwnerPackageName();
11405                 }
11406                 PackageManager pm = mInjector.getPackageManager();
11407                 PackageInfo packageInfo;
11408                 try {
11409                     packageInfo = pm.getPackageInfo(ownerPackage, 0);
11410                 } catch (NameNotFoundException e) {
11411                     Log.e(LOG_TAG, "getPackageInfo error", e);
11412                     return null;
11413                 }
11414                 if (packageInfo == null) {
11415                     Log.e(LOG_TAG, "packageInfo is inexplicably null");
11416                     return null;
11417                 }
11418                 ApplicationInfo appInfo = packageInfo.applicationInfo;
11419                 if (appInfo == null) {
11420                     Log.e(LOG_TAG, "appInfo is inexplicably null");
11421                     return null;
11422                 }
11423                 CharSequence appLabel = pm.getApplicationLabel(appInfo);
11424                 if (appLabel == null) {
11425                     Log.e(LOG_TAG, "appLabel is inexplicably null");
11426                     return null;
11427                 }
11428                 return ((Context) ActivityThread.currentActivityThread().getSystemUiContext())
11429                         .getResources().getString(R.string.printing_disabled_by, appLabel);
11430             }
11431         }
11432 
11433         @Override
getDevicePolicyCache()11434         protected DevicePolicyCache getDevicePolicyCache() {
11435             return mPolicyCache;
11436         }
11437     }
11438 
createShowAdminSupportIntent(ComponentName admin, int userId)11439     private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
11440         // This method is called with AMS lock held, so don't take DPMS lock
11441         final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
11442         intent.putExtra(Intent.EXTRA_USER_ID, userId);
11443         intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
11444         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
11445         return intent;
11446     }
11447 
11448     @Override
createAdminSupportIntent(String restriction)11449     public Intent createAdminSupportIntent(String restriction) {
11450         Preconditions.checkNotNull(restriction);
11451         final int uid = mInjector.binderGetCallingUid();
11452         final int userId = UserHandle.getUserId(uid);
11453         Intent intent = null;
11454         if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
11455                 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
11456             synchronized (getLockObject()) {
11457                 final DevicePolicyData policy = getUserData(userId);
11458                 final int N = policy.mAdminList.size();
11459                 for (int i = 0; i < N; i++) {
11460                     final ActiveAdmin admin = policy.mAdminList.get(i);
11461                     if ((admin.disableCamera &&
11462                                 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
11463                         (admin.disableScreenCapture && DevicePolicyManager
11464                                 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) {
11465                         intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
11466                         break;
11467                     }
11468                 }
11469                 // For the camera, a device owner on a different user can disable it globally,
11470                 // so we need an additional check.
11471                 if (intent == null
11472                         && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
11473                     final ActiveAdmin admin = getDeviceOwnerAdminLocked();
11474                     if (admin != null && admin.disableCamera) {
11475                         intent = createShowAdminSupportIntent(admin.info.getComponent(),
11476                                 mOwners.getDeviceOwnerUserId());
11477                     }
11478                 }
11479             }
11480         } else {
11481             // if valid, |restriction| can only be a user restriction
11482             intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
11483         }
11484         if (intent != null) {
11485             intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
11486         }
11487         return intent;
11488     }
11489 
11490     /**
11491      * Returns true if specified admin is allowed to limit passwords and has a
11492      * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
11493      */
isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality)11494     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
11495         if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
11496             return false;
11497         }
11498         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
11499     }
11500 
11501     @Override
setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy)11502     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
11503         if (policy != null) {
11504             // throws exception if policy type is invalid
11505             policy.validateType();
11506             // throws exception if freeze period is invalid
11507             policy.validateFreezePeriods();
11508             Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
11509             // throws exception if freeze period is incompatible with previous freeze period record
11510             policy.validateAgainstPreviousFreezePeriod(record.first, record.second,
11511                     LocalDate.now());
11512         }
11513         synchronized (getLockObject()) {
11514             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11515             if (policy == null) {
11516                 mOwners.clearSystemUpdatePolicy();
11517             } else {
11518                 mOwners.setSystemUpdatePolicy(policy);
11519                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false);
11520             }
11521             mOwners.writeDeviceOwner();
11522         }
11523         mContext.sendBroadcastAsUser(
11524                 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
11525                 UserHandle.SYSTEM);
11526         DevicePolicyEventLogger
11527                 .createEvent(DevicePolicyEnums.SET_SYSTEM_UPDATE_POLICY)
11528                 .setAdmin(who)
11529                 .setInt(policy != null ? policy.getPolicyType() : 0)
11530                 .write();
11531     }
11532 
11533     @Override
getSystemUpdatePolicy()11534     public SystemUpdatePolicy getSystemUpdatePolicy() {
11535         synchronized (getLockObject()) {
11536             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
11537             if (policy != null && !policy.isValid()) {
11538                 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
11539                 return null;
11540             }
11541             return policy;
11542         }
11543     }
11544 
withinRange(Pair<LocalDate, LocalDate> range, LocalDate date)11545     private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) {
11546         return (!date.isBefore(range.first) && !date.isAfter(range.second));
11547     }
11548 
11549     /**
11550      * keeps track of the last continuous period when the system is under OTA freeze.
11551      *
11552      * DPMS keeps track of the previous dates during which OTA was freezed as a result of an
11553      * system update policy with freeze periods in effect. This is needed to make robust
11554      * validation on new system update polices, for example to prevent the OTA from being
11555      * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period
11556      * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting
11557      * a new freeze period after a few days.
11558      *
11559      * @param saveIfChanged whether to persist the result on disk if freeze period record is
11560      *            updated. This should only be set to {@code false} if there is a guaranteed
11561      *            mOwners.writeDeviceOwner() later in the control flow to reduce the number of
11562      *            disk writes. Otherwise you risk inconsistent on-disk state.
11563      *
11564      * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod
11565      */
updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged)11566     private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) {
11567         Slog.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord");
11568         synchronized (getLockObject()) {
11569             final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
11570             if (policy == null) {
11571                 return;
11572             }
11573             final LocalDate now = LocalDate.now();
11574             final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now);
11575             if (currentPeriod == null) {
11576                 return;
11577             }
11578             final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
11579             final LocalDate start = record.first;
11580             final LocalDate end = record.second;
11581             final boolean changed;
11582             if (end == null || start == null) {
11583                 // Start a new period if there is none at the moment
11584                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
11585             } else if (now.equals(end.plusDays(1))) {
11586                 // Extend the existing period
11587                 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
11588             } else if (now.isAfter(end.plusDays(1))) {
11589                 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) {
11590                     // The device might be off for some period. If the past freeze record
11591                     // is within range of the current freeze period, assume the device was off
11592                     // during the period [end, now] and extend the freeze record to [start, now].
11593                     changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
11594                 } else {
11595                     changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
11596                 }
11597             } else if (now.isBefore(start)) {
11598                 // Systm clock was adjusted backwards, restart record
11599                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
11600             } else /* start <= now <= end */ {
11601                 changed = false;
11602             }
11603             if (changed && saveIfChanged) {
11604                 mOwners.writeDeviceOwner();
11605             }
11606         }
11607     }
11608 
11609     @Override
clearSystemUpdatePolicyFreezePeriodRecord()11610     public void clearSystemUpdatePolicyFreezePeriodRecord() {
11611         enforceShell("clearSystemUpdatePolicyFreezePeriodRecord");
11612         synchronized (getLockObject()) {
11613             // Print out current record to help diagnosed CTS failures
11614             Slog.i(LOG_TAG, "Clear freeze period record: "
11615                     + mOwners.getSystemUpdateFreezePeriodRecordAsString());
11616             if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) {
11617                 mOwners.writeDeviceOwner();
11618             }
11619         }
11620     }
11621 
11622     /**
11623      * Checks if the caller of the method is the device owner app.
11624      *
11625      * @param callerUid UID of the caller.
11626      * @return true if the caller is the device owner app
11627      */
11628     @VisibleForTesting
isCallerDeviceOwner(int callerUid)11629     boolean isCallerDeviceOwner(int callerUid) {
11630         synchronized (getLockObject()) {
11631             if (!mOwners.hasDeviceOwner()) {
11632                 return false;
11633             }
11634             if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
11635                 return false;
11636             }
11637             final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
11638                     .getPackageName();
11639                 try {
11640                     String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid);
11641                     for (String pkg : pkgs) {
11642                         if (deviceOwnerPackageName.equals(pkg)) {
11643                             return true;
11644                         }
11645                     }
11646                 } catch (RemoteException e) {
11647                     return false;
11648                 }
11649         }
11650         return false;
11651     }
11652 
11653     @Override
notifyPendingSystemUpdate(@ullable SystemUpdateInfo info)11654     public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
11655         mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
11656                 "Only the system update service can broadcast update information");
11657 
11658         if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
11659             Slog.w(LOG_TAG, "Only the system update service in the system user " +
11660                     "can broadcast update information.");
11661             return;
11662         }
11663 
11664         if (!mOwners.saveSystemUpdateInfo(info)) {
11665             // Pending system update hasn't changed, don't send duplicate notification.
11666             return;
11667         }
11668 
11669         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
11670                 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
11671                         info == null ? -1 : info.getReceivedTime());
11672 
11673         final long ident = mInjector.binderClearCallingIdentity();
11674         try {
11675             synchronized (getLockObject()) {
11676                 // Broadcast to device owner first if there is one.
11677                 if (mOwners.hasDeviceOwner()) {
11678                     final UserHandle deviceOwnerUser =
11679                             UserHandle.of(mOwners.getDeviceOwnerUserId());
11680                     intent.setComponent(mOwners.getDeviceOwnerComponent());
11681                     mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
11682                 }
11683             }
11684             // Get running users.
11685             final int runningUserIds[];
11686             try {
11687                 runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
11688             } catch (RemoteException e) {
11689                 // Shouldn't happen.
11690                 Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
11691                 return;
11692             }
11693             // Send broadcasts to corresponding profile owners if any.
11694             for (final int userId : runningUserIds) {
11695                 synchronized (getLockObject()) {
11696                     final ComponentName profileOwnerPackage =
11697                             mOwners.getProfileOwnerComponent(userId);
11698                     if (profileOwnerPackage != null) {
11699                         intent.setComponent(profileOwnerPackage);
11700                         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
11701                     }
11702                 }
11703             }
11704         } finally {
11705             mInjector.binderRestoreCallingIdentity(ident);
11706         }
11707     }
11708 
11709     @Override
getPendingSystemUpdate(ComponentName admin)11710     public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
11711         Preconditions.checkNotNull(admin, "ComponentName is null");
11712         enforceProfileOrDeviceOwner(admin);
11713 
11714         return mOwners.getSystemUpdateInfo();
11715     }
11716 
11717     @Override
setPermissionPolicy(ComponentName admin, String callerPackage, int policy)11718     public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
11719             throws RemoteException {
11720         int userId = UserHandle.getCallingUserId();
11721         synchronized (getLockObject()) {
11722             // Ensure the caller is a DO/PO or a permission grant state delegate.
11723             enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
11724                     DELEGATION_PERMISSION_GRANT);
11725             DevicePolicyData userPolicy = getUserData(userId);
11726             if (userPolicy.mPermissionPolicy != policy) {
11727                 userPolicy.mPermissionPolicy = policy;
11728                 saveSettingsLocked(userId);
11729             }
11730         }
11731         final boolean isDelegate = (admin == null);
11732         DevicePolicyEventLogger
11733                 .createEvent(DevicePolicyEnums.SET_PERMISSION_POLICY)
11734                 .setAdmin(callerPackage)
11735                 .setInt(policy)
11736                 .setBoolean(isDelegate)
11737                 .write();
11738     }
11739 
11740     @Override
getPermissionPolicy(ComponentName admin)11741     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
11742         int userId = UserHandle.getCallingUserId();
11743         synchronized (getLockObject()) {
11744             DevicePolicyData userPolicy = getUserData(userId);
11745             return userPolicy.mPermissionPolicy;
11746         }
11747     }
11748 
11749     @Override
setPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission, int grantState, RemoteCallback callback)11750     public void setPermissionGrantState(ComponentName admin, String callerPackage,
11751             String packageName, String permission, int grantState, RemoteCallback callback)
11752             throws RemoteException {
11753         Preconditions.checkNotNull(callback);
11754 
11755         UserHandle user = mInjector.binderGetCallingUserHandle();
11756         synchronized (getLockObject()) {
11757             // Ensure the caller is a DO/PO or a permission grant state delegate.
11758             enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
11759                     DELEGATION_PERMISSION_GRANT);
11760             long ident = mInjector.binderClearCallingIdentity();
11761             try {
11762                 boolean isPostQAdmin = getTargetSdk(callerPackage, user.getIdentifier())
11763                         >= android.os.Build.VERSION_CODES.Q;
11764                 if (!isPostQAdmin) {
11765                     // Legacy admins assume that they cannot control pre-M apps
11766                     if (getTargetSdk(packageName, user.getIdentifier())
11767                             < android.os.Build.VERSION_CODES.M) {
11768                         callback.sendResult(null);
11769                         return;
11770                     }
11771                 }
11772                 try {
11773                     if (!isRuntimePermission(permission)) {
11774                         callback.sendResult(null);
11775                         return;
11776                     }
11777                 } catch (NameNotFoundException e) {
11778                     throw new RemoteException(
11779                             "Cannot check if " + permission + "is a runtime permission", e, false,
11780                             true);
11781                 }
11782 
11783                 if (grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
11784                         || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED
11785                         || grantState == DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT) {
11786                     mInjector.getPermissionControllerManager(user)
11787                             .setRuntimePermissionGrantStateByDeviceAdmin(callerPackage,
11788                                     packageName, permission, grantState, mContext.getMainExecutor(),
11789                                     (permissionWasSet) -> {
11790                                         if (isPostQAdmin && !permissionWasSet) {
11791                                             callback.sendResult(null);
11792                                             return;
11793                                         }
11794 
11795                                         final boolean isDelegate = (admin == null);
11796                                         DevicePolicyEventLogger
11797                                                 .createEvent(DevicePolicyEnums
11798                                                         .SET_PERMISSION_GRANT_STATE)
11799                                                 .setAdmin(callerPackage)
11800                                                 .setStrings(permission)
11801                                                 .setInt(grantState)
11802                                                 .setBoolean(isDelegate)
11803                                                 .write();
11804 
11805                                         callback.sendResult(Bundle.EMPTY);
11806                                     });
11807                 }
11808             } catch (SecurityException e) {
11809                 Slog.e(LOG_TAG, "Could not set permission grant state", e);
11810 
11811                 callback.sendResult(null);
11812             } finally {
11813                 mInjector.binderRestoreCallingIdentity(ident);
11814             }
11815         }
11816     }
11817 
11818     @Override
getPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission)11819     public int getPermissionGrantState(ComponentName admin, String callerPackage,
11820             String packageName, String permission) throws RemoteException {
11821         PackageManager packageManager = mInjector.getPackageManager();
11822 
11823         UserHandle user = mInjector.binderGetCallingUserHandle();
11824         if (!isCallerWithSystemUid()) {
11825             // Ensure the caller is a DO/PO or a permission grant state delegate.
11826             enforceCanManageScope(admin, callerPackage,
11827                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT);
11828         }
11829         synchronized (getLockObject()) {
11830             long ident = mInjector.binderClearCallingIdentity();
11831             try {
11832                 int granted;
11833                 if (getTargetSdk(callerPackage, user.getIdentifier())
11834                         < android.os.Build.VERSION_CODES.Q) {
11835                     // The per-Q behavior was to not check the app-ops state.
11836                     granted = mIPackageManager.checkPermission(permission, packageName,
11837                             user.getIdentifier());
11838                 } else {
11839                     try {
11840                         int uid = packageManager.getPackageUidAsUser(packageName,
11841                                 user.getIdentifier());
11842                         if (PermissionChecker.checkPermissionForPreflight(mContext, permission,
11843                                 PermissionChecker.PID_UNKNOWN, uid, packageName)
11844                                         != PermissionChecker.PERMISSION_GRANTED) {
11845                             granted = PackageManager.PERMISSION_DENIED;
11846                         } else {
11847                             granted = PackageManager.PERMISSION_GRANTED;
11848                         }
11849                     } catch (NameNotFoundException e) {
11850                         throw new RemoteException(
11851                                 "Cannot check if " + permission + "is a runtime permission", e,
11852                                 false, true);
11853                     }
11854                 }
11855                 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
11856                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
11857                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
11858                     // Not controlled by policy
11859                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
11860                 } else {
11861                     // Policy controlled so return result based on permission grant state
11862                     return granted == PackageManager.PERMISSION_GRANTED
11863                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
11864                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
11865                 }
11866             } finally {
11867                 mInjector.binderRestoreCallingIdentity(ident);
11868             }
11869         }
11870     }
11871 
isPackageInstalledForUser(String packageName, int userHandle)11872     boolean isPackageInstalledForUser(String packageName, int userHandle) {
11873         try {
11874             PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
11875                     userHandle);
11876             return (pi != null) && (pi.applicationInfo.flags != 0);
11877         } catch (RemoteException re) {
11878             throw new RuntimeException("Package manager has died", re);
11879         }
11880     }
11881 
isRuntimePermission(String permissionName)11882     public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
11883         final PackageManager packageManager = mInjector.getPackageManager();
11884         PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
11885         return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
11886                 == PermissionInfo.PROTECTION_DANGEROUS;
11887     }
11888 
11889     @Override
isProvisioningAllowed(String action, String packageName)11890     public boolean isProvisioningAllowed(String action, String packageName) {
11891         Preconditions.checkNotNull(packageName);
11892 
11893         final int callingUid = mInjector.binderGetCallingUid();
11894         final long ident = mInjector.binderClearCallingIdentity();
11895         try {
11896             final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
11897                     packageName, UserHandle.getUserId(callingUid));
11898             Preconditions.checkArgument(callingUid == uidForPackage,
11899                     "Caller uid doesn't match the one for the provided package.");
11900         } catch (NameNotFoundException e) {
11901             throw new IllegalArgumentException("Invalid package provided " + packageName, e);
11902         } finally {
11903             mInjector.binderRestoreCallingIdentity(ident);
11904         }
11905 
11906         return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
11907     }
11908 
11909     @Override
checkProvisioningPreCondition(String action, String packageName)11910     public int checkProvisioningPreCondition(String action, String packageName) {
11911         Preconditions.checkNotNull(packageName);
11912         enforceCanManageProfileAndDeviceOwners();
11913         return checkProvisioningPreConditionSkipPermission(action, packageName);
11914     }
11915 
checkProvisioningPreConditionSkipPermission(String action, String packageName)11916     private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
11917         if (!mHasFeature) {
11918             return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
11919         }
11920 
11921         final int callingUserId = mInjector.userHandleGetCallingUserId();
11922         if (action != null) {
11923             switch (action) {
11924                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
11925                     return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
11926                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
11927                     return checkDeviceOwnerProvisioningPreCondition(callingUserId);
11928                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
11929                     return checkManagedUserProvisioningPreCondition(callingUserId);
11930                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
11931                     return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
11932             }
11933         }
11934         throw new IllegalArgumentException("Unknown provisioning action " + action);
11935     }
11936 
11937     /**
11938      * The device owner can only be set before the setup phase of the primary user has completed,
11939      * except for adb command if no accounts or additional users are present on the device.
11940      */
checkDeviceOwnerProvisioningPreConditionLocked(@ullable ComponentName owner, int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb)11941     private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
11942             int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
11943         if (mOwners.hasDeviceOwner()) {
11944             return CODE_HAS_DEVICE_OWNER;
11945         }
11946         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
11947             return CODE_USER_HAS_PROFILE_OWNER;
11948         }
11949         if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
11950             return CODE_USER_NOT_RUNNING;
11951         }
11952         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
11953             return CODE_HAS_PAIRED;
11954         }
11955         if (isAdb) {
11956             // if shell command runs after user setup completed check device status. Otherwise, OK.
11957             if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
11958                 if (!mInjector.userManagerIsSplitSystemUser()) {
11959                     if (mUserManager.getUserCount() > 1) {
11960                         return CODE_NONSYSTEM_USER_EXISTS;
11961                     }
11962                     if (hasIncompatibleAccountsOrNonAdb) {
11963                         return CODE_ACCOUNTS_NOT_EMPTY;
11964                     }
11965                 } else {
11966                     // STOPSHIP Do proper check in split user mode
11967                 }
11968             }
11969             return CODE_OK;
11970         } else {
11971             if (!mInjector.userManagerIsSplitSystemUser()) {
11972                 // In non-split user mode, DO has to be user 0
11973                 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
11974                     return CODE_NOT_SYSTEM_USER;
11975                 }
11976                 // In non-split user mode, only provision DO before setup wizard completes
11977                 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
11978                     return CODE_USER_SETUP_COMPLETED;
11979                 }
11980             } else {
11981                 // STOPSHIP Do proper check in split user mode
11982             }
11983             return CODE_OK;
11984         }
11985     }
11986 
checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId)11987     private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
11988         synchronized (getLockObject()) {
11989             // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
11990             return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
11991                     deviceOwnerUserId, /* isAdb= */ false,
11992                     /* hasIncompatibleAccountsOrNonAdb=*/ true);
11993         }
11994     }
11995 
checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId)11996     private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
11997         if (!hasFeatureManagedUsers()) {
11998             return CODE_MANAGED_USERS_NOT_SUPPORTED;
11999         }
12000         if (callingUserId == UserHandle.USER_SYSTEM
12001                 && mInjector.userManagerIsSplitSystemUser()) {
12002             // Managed-profiles cannot be setup on the system user.
12003             return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
12004         }
12005         if (getProfileOwner(callingUserId) != null) {
12006             // Managed user cannot have a managed profile.
12007             return CODE_USER_HAS_PROFILE_OWNER;
12008         }
12009 
12010         final long ident = mInjector.binderClearCallingIdentity();
12011         try {
12012             final UserHandle callingUserHandle = UserHandle.of(callingUserId);
12013             final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
12014             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
12015                     callingUserHandle)) {
12016                 // An admin can initiate provisioning if it has set the restriction.
12017                 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
12018                         UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
12019                     return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
12020                 }
12021             }
12022             boolean canRemoveProfile = true;
12023             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
12024                     callingUserHandle)) {
12025                 // We can remove a profile if the admin itself has set the restriction.
12026                 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
12027                         UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
12028                         callingUserId)) {
12029                     canRemoveProfile = false;
12030                 }
12031             }
12032             if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
12033                 return CODE_CANNOT_ADD_MANAGED_PROFILE;
12034             }
12035         } finally {
12036             mInjector.binderRestoreCallingIdentity(ident);
12037         }
12038         return CODE_OK;
12039     }
12040 
getOwnerComponent(String packageName, int userId)12041     private ComponentName getOwnerComponent(String packageName, int userId) {
12042         if (isDeviceOwnerPackage(packageName, userId)) {
12043             return mOwners.getDeviceOwnerComponent();
12044         }
12045         if (isProfileOwnerPackage(packageName, userId)) {
12046             return mOwners.getProfileOwnerComponent(userId);
12047         }
12048         return null;
12049     }
12050 
12051     /**
12052      * Return device owner or profile owner set on a given user.
12053      */
getOwnerComponent(int userId)12054     private @Nullable ComponentName getOwnerComponent(int userId) {
12055         synchronized (getLockObject()) {
12056             if (mOwners.getDeviceOwnerUserId() == userId) {
12057                 return mOwners.getDeviceOwnerComponent();
12058             }
12059             if (mOwners.hasProfileOwner(userId)) {
12060                 return mOwners.getProfileOwnerComponent(userId);
12061             }
12062         }
12063         return null;
12064     }
12065 
checkManagedUserProvisioningPreCondition(int callingUserId)12066     private int checkManagedUserProvisioningPreCondition(int callingUserId) {
12067         if (!hasFeatureManagedUsers()) {
12068             return CODE_MANAGED_USERS_NOT_SUPPORTED;
12069         }
12070         if (!mInjector.userManagerIsSplitSystemUser()) {
12071             // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
12072             return CODE_NOT_SYSTEM_USER_SPLIT;
12073         }
12074         if (callingUserId == UserHandle.USER_SYSTEM) {
12075             // System user cannot be a managed user.
12076             return CODE_SYSTEM_USER;
12077         }
12078         if (hasUserSetupCompleted(callingUserId)) {
12079             return CODE_USER_SETUP_COMPLETED;
12080         }
12081         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
12082             return CODE_HAS_PAIRED;
12083         }
12084         return CODE_OK;
12085     }
12086 
checkManagedShareableDeviceProvisioningPreCondition(int callingUserId)12087     private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
12088         if (!mInjector.userManagerIsSplitSystemUser()) {
12089             // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
12090             return CODE_NOT_SYSTEM_USER_SPLIT;
12091         }
12092         return checkDeviceOwnerProvisioningPreCondition(callingUserId);
12093     }
12094 
hasFeatureManagedUsers()12095     private boolean hasFeatureManagedUsers() {
12096         try {
12097             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
12098         } catch (RemoteException e) {
12099             return false;
12100         }
12101     }
12102 
12103     @Override
getWifiMacAddress(ComponentName admin)12104     public String getWifiMacAddress(ComponentName admin) {
12105         // Make sure caller has DO.
12106         enforceDeviceOwner(admin);
12107 
12108         final long ident = mInjector.binderClearCallingIdentity();
12109         try {
12110             String[] macAddresses = mInjector.getWifiManager().getFactoryMacAddresses();
12111             if (macAddresses == null) {
12112                 return null;
12113             }
12114             DevicePolicyEventLogger
12115                     .createEvent(DevicePolicyEnums.GET_WIFI_MAC_ADDRESS)
12116                     .setAdmin(admin)
12117                     .write();
12118             return macAddresses.length > 0 ? macAddresses[0] : null;
12119         } finally {
12120             mInjector.binderRestoreCallingIdentity(ident);
12121         }
12122     }
12123 
12124     /**
12125      * Returns the target sdk version number that the given packageName was built for
12126      * in the given user.
12127      */
getTargetSdk(String packageName, int userId)12128     private int getTargetSdk(String packageName, int userId) {
12129         final ApplicationInfo ai;
12130         try {
12131             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
12132             final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
12133             return targetSdkVersion;
12134         } catch (RemoteException e) {
12135             // Shouldn't happen
12136             return 0;
12137         }
12138     }
12139 
12140     @Override
isManagedProfile(ComponentName admin)12141     public boolean isManagedProfile(ComponentName admin) {
12142         enforceProfileOrDeviceOwner(admin);
12143         return isManagedProfile(mInjector.userHandleGetCallingUserId());
12144     }
12145 
12146     @Override
isSystemOnlyUser(ComponentName admin)12147     public boolean isSystemOnlyUser(ComponentName admin) {
12148         enforceDeviceOwner(admin);
12149         final int callingUserId = mInjector.userHandleGetCallingUserId();
12150         return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
12151     }
12152 
12153     @Override
reboot(ComponentName admin)12154     public void reboot(ComponentName admin) {
12155         Preconditions.checkNotNull(admin);
12156         // Make sure caller has DO.
12157         enforceDeviceOwner(admin);
12158         long ident = mInjector.binderClearCallingIdentity();
12159         try {
12160             // Make sure there are no ongoing calls on the device.
12161             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
12162                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
12163             }
12164             DevicePolicyEventLogger
12165                     .createEvent(DevicePolicyEnums.REBOOT)
12166                     .setAdmin(admin)
12167                     .write();
12168             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
12169         } finally {
12170             mInjector.binderRestoreCallingIdentity(ident);
12171         }
12172     }
12173 
12174     @Override
setShortSupportMessage(@onNull ComponentName who, CharSequence message)12175     public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
12176         if (!mHasFeature) {
12177             return;
12178         }
12179         Preconditions.checkNotNull(who, "ComponentName is null");
12180         final int userHandle = mInjector.userHandleGetCallingUserId();
12181         synchronized (getLockObject()) {
12182             ActiveAdmin admin = getActiveAdminForUidLocked(who,
12183                     mInjector.binderGetCallingUid());
12184             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
12185                 admin.shortSupportMessage = message;
12186                 saveSettingsLocked(userHandle);
12187             }
12188         }
12189         DevicePolicyEventLogger
12190                 .createEvent(DevicePolicyEnums.SET_SHORT_SUPPORT_MESSAGE)
12191                 .setAdmin(who)
12192                 .write();
12193     }
12194 
12195     @Override
getShortSupportMessage(@onNull ComponentName who)12196     public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
12197         if (!mHasFeature) {
12198             return null;
12199         }
12200         Preconditions.checkNotNull(who, "ComponentName is null");
12201         synchronized (getLockObject()) {
12202             ActiveAdmin admin = getActiveAdminForUidLocked(who,
12203                     mInjector.binderGetCallingUid());
12204             return admin.shortSupportMessage;
12205         }
12206     }
12207 
12208     @Override
setLongSupportMessage(@onNull ComponentName who, CharSequence message)12209     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
12210         if (!mHasFeature) {
12211             return;
12212         }
12213         Preconditions.checkNotNull(who, "ComponentName is null");
12214         final int userHandle = mInjector.userHandleGetCallingUserId();
12215         synchronized (getLockObject()) {
12216             ActiveAdmin admin = getActiveAdminForUidLocked(who,
12217                     mInjector.binderGetCallingUid());
12218             if (!TextUtils.equals(admin.longSupportMessage, message)) {
12219                 admin.longSupportMessage = message;
12220                 saveSettingsLocked(userHandle);
12221             }
12222         }
12223         DevicePolicyEventLogger
12224                 .createEvent(DevicePolicyEnums.SET_LONG_SUPPORT_MESSAGE)
12225                 .setAdmin(who)
12226                 .write();
12227     }
12228 
12229     @Override
getLongSupportMessage(@onNull ComponentName who)12230     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
12231         if (!mHasFeature) {
12232             return null;
12233         }
12234         Preconditions.checkNotNull(who, "ComponentName is null");
12235         synchronized (getLockObject()) {
12236             ActiveAdmin admin = getActiveAdminForUidLocked(who,
12237                     mInjector.binderGetCallingUid());
12238             return admin.longSupportMessage;
12239         }
12240     }
12241 
12242     @Override
getShortSupportMessageForUser(@onNull ComponentName who, int userHandle)12243     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
12244         if (!mHasFeature) {
12245             return null;
12246         }
12247         Preconditions.checkNotNull(who, "ComponentName is null");
12248         if (!isCallerWithSystemUid()) {
12249             throw new SecurityException("Only the system can query support message for user");
12250         }
12251         synchronized (getLockObject()) {
12252             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
12253             if (admin != null) {
12254                 return admin.shortSupportMessage;
12255             }
12256         }
12257         return null;
12258     }
12259 
12260     @Override
getLongSupportMessageForUser(@onNull ComponentName who, int userHandle)12261     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
12262         if (!mHasFeature) {
12263             return null;
12264         }
12265         Preconditions.checkNotNull(who, "ComponentName is null");
12266         if (!isCallerWithSystemUid()) {
12267             throw new SecurityException("Only the system can query support message for user");
12268         }
12269         synchronized (getLockObject()) {
12270             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
12271             if (admin != null) {
12272                 return admin.longSupportMessage;
12273             }
12274         }
12275         return null;
12276     }
12277 
12278     @Override
setOrganizationColor(@onNull ComponentName who, int color)12279     public void setOrganizationColor(@NonNull ComponentName who, int color) {
12280         if (!mHasFeature) {
12281             return;
12282         }
12283         Preconditions.checkNotNull(who, "ComponentName is null");
12284         final int userHandle = mInjector.userHandleGetCallingUserId();
12285         enforceManagedProfile(userHandle, "set organization color");
12286         synchronized (getLockObject()) {
12287             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
12288                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12289             admin.organizationColor = color;
12290             saveSettingsLocked(userHandle);
12291         }
12292         DevicePolicyEventLogger
12293                 .createEvent(DevicePolicyEnums.SET_ORGANIZATION_COLOR)
12294                 .setAdmin(who)
12295                 .write();
12296     }
12297 
12298     @Override
setOrganizationColorForUser(int color, int userId)12299     public void setOrganizationColorForUser(int color, int userId) {
12300         if (!mHasFeature) {
12301             return;
12302         }
12303         enforceFullCrossUsersPermission(userId);
12304         enforceManageUsers();
12305         enforceManagedProfile(userId, "set organization color");
12306         synchronized (getLockObject()) {
12307             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
12308             admin.organizationColor = color;
12309             saveSettingsLocked(userId);
12310         }
12311     }
12312 
12313     @Override
getOrganizationColor(@onNull ComponentName who)12314     public int getOrganizationColor(@NonNull ComponentName who) {
12315         if (!mHasFeature) {
12316             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
12317         }
12318         Preconditions.checkNotNull(who, "ComponentName is null");
12319         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
12320         synchronized (getLockObject()) {
12321             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
12322                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12323             return admin.organizationColor;
12324         }
12325     }
12326 
12327     @Override
getOrganizationColorForUser(int userHandle)12328     public int getOrganizationColorForUser(int userHandle) {
12329         if (!mHasFeature) {
12330             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
12331         }
12332         enforceFullCrossUsersPermission(userHandle);
12333         enforceManagedProfile(userHandle, "get organization color");
12334         synchronized (getLockObject()) {
12335             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
12336             return (profileOwner != null)
12337                     ? profileOwner.organizationColor
12338                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
12339         }
12340     }
12341 
12342     @Override
setOrganizationName(@onNull ComponentName who, CharSequence text)12343     public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
12344         if (!mHasFeature) {
12345             return;
12346         }
12347         Preconditions.checkNotNull(who, "ComponentName is null");
12348         final int userHandle = mInjector.userHandleGetCallingUserId();
12349 
12350         synchronized (getLockObject()) {
12351             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
12352                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12353             if (!TextUtils.equals(admin.organizationName, text)) {
12354                 admin.organizationName = (text == null || text.length() == 0)
12355                         ? null : text.toString();
12356                 saveSettingsLocked(userHandle);
12357             }
12358         }
12359     }
12360 
12361     @Override
getOrganizationName(@onNull ComponentName who)12362     public CharSequence getOrganizationName(@NonNull ComponentName who) {
12363         if (!mHasFeature) {
12364             return null;
12365         }
12366         Preconditions.checkNotNull(who, "ComponentName is null");
12367         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
12368         synchronized (getLockObject()) {
12369             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
12370                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12371             return admin.organizationName;
12372         }
12373     }
12374 
12375     @Override
getDeviceOwnerOrganizationName()12376     public CharSequence getDeviceOwnerOrganizationName() {
12377         if (!mHasFeature) {
12378             return null;
12379         }
12380         enforceDeviceOwnerOrManageUsers();
12381         synchronized (getLockObject()) {
12382             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
12383             return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
12384         }
12385     }
12386 
12387     @Override
getOrganizationNameForUser(int userHandle)12388     public CharSequence getOrganizationNameForUser(int userHandle) {
12389         if (!mHasFeature) {
12390             return null;
12391         }
12392         enforceFullCrossUsersPermission(userHandle);
12393         enforceManagedProfile(userHandle, "get organization name");
12394         synchronized (getLockObject()) {
12395             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
12396             return (profileOwner != null)
12397                     ? profileOwner.organizationName
12398                     : null;
12399         }
12400     }
12401 
12402     @Override
setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames)12403     public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) {
12404         Preconditions.checkNotNull(who);
12405         Preconditions.checkNotNull(packageNames);
12406 
12407         if (!mHasFeature) {
12408             return packageNames;
12409         }
12410         synchronized (getLockObject()) {
12411             final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
12412                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12413             final int callingUserId = mInjector.userHandleGetCallingUserId();
12414             final long identity = mInjector.binderClearCallingIdentity();
12415             try {
12416                 final List<String> excludedPkgs
12417                         = removeInvalidPkgsForMeteredDataRestriction(callingUserId, packageNames);
12418                 admin.meteredDisabledPackages = packageNames;
12419                 pushMeteredDisabledPackagesLocked(callingUserId);
12420                 saveSettingsLocked(callingUserId);
12421                 return excludedPkgs;
12422             } finally {
12423                 mInjector.binderRestoreCallingIdentity(identity);
12424             }
12425         }
12426     }
12427 
removeInvalidPkgsForMeteredDataRestriction( int userId, List<String> pkgNames)12428     private List<String> removeInvalidPkgsForMeteredDataRestriction(
12429             int userId, List<String> pkgNames) {
12430         final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId);
12431         final List<String> excludedPkgs = new ArrayList<>();
12432         for (int i = pkgNames.size() - 1; i >= 0; --i) {
12433             final String pkgName = pkgNames.get(i);
12434             // If the package is an active admin, don't restrict it.
12435             if (activeAdmins.contains(pkgName)) {
12436                 excludedPkgs.add(pkgName);
12437                 continue;
12438             }
12439             // If the package doesn't exist, don't restrict it.
12440             try {
12441                 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) {
12442                     excludedPkgs.add(pkgName);
12443                 }
12444             } catch (RemoteException e) {
12445                 // Should not happen
12446             }
12447         }
12448         pkgNames.removeAll(excludedPkgs);
12449         return excludedPkgs;
12450     }
12451 
12452     @Override
getMeteredDataDisabledPackages(ComponentName who)12453     public List<String> getMeteredDataDisabledPackages(ComponentName who) {
12454         Preconditions.checkNotNull(who);
12455 
12456         if (!mHasFeature) {
12457             return new ArrayList<>();
12458         }
12459         synchronized (getLockObject()) {
12460             final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
12461                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12462             return admin.meteredDisabledPackages == null
12463                     ? new ArrayList<>() : admin.meteredDisabledPackages;
12464         }
12465     }
12466 
12467     @Override
isMeteredDataDisabledPackageForUser(ComponentName who, String packageName, int userId)12468     public boolean isMeteredDataDisabledPackageForUser(ComponentName who,
12469             String packageName, int userId) {
12470         Preconditions.checkNotNull(who);
12471 
12472         if (!mHasFeature) {
12473             return false;
12474         }
12475         if (!isCallerWithSystemUid()) {
12476             throw new SecurityException(
12477                     "Only the system can query restricted pkgs for a specific user");
12478         }
12479         synchronized (getLockObject()) {
12480             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
12481             if (admin != null && admin.meteredDisabledPackages != null) {
12482                 return admin.meteredDisabledPackages.contains(packageName);
12483             }
12484         }
12485         return false;
12486     }
12487 
hasGrantProfileOwnerDevcieIdAccessPermission()12488     private boolean hasGrantProfileOwnerDevcieIdAccessPermission() {
12489         return mContext.checkCallingPermission(
12490                 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS)
12491                 == PackageManager.PERMISSION_GRANTED;
12492     }
12493 
12494     @Override
grantDeviceIdsAccessToProfileOwner(ComponentName who, int userId)12495     public void grantDeviceIdsAccessToProfileOwner(ComponentName who, int userId) {
12496         // As the caller is the system, it must specify the component name of the profile owner
12497         // as a sanity / safety check.
12498         Preconditions.checkNotNull(who);
12499 
12500         if (!mHasFeature) {
12501             return;
12502         }
12503 
12504         // Only privileged system apps can grant the Profile Owner access to Device IDs.
12505         if (!(isCallerWithSystemUid() || isAdb()
12506                 || hasGrantProfileOwnerDevcieIdAccessPermission())) {
12507             throw new SecurityException(
12508                     "Only the system can grant Device IDs access for a profile owner.");
12509         }
12510 
12511         if (isAdb() && hasIncompatibleAccountsOrNonAdbNoLock(userId, who)) {
12512             throw new SecurityException(
12513                     "Can only be called from ADB if the device has no accounts.");
12514         }
12515 
12516         // Grant access under lock.
12517         synchronized (getLockObject()) {
12518             // Sanity check: Make sure that the user has a profile owner and that the specified
12519             // component is the profile owner of that user.
12520             if (!isProfileOwner(who, userId)) {
12521                 throw new IllegalArgumentException(String.format(
12522                         "Component %s is not a Profile Owner of user %d",
12523                         who.flattenToString(), userId));
12524             }
12525 
12526             Slog.i(LOG_TAG, String.format("Granting Device ID access to %s, for user %d",
12527                         who.flattenToString(), userId));
12528 
12529             // setProfileOwnerCanAccessDeviceIds will trigger writing of the profile owner
12530             // data, no need to do it manually.
12531             mOwners.setProfileOwnerCanAccessDeviceIds(userId);
12532         }
12533     }
12534 
pushMeteredDisabledPackagesLocked(int userId)12535     private void pushMeteredDisabledPackagesLocked(int userId) {
12536         mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages(
12537                 getMeteredDisabledPackagesLocked(userId), userId);
12538     }
12539 
getMeteredDisabledPackagesLocked(int userId)12540     private Set<String> getMeteredDisabledPackagesLocked(int userId) {
12541         final ComponentName who = getOwnerComponent(userId);
12542         final Set<String> restrictedPkgs = new ArraySet<>();
12543         if (who != null) {
12544             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
12545             if (admin != null && admin.meteredDisabledPackages != null) {
12546                 restrictedPkgs.addAll(admin.meteredDisabledPackages);
12547             }
12548         }
12549         return restrictedPkgs;
12550     }
12551 
12552     @Override
setAffiliationIds(ComponentName admin, List<String> ids)12553     public void setAffiliationIds(ComponentName admin, List<String> ids) {
12554         if (!mHasFeature) {
12555             return;
12556         }
12557         if (ids == null) {
12558             throw new IllegalArgumentException("ids must not be null");
12559         }
12560         for (String id : ids) {
12561             if (TextUtils.isEmpty(id)) {
12562                 throw new IllegalArgumentException("ids must not contain empty string");
12563             }
12564         }
12565 
12566         final Set<String> affiliationIds = new ArraySet<>(ids);
12567         final int callingUserId = mInjector.userHandleGetCallingUserId();
12568         synchronized (getLockObject()) {
12569             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12570             getUserData(callingUserId).mAffiliationIds = affiliationIds;
12571             saveSettingsLocked(callingUserId);
12572             if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
12573                 // Affiliation ids specified by the device owner are additionally stored in
12574                 // UserHandle.USER_SYSTEM's DevicePolicyData.
12575                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
12576                 saveSettingsLocked(UserHandle.USER_SYSTEM);
12577             }
12578 
12579             // Affiliation status for any user, not just the calling user, might have changed.
12580             // The device owner user will still be affiliated after changing its affiliation ids,
12581             // but as a result of that other users might become affiliated or un-affiliated.
12582             maybePauseDeviceWideLoggingLocked();
12583             maybeResumeDeviceWideLoggingLocked();
12584             maybeClearLockTaskPolicyLocked();
12585         }
12586     }
12587 
12588     @Override
getAffiliationIds(ComponentName admin)12589     public List<String> getAffiliationIds(ComponentName admin) {
12590         if (!mHasFeature) {
12591             return Collections.emptyList();
12592         }
12593 
12594         Preconditions.checkNotNull(admin);
12595         synchronized (getLockObject()) {
12596             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12597             return new ArrayList<String>(
12598                     getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
12599         }
12600     }
12601 
12602     @Override
isAffiliatedUser()12603     public boolean isAffiliatedUser() {
12604         if (!mHasFeature) {
12605             return false;
12606         }
12607 
12608         synchronized (getLockObject()) {
12609             return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
12610         }
12611     }
12612 
isUserAffiliatedWithDeviceLocked(int userId)12613     private boolean isUserAffiliatedWithDeviceLocked(int userId) {
12614         if (!mOwners.hasDeviceOwner()) {
12615             return false;
12616         }
12617         if (userId == mOwners.getDeviceOwnerUserId()) {
12618             // The user that the DO is installed on is always affiliated with the device.
12619             return true;
12620         }
12621         if (userId == UserHandle.USER_SYSTEM) {
12622             // The system user is always affiliated in a DO device, even if the DO is set on a
12623             // different user. This could be the case if the DO is set in the primary user
12624             // of a split user device.
12625             return true;
12626         }
12627 
12628         final ComponentName profileOwner = getProfileOwner(userId);
12629         if (profileOwner == null) {
12630             return false;
12631         }
12632 
12633         final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
12634         final Set<String> deviceAffiliationIds =
12635                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
12636         for (String id : userAffiliationIds) {
12637             if (deviceAffiliationIds.contains(id)) {
12638                 return true;
12639             }
12640         }
12641         return false;
12642     }
12643 
areAllUsersAffiliatedWithDeviceLocked()12644     private boolean areAllUsersAffiliatedWithDeviceLocked() {
12645         final long ident = mInjector.binderClearCallingIdentity();
12646         try {
12647             final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
12648             for (int i = 0; i < userInfos.size(); i++) {
12649                 int userId = userInfos.get(i).id;
12650                 if (!isUserAffiliatedWithDeviceLocked(userId)) {
12651                     Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
12652                     return false;
12653                 }
12654             }
12655         } finally {
12656             mInjector.binderRestoreCallingIdentity(ident);
12657         }
12658 
12659         return true;
12660     }
12661 
12662     @Override
setSecurityLoggingEnabled(ComponentName admin, boolean enabled)12663     public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
12664         if (!mHasFeature) {
12665             return;
12666         }
12667         Preconditions.checkNotNull(admin);
12668 
12669         synchronized (getLockObject()) {
12670             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12671             if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
12672                 return;
12673             }
12674             mInjector.securityLogSetLoggingEnabledProperty(enabled);
12675             if (enabled) {
12676                 mSecurityLogMonitor.start();
12677                 maybePauseDeviceWideLoggingLocked();
12678             } else {
12679                 mSecurityLogMonitor.stop();
12680             }
12681         }
12682         DevicePolicyEventLogger
12683                 .createEvent(DevicePolicyEnums.SET_SECURITY_LOGGING_ENABLED)
12684                 .setAdmin(admin)
12685                 .setBoolean(enabled)
12686                 .write();
12687     }
12688 
12689     @Override
isSecurityLoggingEnabled(ComponentName admin)12690     public boolean isSecurityLoggingEnabled(ComponentName admin) {
12691         if (!mHasFeature) {
12692             return false;
12693         }
12694 
12695         synchronized (getLockObject()) {
12696             if (!isCallerWithSystemUid()) {
12697                 Preconditions.checkNotNull(admin);
12698                 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12699             }
12700             return mInjector.securityLogGetLoggingEnabledProperty();
12701         }
12702     }
12703 
recordSecurityLogRetrievalTime()12704     private void recordSecurityLogRetrievalTime() {
12705         synchronized (getLockObject()) {
12706             final long currentTime = System.currentTimeMillis();
12707             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
12708             if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
12709                 policyData.mLastSecurityLogRetrievalTime = currentTime;
12710                 saveSettingsLocked(UserHandle.USER_SYSTEM);
12711             }
12712         }
12713     }
12714 
12715     @Override
retrievePreRebootSecurityLogs(ComponentName admin)12716     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
12717         if (!mHasFeature) {
12718             return null;
12719         }
12720 
12721         Preconditions.checkNotNull(admin);
12722         ensureDeviceOwnerAndAllUsersAffiliated(admin);
12723 
12724         DevicePolicyEventLogger
12725                 .createEvent(DevicePolicyEnums.RETRIEVE_PRE_REBOOT_SECURITY_LOGS)
12726                 .setAdmin(admin)
12727                 .write();
12728 
12729         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
12730                 || !mInjector.securityLogGetLoggingEnabledProperty()) {
12731             return null;
12732         }
12733 
12734         recordSecurityLogRetrievalTime();
12735         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
12736         try {
12737             SecurityLog.readPreviousEvents(output);
12738             return new ParceledListSlice<SecurityEvent>(output);
12739         } catch (IOException e) {
12740             Slog.w(LOG_TAG, "Fail to read previous events" , e);
12741             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
12742         }
12743     }
12744 
12745     @Override
retrieveSecurityLogs(ComponentName admin)12746     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
12747         if (!mHasFeature) {
12748             return null;
12749         }
12750 
12751         Preconditions.checkNotNull(admin);
12752         ensureDeviceOwnerAndAllUsersAffiliated(admin);
12753 
12754         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
12755             return null;
12756         }
12757 
12758         recordSecurityLogRetrievalTime();
12759 
12760         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
12761         DevicePolicyEventLogger
12762                 .createEvent(DevicePolicyEnums.RETRIEVE_SECURITY_LOGS)
12763                 .setAdmin(admin)
12764                 .write();
12765         return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
12766     }
12767 
12768     @Override
forceSecurityLogs()12769     public long forceSecurityLogs() {
12770         enforceShell("forceSecurityLogs");
12771         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
12772             throw new IllegalStateException("logging is not available");
12773         }
12774         return mSecurityLogMonitor.forceLogs();
12775     }
12776 
enforceCanManageDeviceAdmin()12777     private void enforceCanManageDeviceAdmin() {
12778         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
12779                 null);
12780     }
12781 
enforceCanManageProfileAndDeviceOwners()12782     private void enforceCanManageProfileAndDeviceOwners() {
12783         mContext.enforceCallingOrSelfPermission(
12784                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
12785     }
12786 
enforceCallerSystemUserHandle()12787     private void enforceCallerSystemUserHandle() {
12788         final int callingUid = mInjector.binderGetCallingUid();
12789         final int userId = UserHandle.getUserId(callingUid);
12790         if (userId != UserHandle.USER_SYSTEM) {
12791             throw new SecurityException("Caller has to be in user 0");
12792         }
12793     }
12794 
12795     @Override
isUninstallInQueue(final String packageName)12796     public boolean isUninstallInQueue(final String packageName) {
12797         enforceCanManageDeviceAdmin();
12798         final int userId = mInjector.userHandleGetCallingUserId();
12799         Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
12800         synchronized (getLockObject()) {
12801             return mPackagesToRemove.contains(packageUserPair);
12802         }
12803     }
12804 
12805     @Override
uninstallPackageWithActiveAdmins(final String packageName)12806     public void uninstallPackageWithActiveAdmins(final String packageName) {
12807         enforceCanManageDeviceAdmin();
12808         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
12809 
12810         final int userId = mInjector.userHandleGetCallingUserId();
12811 
12812         enforceUserUnlocked(userId);
12813 
12814         final ComponentName profileOwner = getProfileOwner(userId);
12815         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
12816             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
12817         }
12818 
12819         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
12820         if (getDeviceOwnerUserId() == userId && deviceOwner != null
12821                 && packageName.equals(deviceOwner.getPackageName())) {
12822             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
12823         }
12824 
12825         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
12826         synchronized (getLockObject()) {
12827             mPackagesToRemove.add(packageUserPair);
12828         }
12829 
12830         // All active admins on the user.
12831         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
12832 
12833         // Active admins in the target package.
12834         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
12835         if (allActiveAdmins != null) {
12836             for (ComponentName activeAdmin : allActiveAdmins) {
12837                 if (packageName.equals(activeAdmin.getPackageName())) {
12838                     packageActiveAdmins.add(activeAdmin);
12839                     removeActiveAdmin(activeAdmin, userId);
12840                 }
12841             }
12842         }
12843         if (packageActiveAdmins.size() == 0) {
12844             startUninstallIntent(packageName, userId);
12845         } else {
12846             mHandler.postDelayed(new Runnable() {
12847                 @Override
12848                 public void run() {
12849                     for (ComponentName activeAdmin : packageActiveAdmins) {
12850                         removeAdminArtifacts(activeAdmin, userId);
12851                     }
12852                     startUninstallIntent(packageName, userId);
12853                 }
12854             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
12855         }
12856     }
12857 
12858     @Override
isDeviceProvisioned()12859     public boolean isDeviceProvisioned() {
12860         enforceManageUsers();
12861         synchronized (getLockObject()) {
12862             return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
12863         }
12864     }
12865 
isCurrentUserDemo()12866     private boolean isCurrentUserDemo() {
12867         if (UserManager.isDeviceInDemoMode(mContext)) {
12868             final int userId = mInjector.userHandleGetCallingUserId();
12869             final long callingIdentity = mInjector.binderClearCallingIdentity();
12870             try {
12871                 return mUserManager.getUserInfo(userId).isDemo();
12872             } finally {
12873                 mInjector.binderRestoreCallingIdentity(callingIdentity);
12874             }
12875         }
12876         return false;
12877     }
12878 
removePackageIfRequired(final String packageName, final int userId)12879     private void removePackageIfRequired(final String packageName, final int userId) {
12880         if (!packageHasActiveAdmins(packageName, userId)) {
12881             // Will not do anything if uninstall was not requested or was already started.
12882             startUninstallIntent(packageName, userId);
12883         }
12884     }
12885 
startUninstallIntent(final String packageName, final int userId)12886     private void startUninstallIntent(final String packageName, final int userId) {
12887         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
12888         synchronized (getLockObject()) {
12889             if (!mPackagesToRemove.contains(packageUserPair)) {
12890                 // Do nothing if uninstall was not requested or was already started.
12891                 return;
12892             }
12893             mPackagesToRemove.remove(packageUserPair);
12894         }
12895         try {
12896             if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
12897                 // Package does not exist. Nothing to do.
12898                 return;
12899             }
12900         } catch (RemoteException re) {
12901             Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
12902         }
12903 
12904         try { // force stop the package before uninstalling
12905             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
12906         } catch (RemoteException re) {
12907             Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
12908         }
12909         final Uri packageURI = Uri.parse("package:" + packageName);
12910         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
12911         uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
12912         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
12913     }
12914 
12915     /**
12916      * Removes the admin from the policy. Ideally called after the admin's
12917      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
12918      *
12919      * @param adminReceiver The admin to remove
12920      * @param userHandle The user for which this admin has to be removed.
12921      */
removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle)12922     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
12923         synchronized (getLockObject()) {
12924             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
12925             if (admin == null) {
12926                 return;
12927             }
12928             final DevicePolicyData policy = getUserData(userHandle);
12929             final boolean doProxyCleanup = admin.info.usesPolicy(
12930                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
12931             policy.mAdminList.remove(admin);
12932             policy.mAdminMap.remove(adminReceiver);
12933             validatePasswordOwnerLocked(policy);
12934             if (doProxyCleanup) {
12935                 resetGlobalProxyLocked(policy);
12936             }
12937             pushActiveAdminPackagesLocked(userHandle);
12938             pushMeteredDisabledPackagesLocked(userHandle);
12939             saveSettingsLocked(userHandle);
12940             updateMaximumTimeToLockLocked(userHandle);
12941             policy.mRemovingAdmins.remove(adminReceiver);
12942 
12943             Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
12944         }
12945         // The removed admin might have disabled camera, so update user
12946         // restrictions.
12947         pushUserRestrictions(userHandle);
12948     }
12949 
12950     @Override
setDeviceProvisioningConfigApplied()12951     public void setDeviceProvisioningConfigApplied() {
12952         enforceManageUsers();
12953         synchronized (getLockObject()) {
12954             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
12955             policy.mDeviceProvisioningConfigApplied = true;
12956             saveSettingsLocked(UserHandle.USER_SYSTEM);
12957         }
12958     }
12959 
12960     @Override
isDeviceProvisioningConfigApplied()12961     public boolean isDeviceProvisioningConfigApplied() {
12962         enforceManageUsers();
12963         synchronized (getLockObject()) {
12964             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
12965             return policy.mDeviceProvisioningConfigApplied;
12966         }
12967     }
12968 
12969     /**
12970      * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
12971      *
12972      * It's added for testing only. Please use this API carefully if it's used by other system app
12973      * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
12974      * apps.
12975      */
12976     @Override
forceUpdateUserSetupComplete()12977     public void forceUpdateUserSetupComplete() {
12978         enforceCanManageProfileAndDeviceOwners();
12979         enforceCallerSystemUserHandle();
12980         // no effect if it's called from user build
12981         if (!mInjector.isBuildDebuggable()) {
12982             return;
12983         }
12984         final int userId = UserHandle.USER_SYSTEM;
12985         boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
12986                 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
12987         DevicePolicyData policy = getUserData(userId);
12988         policy.mUserSetupComplete = isUserCompleted;
12989         synchronized (getLockObject()) {
12990             saveSettingsLocked(userId);
12991         }
12992     }
12993 
12994     @Override
setBackupServiceEnabled(ComponentName admin, boolean enabled)12995     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
12996         if (!mHasFeature) {
12997             return;
12998         }
12999         Preconditions.checkNotNull(admin);
13000         enforceProfileOrDeviceOwner(admin);
13001         int userId = mInjector.userHandleGetCallingUserId();
13002         toggleBackupServiceActive(userId, enabled);
13003     }
13004 
13005     @Override
isBackupServiceEnabled(ComponentName admin)13006     public boolean isBackupServiceEnabled(ComponentName admin) {
13007         Preconditions.checkNotNull(admin);
13008         if (!mHasFeature) {
13009             return true;
13010         }
13011 
13012         enforceProfileOrDeviceOwner(admin);
13013         synchronized (getLockObject()) {
13014             try {
13015                 IBackupManager ibm = mInjector.getIBackupManager();
13016                 return ibm != null && ibm.isBackupServiceActive(
13017                     mInjector.userHandleGetCallingUserId());
13018             } catch (RemoteException e) {
13019                 throw new IllegalStateException("Failed requesting backup service state.", e);
13020             }
13021         }
13022     }
13023 
13024     @Override
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, @NonNull IApplicationThread caller, @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId)13025     public boolean bindDeviceAdminServiceAsUser(
13026             @NonNull ComponentName admin, @NonNull IApplicationThread caller,
13027             @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
13028             @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
13029         if (!mHasFeature) {
13030             return false;
13031         }
13032         Preconditions.checkNotNull(admin);
13033         Preconditions.checkNotNull(caller);
13034         Preconditions.checkNotNull(serviceIntent);
13035         Preconditions.checkArgument(
13036                 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
13037                 "Service intent must be explicit (with a package name or component): "
13038                         + serviceIntent);
13039         Preconditions.checkNotNull(connection);
13040         Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
13041                 "target user id must be different from the calling user id");
13042 
13043         if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
13044             throw new SecurityException("Not allowed to bind to target user id");
13045         }
13046 
13047         final String targetPackage;
13048         synchronized (getLockObject()) {
13049             targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
13050         }
13051 
13052         final long callingIdentity = mInjector.binderClearCallingIdentity();
13053         try {
13054             // Validate and sanitize the incoming service intent.
13055             final Intent sanitizedIntent =
13056                     createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
13057             if (sanitizedIntent == null) {
13058                 // Fail, cannot lookup the target service.
13059                 return false;
13060             }
13061             // Ask ActivityManager to bind it. Notice that we are binding the service with the
13062             // caller app instead of DevicePolicyManagerService.
13063             return mInjector.getIActivityManager().bindService(
13064                     caller, activtiyToken, serviceIntent,
13065                     serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
13066                     connection, flags, mContext.getOpPackageName(),
13067                     targetUserId) != 0;
13068         } catch (RemoteException ex) {
13069             // Same process, should not happen.
13070         } finally {
13071             mInjector.binderRestoreCallingIdentity(callingIdentity);
13072         }
13073 
13074         // Failed to bind.
13075         return false;
13076     }
13077 
13078     @Override
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)13079     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
13080         if (!mHasFeature) {
13081             return Collections.emptyList();
13082         }
13083         Preconditions.checkNotNull(admin);
13084 
13085         synchronized (getLockObject()) {
13086             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
13087 
13088             final int callingUserId = mInjector.userHandleGetCallingUserId();
13089             final long callingIdentity = mInjector.binderClearCallingIdentity();
13090             try {
13091                 ArrayList<UserHandle> targetUsers = new ArrayList<>();
13092                 if (!isDeviceOwner(admin, callingUserId)) {
13093                     // Profile owners can only bind to the device owner.
13094                     if (canUserBindToDeviceOwnerLocked(callingUserId)) {
13095                         targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
13096                     }
13097                 } else {
13098                     // Caller is the device owner: Look for profile owners that it can bind to.
13099                     final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
13100                     for (int i = 0; i < userInfos.size(); i++) {
13101                         final int userId = userInfos.get(i).id;
13102                         if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
13103                             targetUsers.add(UserHandle.of(userId));
13104                         }
13105                     }
13106                 }
13107 
13108                 return targetUsers;
13109             } finally {
13110                 mInjector.binderRestoreCallingIdentity(callingIdentity);
13111             }
13112         }
13113     }
13114 
canUserBindToDeviceOwnerLocked(int userId)13115     private boolean canUserBindToDeviceOwnerLocked(int userId) {
13116         // There has to be a device owner, under another user id.
13117         if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
13118             return false;
13119         }
13120 
13121         // The user must have a profile owner that belongs to the same package as the device owner.
13122         if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
13123                 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
13124             return false;
13125         }
13126 
13127         // The user must be affiliated.
13128         return isUserAffiliatedWithDeviceLocked(userId);
13129     }
13130 
13131     /**
13132      * Return true if a given user has any accounts that'll prevent installing a device or profile
13133      * owner {@code owner}.
13134      * - If the user has no accounts, then return false.
13135      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
13136      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
13137      *   ..._DISALLOWED, return true.
13138      * - Otherwise return false.
13139      *
13140      * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
13141      * when the caller is not ADB.
13142      *
13143      * DO NOT CALL IT WITH THE DPMS LOCK HELD.
13144      */
hasIncompatibleAccountsOrNonAdbNoLock( int userId, @Nullable ComponentName owner)13145     private boolean hasIncompatibleAccountsOrNonAdbNoLock(
13146             int userId, @Nullable ComponentName owner) {
13147         if (!isAdb()) {
13148             return true;
13149         }
13150         wtfIfInLock();
13151 
13152         final long token = mInjector.binderClearCallingIdentity();
13153         try {
13154             final AccountManager am = AccountManager.get(mContext);
13155             final Account accounts[] = am.getAccountsAsUser(userId);
13156             if (accounts.length == 0) {
13157                 return false;
13158             }
13159             synchronized (getLockObject()) {
13160                 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
13161                     Log.w(LOG_TAG,
13162                             "Non test-only owner can't be installed with existing accounts.");
13163                     return true;
13164                 }
13165             }
13166 
13167             final String[] feature_allow =
13168                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
13169             final String[] feature_disallow =
13170                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
13171 
13172             boolean compatible = true;
13173             for (Account account : accounts) {
13174                 if (hasAccountFeatures(am, account, feature_disallow)) {
13175                     Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
13176                     compatible = false;
13177                     break;
13178                 }
13179                 if (!hasAccountFeatures(am, account, feature_allow)) {
13180                     Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
13181                     compatible = false;
13182                     break;
13183                 }
13184             }
13185             if (compatible) {
13186                 Log.w(LOG_TAG, "All accounts are compatible");
13187             } else {
13188                 Log.e(LOG_TAG, "Found incompatible accounts");
13189             }
13190             return !compatible;
13191         } finally {
13192             mInjector.binderRestoreCallingIdentity(token);
13193         }
13194     }
13195 
hasAccountFeatures(AccountManager am, Account account, String[] features)13196     private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
13197         try {
13198             return am.hasFeatures(account, features, null, null).getResult();
13199         } catch (Exception e) {
13200             Log.w(LOG_TAG, "Failed to get account feature", e);
13201             return false;
13202         }
13203     }
13204 
isAdb()13205     private boolean isAdb() {
13206         final int callingUid = mInjector.binderGetCallingUid();
13207         return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
13208     }
13209 
13210     @Override
setNetworkLoggingEnabled(@ullable ComponentName admin, @NonNull String packageName, boolean enabled)13211     public void setNetworkLoggingEnabled(@Nullable ComponentName admin,
13212             @NonNull String packageName, boolean enabled) {
13213         if (!mHasFeature) {
13214             return;
13215         }
13216         synchronized (getLockObject()) {
13217             enforceCanManageScope(admin, packageName, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
13218                     DELEGATION_NETWORK_LOGGING);
13219 
13220             if (enabled == isNetworkLoggingEnabledInternalLocked()) {
13221                 // already in the requested state
13222                 return;
13223             }
13224             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
13225             deviceOwner.isNetworkLoggingEnabled = enabled;
13226             if (!enabled) {
13227                 deviceOwner.numNetworkLoggingNotifications = 0;
13228                 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
13229             }
13230             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
13231 
13232             setNetworkLoggingActiveInternal(enabled);
13233 
13234             final boolean isDelegate = (admin == null);
13235             DevicePolicyEventLogger
13236                     .createEvent(DevicePolicyEnums.SET_NETWORK_LOGGING_ENABLED)
13237                     .setAdmin(packageName)
13238                     .setBoolean(isDelegate)
13239                     .setInt(enabled ? 1 : 0)
13240                     .write();
13241         }
13242     }
13243 
setNetworkLoggingActiveInternal(boolean active)13244     private void setNetworkLoggingActiveInternal(boolean active) {
13245         synchronized (getLockObject()) {
13246             final long callingIdentity = mInjector.binderClearCallingIdentity();
13247             try {
13248                 if (active) {
13249                     mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
13250                     if (!mNetworkLogger.startNetworkLogging()) {
13251                         mNetworkLogger = null;
13252                         Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
13253                                 + " service not being available yet.");
13254                     }
13255                     maybePauseDeviceWideLoggingLocked();
13256                     sendNetworkLoggingNotificationLocked();
13257                 } else {
13258                     if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
13259                         Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
13260                                 + " service not being available yet.");
13261                     }
13262                     mNetworkLogger = null;
13263                     mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING);
13264                 }
13265             } finally {
13266                 mInjector.binderRestoreCallingIdentity(callingIdentity);
13267             }
13268         }
13269     }
13270 
13271     @Override
forceNetworkLogs()13272     public long forceNetworkLogs() {
13273         enforceShell("forceNetworkLogs");
13274         synchronized (getLockObject()) {
13275             if (!isNetworkLoggingEnabledInternalLocked()) {
13276                 throw new IllegalStateException("logging is not available");
13277             }
13278             if (mNetworkLogger != null) {
13279                 final long ident = mInjector.binderClearCallingIdentity();
13280                 try {
13281                     return mNetworkLogger.forceBatchFinalization();
13282                 } finally {
13283                     mInjector.binderRestoreCallingIdentity(ident);
13284                 }
13285             }
13286             return 0;
13287         }
13288     }
13289 
13290     /** Pauses security and network logging if there are unaffiliated users on the device */
13291     @GuardedBy("getLockObject()")
maybePauseDeviceWideLoggingLocked()13292     private void maybePauseDeviceWideLoggingLocked() {
13293         if (!areAllUsersAffiliatedWithDeviceLocked()) {
13294             Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
13295                     + "paused if enabled.");
13296             mSecurityLogMonitor.pause();
13297             if (mNetworkLogger != null) {
13298                 mNetworkLogger.pause();
13299             }
13300         }
13301     }
13302 
13303     /** Resumes security and network logging (if they are enabled) if all users are affiliated */
13304     @GuardedBy("getLockObject()")
maybeResumeDeviceWideLoggingLocked()13305     private void maybeResumeDeviceWideLoggingLocked() {
13306         if (areAllUsersAffiliatedWithDeviceLocked()) {
13307             final long ident = mInjector.binderClearCallingIdentity();
13308             try {
13309                 mSecurityLogMonitor.resume();
13310                 if (mNetworkLogger != null) {
13311                     mNetworkLogger.resume();
13312                 }
13313             } finally {
13314                 mInjector.binderRestoreCallingIdentity(ident);
13315             }
13316         }
13317     }
13318 
13319     /** Deletes any security and network logs that might have been collected so far */
13320     @GuardedBy("getLockObject()")
discardDeviceWideLogsLocked()13321     private void discardDeviceWideLogsLocked() {
13322         mSecurityLogMonitor.discardLogs();
13323         if (mNetworkLogger != null) {
13324             mNetworkLogger.discardLogs();
13325         }
13326         // TODO: We should discard pre-boot security logs here too, as otherwise those
13327         // logs (which might contain data from the user just removed) will be
13328         // available after next boot.
13329     }
13330 
13331     @Override
isNetworkLoggingEnabled(@ullable ComponentName admin, @NonNull String packageName)13332     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin,
13333             @NonNull String packageName) {
13334         if (!mHasFeature) {
13335             return false;
13336         }
13337         synchronized (getLockObject()) {
13338             enforceCanManageScopeOrCheckPermission(admin, packageName,
13339                     DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, DELEGATION_NETWORK_LOGGING,
13340                     android.Manifest.permission.MANAGE_USERS);
13341             return isNetworkLoggingEnabledInternalLocked();
13342         }
13343     }
13344 
isNetworkLoggingEnabledInternalLocked()13345     private boolean isNetworkLoggingEnabledInternalLocked() {
13346         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
13347         return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
13348     }
13349 
13350     /*
13351      * A maximum of 1200 events are returned, and the total marshalled size is in the order of
13352      * 100kB, so returning a List instead of ParceledListSlice is acceptable.
13353      * Ideally this would be done with ParceledList, however it only supports homogeneous types.
13354      *
13355      * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
13356      */
13357     @Override
retrieveNetworkLogs(@ullable ComponentName admin, @NonNull String packageName, long batchToken)13358     public List<NetworkEvent> retrieveNetworkLogs(@Nullable ComponentName admin,
13359             @NonNull String packageName, long batchToken) {
13360         if (!mHasFeature) {
13361             return null;
13362         }
13363         enforceCanManageScope(admin, packageName, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
13364                 DELEGATION_NETWORK_LOGGING);
13365         ensureAllUsersAffiliated();
13366 
13367         synchronized (getLockObject()) {
13368             if (mNetworkLogger == null
13369                     || !isNetworkLoggingEnabledInternalLocked()) {
13370                 return null;
13371             }
13372             final boolean isDelegate = (admin == null);
13373             DevicePolicyEventLogger
13374                     .createEvent(DevicePolicyEnums.RETRIEVE_NETWORK_LOGS)
13375                     .setAdmin(packageName)
13376                     .setBoolean(isDelegate)
13377                     .write();
13378 
13379             final long currentTime = System.currentTimeMillis();
13380             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
13381             if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
13382                 policyData.mLastNetworkLogsRetrievalTime = currentTime;
13383                 saveSettingsLocked(UserHandle.USER_SYSTEM);
13384             }
13385             return mNetworkLogger.retrieveLogs(batchToken);
13386         }
13387     }
13388 
sendNetworkLoggingNotificationLocked()13389     private void sendNetworkLoggingNotificationLocked() {
13390         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
13391         if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
13392             return;
13393         }
13394         if (deviceOwner.numNetworkLoggingNotifications >=
13395                 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
13396             return;
13397         }
13398         final long now = System.currentTimeMillis();
13399         if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
13400             return;
13401         }
13402         deviceOwner.numNetworkLoggingNotifications++;
13403         if (deviceOwner.numNetworkLoggingNotifications
13404                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
13405             deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
13406         } else {
13407             deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
13408         }
13409         final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
13410         intent.setPackage("com.android.systemui");
13411         final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
13412                 UserHandle.CURRENT);
13413         Notification notification =
13414                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
13415                 .setSmallIcon(R.drawable.ic_info_outline)
13416                 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
13417                 .setContentText(mContext.getString(R.string.network_logging_notification_text))
13418                 .setTicker(mContext.getString(R.string.network_logging_notification_title))
13419                 .setShowWhen(true)
13420                 .setContentIntent(pendingIntent)
13421                 .setStyle(new Notification.BigTextStyle()
13422                         .bigText(mContext.getString(R.string.network_logging_notification_text)))
13423                 .build();
13424         mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification);
13425         saveSettingsLocked(mOwners.getDeviceOwnerUserId());
13426     }
13427 
13428     /**
13429      * Return the package name of owner in a given user.
13430      */
getOwnerPackageNameForUserLocked(int userId)13431     private String getOwnerPackageNameForUserLocked(int userId) {
13432         return mOwners.getDeviceOwnerUserId() == userId
13433                 ? mOwners.getDeviceOwnerPackageName()
13434                 : mOwners.getProfileOwnerPackage(userId);
13435     }
13436 
13437     /**
13438      * @param rawIntent Original service intent specified by caller. It must be explicit.
13439      * @param expectedPackageName The expected package name of the resolved service.
13440      * @return Intent that have component explicitly set. {@code null} if no service is resolved
13441      *     with the given intent.
13442      * @throws SecurityException if the intent is resolved to an invalid service.
13443      */
createCrossUserServiceIntent( @onNull Intent rawIntent, @NonNull String expectedPackageName, @UserIdInt int targetUserId)13444     private Intent createCrossUserServiceIntent(
13445             @NonNull Intent rawIntent, @NonNull String expectedPackageName,
13446             @UserIdInt int targetUserId) throws RemoteException, SecurityException {
13447         ResolveInfo info = mIPackageManager.resolveService(
13448                 rawIntent,
13449                 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
13450                 0,  // flags
13451                 targetUserId);
13452         if (info == null || info.serviceInfo == null) {
13453             Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
13454                     + " or user " + targetUserId + " is not running");
13455             return null;
13456         }
13457         if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
13458             throw new SecurityException("Only allow to bind service in " + expectedPackageName);
13459         }
13460         // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
13461         if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
13462             throw new SecurityException(
13463                     "Service must be protected by BIND_DEVICE_ADMIN permission");
13464         }
13465         // It is the system server to bind the service, it would be extremely dangerous if it
13466         // can be exploited to bind any service. Set the component explicitly to make sure we
13467         // do not bind anything accidentally.
13468         rawIntent.setComponent(info.serviceInfo.getComponentName());
13469         return rawIntent;
13470     }
13471 
13472     @Override
getLastSecurityLogRetrievalTime()13473     public long getLastSecurityLogRetrievalTime() {
13474         enforceDeviceOwnerOrManageUsers();
13475         return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
13476      }
13477 
13478     @Override
getLastBugReportRequestTime()13479     public long getLastBugReportRequestTime() {
13480         enforceDeviceOwnerOrManageUsers();
13481         return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
13482      }
13483 
13484     @Override
getLastNetworkLogRetrievalTime()13485     public long getLastNetworkLogRetrievalTime() {
13486         enforceDeviceOwnerOrManageUsers();
13487         return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
13488     }
13489 
13490     @Override
setResetPasswordToken(ComponentName admin, byte[] token)13491     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
13492         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
13493             return false;
13494         }
13495         if (token == null || token.length < 32) {
13496             throw new IllegalArgumentException("token must be at least 32-byte long");
13497         }
13498         synchronized (getLockObject()) {
13499             final int userHandle = mInjector.userHandleGetCallingUserId();
13500             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
13501 
13502             DevicePolicyData policy = getUserData(userHandle);
13503             long ident = mInjector.binderClearCallingIdentity();
13504             try {
13505                 if (policy.mPasswordTokenHandle != 0) {
13506                     mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
13507                 }
13508                 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token,
13509                         userHandle, /*EscrowTokenStateChangeCallback*/ null);
13510                 saveSettingsLocked(userHandle);
13511                 return policy.mPasswordTokenHandle != 0;
13512             } finally {
13513                 mInjector.binderRestoreCallingIdentity(ident);
13514             }
13515         }
13516     }
13517 
13518     @Override
clearResetPasswordToken(ComponentName admin)13519     public boolean clearResetPasswordToken(ComponentName admin) {
13520         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
13521             return false;
13522         }
13523         synchronized (getLockObject()) {
13524             final int userHandle = mInjector.userHandleGetCallingUserId();
13525             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
13526 
13527             DevicePolicyData policy = getUserData(userHandle);
13528             if (policy.mPasswordTokenHandle != 0) {
13529                 long ident = mInjector.binderClearCallingIdentity();
13530                 try {
13531                     boolean result = mLockPatternUtils.removeEscrowToken(
13532                             policy.mPasswordTokenHandle, userHandle);
13533                     policy.mPasswordTokenHandle = 0;
13534                     saveSettingsLocked(userHandle);
13535                     return result;
13536                 } finally {
13537                     mInjector.binderRestoreCallingIdentity(ident);
13538                 }
13539             }
13540         }
13541         return false;
13542     }
13543 
13544     @Override
isResetPasswordTokenActive(ComponentName admin)13545     public boolean isResetPasswordTokenActive(ComponentName admin) {
13546         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
13547             return false;
13548         }
13549         synchronized (getLockObject()) {
13550             final int userHandle = mInjector.userHandleGetCallingUserId();
13551             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
13552 
13553             DevicePolicyData policy = getUserData(userHandle);
13554             if (policy.mPasswordTokenHandle != 0) {
13555                 long ident = mInjector.binderClearCallingIdentity();
13556                 try {
13557                     return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle,
13558                             userHandle);
13559                 } finally {
13560                     mInjector.binderRestoreCallingIdentity(ident);
13561                 }
13562             }
13563         }
13564         return false;
13565     }
13566 
13567     @Override
resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, int flags)13568     public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
13569             int flags) {
13570         if (!mHasFeature || !mLockPatternUtils.hasSecureLockScreen()) {
13571             return false;
13572         }
13573         Preconditions.checkNotNull(token);
13574         synchronized (getLockObject()) {
13575             final int userHandle = mInjector.userHandleGetCallingUserId();
13576             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
13577 
13578             DevicePolicyData policy = getUserData(userHandle);
13579             if (policy.mPasswordTokenHandle != 0) {
13580                 final String password = passwordOrNull != null ? passwordOrNull : "";
13581                 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token,
13582                         flags, mInjector.binderGetCallingUid(), userHandle);
13583             } else {
13584                 Slog.w(LOG_TAG, "No saved token handle");
13585             }
13586         }
13587         return false;
13588     }
13589 
13590     @Override
isCurrentInputMethodSetByOwner()13591     public boolean isCurrentInputMethodSetByOwner() {
13592         enforceProfileOwnerOrSystemUser();
13593         return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet;
13594     }
13595 
13596     @Override
getOwnerInstalledCaCerts(@onNull UserHandle user)13597     public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
13598         final int userId = user.getIdentifier();
13599         enforceProfileOwnerOrFullCrossUsersPermission(userId);
13600         synchronized (getLockObject()) {
13601             return new StringParceledListSlice(
13602                     new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
13603         }
13604     }
13605 
13606     @Override
clearApplicationUserData(ComponentName admin, String packageName, IPackageDataObserver callback)13607     public void clearApplicationUserData(ComponentName admin, String packageName,
13608             IPackageDataObserver callback) {
13609         Preconditions.checkNotNull(admin, "ComponentName is null");
13610         Preconditions.checkNotNull(packageName, "packageName is null");
13611         Preconditions.checkNotNull(callback, "callback is null");
13612         enforceProfileOrDeviceOwner(admin);
13613         final int userId = UserHandle.getCallingUserId();
13614 
13615         long ident = mInjector.binderClearCallingIdentity();
13616         try {
13617             ActivityManager.getService().clearApplicationUserData(packageName, false, callback,
13618                     userId);
13619         } catch(RemoteException re) {
13620             // Same process, should not happen.
13621         } catch (SecurityException se) {
13622             // This can happen e.g. for device admin packages, do not throw out the exception,
13623             // because callers have no means to know beforehand for which packages this might
13624             // happen. If so, we send back that removal failed.
13625             Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName,
13626                     se);
13627             try {
13628                 callback.onRemoveCompleted(packageName, false);
13629             } catch (RemoteException re) {
13630                 // Caller is no longer available, ignore
13631             }
13632         } finally {
13633             mInjector.binderRestoreCallingIdentity(ident);
13634         }
13635     }
13636 
13637     @Override
setLogoutEnabled(ComponentName admin, boolean enabled)13638     public void setLogoutEnabled(ComponentName admin, boolean enabled) {
13639         if (!mHasFeature) {
13640             return;
13641         }
13642         Preconditions.checkNotNull(admin);
13643 
13644         synchronized (getLockObject()) {
13645             ActiveAdmin deviceOwner =
13646                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13647 
13648             if (deviceOwner.isLogoutEnabled == enabled) {
13649                 // already in the requested state
13650                 return;
13651             }
13652             deviceOwner.isLogoutEnabled = enabled;
13653             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
13654         }
13655     }
13656 
13657     @Override
isLogoutEnabled()13658     public boolean isLogoutEnabled() {
13659         if (!mHasFeature) {
13660             return false;
13661         }
13662         synchronized (getLockObject()) {
13663             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
13664             return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
13665         }
13666     }
13667 
13668     @Override
getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)13669     public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
13670             String provisioningAction) throws RemoteException {
13671         enforceCanManageProfileAndDeviceOwners();
13672         return new ArrayList<>(
13673                 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
13674     }
13675 
13676     @Override
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)13677     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
13678             @Nullable PersistableBundle bundle) {
13679         if (!mHasFeature) {
13680             return;
13681         }
13682 
13683         Preconditions.checkNotNull(admin, "Admin cannot be null.");
13684         Preconditions.checkNotNull(target, "Target cannot be null.");
13685 
13686         enforceProfileOrDeviceOwner(admin);
13687 
13688         if (admin.equals(target)) {
13689             throw new IllegalArgumentException("Provided administrator and target are "
13690                     + "the same object.");
13691         }
13692 
13693         if (admin.getPackageName().equals(target.getPackageName())) {
13694             throw new IllegalArgumentException("Provided administrator and target have "
13695                     + "the same package name.");
13696         }
13697 
13698         final int callingUserId = mInjector.userHandleGetCallingUserId();
13699         final DevicePolicyData policy = getUserData(callingUserId);
13700         final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId,
13701                 /* throwForMissingPermission= */ true);
13702         checkActiveAdminPrecondition(target, incomingDeviceInfo, policy);
13703         if (!incomingDeviceInfo.supportsTransferOwnership()) {
13704             throw new IllegalArgumentException("Provided target does not support "
13705                     + "ownership transfer.");
13706         }
13707 
13708         final long id = mInjector.binderClearCallingIdentity();
13709         String ownerType = null;
13710         try {
13711             synchronized (getLockObject()) {
13712                 /*
13713                 * We must ensure the whole process is atomic to prevent the device from ending up
13714                 * in an invalid state (e.g. no active admin). This could happen if the device
13715                 * is rebooted or work mode is turned off mid-transfer.
13716                 * In order to guarantee atomicity, we:
13717                 *
13718                 * 1. Save an atomic journal file describing the transfer process
13719                 * 2. Perform the transfer itself
13720                 * 3. Delete the journal file
13721                 *
13722                 * That way if the journal file exists on device boot, we know that the transfer
13723                 * must be reverted back to the original administrator. This logic is implemented in
13724                 * revertTransferOwnershipIfNecessaryLocked.
13725                 * */
13726                 if (bundle == null) {
13727                     bundle = new PersistableBundle();
13728                 }
13729                 if (isProfileOwner(admin, callingUserId)) {
13730                     ownerType = ADMIN_TYPE_PROFILE_OWNER;
13731                     prepareTransfer(admin, target, bundle, callingUserId,
13732                             ADMIN_TYPE_PROFILE_OWNER);
13733                     transferProfileOwnershipLocked(admin, target, callingUserId);
13734                     sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
13735                             getTransferOwnershipAdminExtras(bundle), callingUserId);
13736                     postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId);
13737                     if (isUserAffiliatedWithDeviceLocked(callingUserId)) {
13738                         notifyAffiliatedProfileTransferOwnershipComplete(callingUserId);
13739                     }
13740                 } else if (isDeviceOwner(admin, callingUserId)) {
13741                     ownerType = ADMIN_TYPE_DEVICE_OWNER;
13742                     prepareTransfer(admin, target, bundle, callingUserId,
13743                             ADMIN_TYPE_DEVICE_OWNER);
13744                     transferDeviceOwnershipLocked(admin, target, callingUserId);
13745                     sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
13746                             getTransferOwnershipAdminExtras(bundle));
13747                     postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId);
13748                 }
13749             }
13750         } finally {
13751             mInjector.binderRestoreCallingIdentity(id);
13752         }
13753         DevicePolicyEventLogger
13754                 .createEvent(DevicePolicyEnums.TRANSFER_OWNERSHIP)
13755                 .setAdmin(admin)
13756                 .setStrings(target.getPackageName(), ownerType)
13757                 .write();
13758     }
13759 
prepareTransfer(ComponentName admin, ComponentName target, PersistableBundle bundle, int callingUserId, String adminType)13760     private void prepareTransfer(ComponentName admin, ComponentName target,
13761             PersistableBundle bundle, int callingUserId, String adminType) {
13762         saveTransferOwnershipBundleLocked(bundle, callingUserId);
13763         mTransferOwnershipMetadataManager.saveMetadataFile(
13764                 new TransferOwnershipMetadataManager.Metadata(admin, target,
13765                         callingUserId, adminType));
13766     }
13767 
postTransfer(String broadcast, int callingUserId)13768     private void postTransfer(String broadcast, int callingUserId) {
13769         deleteTransferOwnershipMetadataFileLocked();
13770         sendOwnerChangedBroadcast(broadcast, callingUserId);
13771     }
13772 
notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId)13773     private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) {
13774         final Bundle extras = new Bundle();
13775         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId));
13776         sendDeviceOwnerCommand(
13777                 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras);
13778     }
13779 
13780     /**
13781      * Transfers the profile owner for user with id profileOwnerUserId from admin to target.
13782      */
transferProfileOwnershipLocked(ComponentName admin, ComponentName target, int profileOwnerUserId)13783     private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target,
13784             int profileOwnerUserId) {
13785         transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId);
13786         mOwners.transferProfileOwner(target, profileOwnerUserId);
13787         Slog.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId);
13788         mOwners.writeProfileOwner(profileOwnerUserId);
13789         mDeviceAdminServiceController.startServiceForOwner(
13790                 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner");
13791     }
13792 
13793     /**
13794      * Transfers the device owner for user with id userId from admin to target.
13795      */
transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId)13796     private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) {
13797         transferActiveAdminUncheckedLocked(target, admin, userId);
13798         mOwners.transferDeviceOwnership(target);
13799         Slog.i(LOG_TAG, "Device owner set: " + target + " on user " + userId);
13800         mOwners.writeDeviceOwner();
13801         mDeviceAdminServiceController.startServiceForOwner(
13802                 target.getPackageName(), userId, "transfer-device-owner");
13803     }
13804 
getTransferOwnershipAdminExtras(PersistableBundle bundle)13805     private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) {
13806         Bundle extras = new Bundle();
13807         if (bundle != null) {
13808             extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle);
13809         }
13810         return extras;
13811     }
13812 
13813     @Override
setStartUserSessionMessage( ComponentName admin, CharSequence startUserSessionMessage)13814     public void setStartUserSessionMessage(
13815             ComponentName admin, CharSequence startUserSessionMessage) {
13816         if (!mHasFeature) {
13817             return;
13818         }
13819         Preconditions.checkNotNull(admin);
13820 
13821         final String startUserSessionMessageString =
13822                 startUserSessionMessage != null ? startUserSessionMessage.toString() : null;
13823 
13824         synchronized (getLockObject()) {
13825             final ActiveAdmin deviceOwner =
13826                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13827 
13828             if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) {
13829                 return;
13830             }
13831             deviceOwner.startUserSessionMessage = startUserSessionMessageString;
13832             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
13833         }
13834 
13835         mInjector.getActivityManagerInternal()
13836                 .setSwitchingFromSystemUserMessage(startUserSessionMessageString);
13837     }
13838 
13839     @Override
setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage)13840     public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) {
13841         if (!mHasFeature) {
13842             return;
13843         }
13844         Preconditions.checkNotNull(admin);
13845 
13846         final String endUserSessionMessageString =
13847                 endUserSessionMessage != null ? endUserSessionMessage.toString() : null;
13848 
13849         synchronized (getLockObject()) {
13850             final ActiveAdmin deviceOwner =
13851                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13852 
13853             if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) {
13854                 return;
13855             }
13856             deviceOwner.endUserSessionMessage = endUserSessionMessageString;
13857             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
13858         }
13859 
13860         mInjector.getActivityManagerInternal()
13861                 .setSwitchingToSystemUserMessage(endUserSessionMessageString);
13862     }
13863 
13864     @Override
getStartUserSessionMessage(ComponentName admin)13865     public String getStartUserSessionMessage(ComponentName admin) {
13866         if (!mHasFeature) {
13867             return null;
13868         }
13869         Preconditions.checkNotNull(admin);
13870 
13871         synchronized (getLockObject()) {
13872             final ActiveAdmin deviceOwner =
13873                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13874             return deviceOwner.startUserSessionMessage;
13875         }
13876     }
13877 
13878     @Override
getEndUserSessionMessage(ComponentName admin)13879     public String getEndUserSessionMessage(ComponentName admin) {
13880         if (!mHasFeature) {
13881             return null;
13882         }
13883         Preconditions.checkNotNull(admin);
13884 
13885         synchronized (getLockObject()) {
13886             final ActiveAdmin deviceOwner =
13887                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13888             return deviceOwner.endUserSessionMessage;
13889         }
13890     }
13891 
deleteTransferOwnershipMetadataFileLocked()13892     private void deleteTransferOwnershipMetadataFileLocked() {
13893         mTransferOwnershipMetadataManager.deleteMetadataFile();
13894     }
13895 
13896     @Override
13897     @Nullable
getTransferOwnershipBundle()13898     public PersistableBundle getTransferOwnershipBundle() {
13899         synchronized (getLockObject()) {
13900             final int callingUserId = mInjector.userHandleGetCallingUserId();
13901             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
13902             final File bundleFile = new File(
13903                     mInjector.environmentGetUserSystemDirectory(callingUserId),
13904                     TRANSFER_OWNERSHIP_PARAMETERS_XML);
13905             if (!bundleFile.exists()) {
13906                 return null;
13907             }
13908             try (FileInputStream stream = new FileInputStream(bundleFile)) {
13909                 XmlPullParser parser = Xml.newPullParser();
13910                 parser.setInput(stream, null);
13911                 parser.next();
13912                 return PersistableBundle.restoreFromXml(parser);
13913             } catch (IOException | XmlPullParserException | IllegalArgumentException e) {
13914                 Slog.e(LOG_TAG, "Caught exception while trying to load the "
13915                         + "owner transfer parameters from file " + bundleFile, e);
13916                 return null;
13917             }
13918         }
13919     }
13920 
13921     @Override
addOverrideApn(@onNull ComponentName who, @NonNull ApnSetting apnSetting)13922     public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) {
13923         if (!mHasFeature || !mHasTelephonyFeature) {
13924             return -1;
13925         }
13926         Preconditions.checkNotNull(who, "ComponentName is null in addOverrideApn");
13927         Preconditions.checkNotNull(apnSetting, "ApnSetting is null in addOverrideApn");
13928         enforceDeviceOwner(who);
13929 
13930         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
13931         if (tm != null) {
13932             return mInjector.binderWithCleanCallingIdentity(
13933                     () -> tm.addDevicePolicyOverrideApn(mContext, apnSetting));
13934         } else {
13935             Log.w(LOG_TAG, "TelephonyManager is null when trying to add override apn");
13936             return Telephony.Carriers.INVALID_APN_ID;
13937         }
13938     }
13939 
13940     @Override
updateOverrideApn(@onNull ComponentName who, int apnId, @NonNull ApnSetting apnSetting)13941     public boolean updateOverrideApn(@NonNull ComponentName who, int apnId,
13942             @NonNull ApnSetting apnSetting) {
13943         if (!mHasFeature || !mHasTelephonyFeature) {
13944             return false;
13945         }
13946         Preconditions.checkNotNull(who, "ComponentName is null in updateOverrideApn");
13947         Preconditions.checkNotNull(apnSetting, "ApnSetting is null in updateOverrideApn");
13948         enforceDeviceOwner(who);
13949 
13950         if (apnId < 0) {
13951             return false;
13952         }
13953         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
13954         if (tm != null) {
13955             return mInjector.binderWithCleanCallingIdentity(
13956                     () -> tm.modifyDevicePolicyOverrideApn(mContext, apnId, apnSetting));
13957         } else {
13958             Log.w(LOG_TAG, "TelephonyManager is null when trying to modify override apn");
13959             return false;
13960         }
13961     }
13962 
13963     @Override
removeOverrideApn(@onNull ComponentName who, int apnId)13964     public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) {
13965         if (!mHasFeature || !mHasTelephonyFeature) {
13966             return false;
13967         }
13968         Preconditions.checkNotNull(who, "ComponentName is null in removeOverrideApn");
13969         enforceDeviceOwner(who);
13970 
13971         return removeOverrideApnUnchecked(apnId);
13972     }
13973 
removeOverrideApnUnchecked(int apnId)13974     private boolean removeOverrideApnUnchecked(int apnId) {
13975         if(apnId < 0) {
13976             return false;
13977         }
13978         int numDeleted = 0;
13979         final long id = mInjector.binderClearCallingIdentity();
13980         try {
13981             numDeleted = mContext.getContentResolver().delete(
13982                     Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null);
13983         } finally {
13984             mInjector.binderRestoreCallingIdentity(id);
13985         }
13986         return numDeleted > 0;
13987     }
13988 
13989     @Override
getOverrideApns(@onNull ComponentName who)13990     public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) {
13991         if (!mHasFeature || !mHasTelephonyFeature) {
13992             return Collections.emptyList();
13993         }
13994         Preconditions.checkNotNull(who, "ComponentName is null in getOverrideApns");
13995         enforceDeviceOwner(who);
13996 
13997         return getOverrideApnsUnchecked();
13998     }
13999 
getOverrideApnsUnchecked()14000     private List<ApnSetting> getOverrideApnsUnchecked() {
14001         TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
14002         if (tm != null) {
14003             return mInjector.binderWithCleanCallingIdentity(
14004                     () -> tm.getDevicePolicyOverrideApns(mContext));
14005         }
14006         Log.w(LOG_TAG, "TelephonyManager is null when trying to get override apns");
14007         return Collections.emptyList();
14008     }
14009 
14010     @Override
setOverrideApnsEnabled(@onNull ComponentName who, boolean enabled)14011     public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) {
14012         if (!mHasFeature || !mHasTelephonyFeature) {
14013             return;
14014         }
14015         Preconditions.checkNotNull(who, "ComponentName is null in setOverrideApnEnabled");
14016         enforceDeviceOwner(who);
14017 
14018         setOverrideApnsEnabledUnchecked(enabled);
14019     }
14020 
setOverrideApnsEnabledUnchecked(boolean enabled)14021     private void setOverrideApnsEnabledUnchecked(boolean enabled) {
14022         ContentValues value = new ContentValues();
14023         value.put(ENFORCE_KEY, enabled);
14024         final long id = mInjector.binderClearCallingIdentity();
14025         try {
14026             mContext.getContentResolver().update(
14027                     ENFORCE_MANAGED_URI, value, null, null);
14028         } finally {
14029             mInjector.binderRestoreCallingIdentity(id);
14030         }
14031     }
14032 
14033     @Override
isOverrideApnEnabled(@onNull ComponentName who)14034     public boolean isOverrideApnEnabled(@NonNull ComponentName who) {
14035         if (!mHasFeature || !mHasTelephonyFeature) {
14036             return false;
14037         }
14038         Preconditions.checkNotNull(who, "ComponentName is null in isOverrideApnEnabled");
14039         enforceDeviceOwner(who);
14040 
14041         Cursor enforceCursor;
14042         final long id = mInjector.binderClearCallingIdentity();
14043         try {
14044             enforceCursor = mContext.getContentResolver().query(
14045                     ENFORCE_MANAGED_URI, null, null, null, null);
14046         } finally {
14047             mInjector.binderRestoreCallingIdentity(id);
14048         }
14049 
14050         if (enforceCursor == null) {
14051             return false;
14052         }
14053         try {
14054             if (enforceCursor.moveToFirst()) {
14055                 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1;
14056             }
14057         } catch (IllegalArgumentException e) {
14058             Slog.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain "
14059                     + "correct info.", e);
14060         } finally {
14061             enforceCursor.close();
14062         }
14063         return false;
14064     }
14065 
14066     @VisibleForTesting
saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId)14067     void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) {
14068         final File parametersFile = new File(
14069                 mInjector.environmentGetUserSystemDirectory(userId),
14070                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
14071         final AtomicFile atomicFile = new AtomicFile(parametersFile);
14072         FileOutputStream stream = null;
14073         try {
14074             stream = atomicFile.startWrite();
14075             final XmlSerializer serializer = new FastXmlSerializer();
14076             serializer.setOutput(stream, StandardCharsets.UTF_8.name());
14077             serializer.startDocument(null, true);
14078             serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
14079             bundle.saveToXml(serializer);
14080             serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
14081             serializer.endDocument();
14082             atomicFile.finishWrite(stream);
14083         } catch (IOException | XmlPullParserException e) {
14084             Slog.e(LOG_TAG, "Caught exception while trying to save the "
14085                     + "owner transfer parameters to file " + parametersFile, e);
14086             parametersFile.delete();
14087             atomicFile.failWrite(stream);
14088         }
14089     }
14090 
deleteTransferOwnershipBundleLocked(int userId)14091     void deleteTransferOwnershipBundleLocked(int userId) {
14092         final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId),
14093                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
14094         parametersFile.delete();
14095     }
14096 
maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent, PasswordMetrics metrics)14097     private void maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent,
14098             PasswordMetrics metrics) {
14099         if (SecurityLog.isLoggingEnabled()) {
14100             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
14101             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(),
14102                     userId, affectedUserId, metrics.length, metrics.quality, metrics.letters,
14103                     metrics.nonLetter, metrics.numeric, metrics.upperCase, metrics.lowerCase,
14104                     metrics.symbols);
14105         }
14106     }
14107 
getManagedProvisioningPackage(Context context)14108     private static String getManagedProvisioningPackage(Context context) {
14109         return context.getResources().getString(R.string.config_managed_provisioning_package);
14110     }
14111 
putPrivateDnsSettings(@ullable String mode, @Nullable String host)14112     private void putPrivateDnsSettings(@Nullable String mode, @Nullable String host) {
14113         // Set Private DNS settings using system permissions, as apps cannot write
14114         // to global settings.
14115         long origId = mInjector.binderClearCallingIdentity();
14116         try {
14117             mInjector.settingsGlobalPutString(PRIVATE_DNS_MODE, mode);
14118             mInjector.settingsGlobalPutString(PRIVATE_DNS_SPECIFIER, host);
14119         } finally {
14120             mInjector.binderRestoreCallingIdentity(origId);
14121         }
14122     }
14123 
14124     @Override
setGlobalPrivateDns(@onNull ComponentName who, int mode, String privateDnsHost)14125     public int setGlobalPrivateDns(@NonNull ComponentName who, int mode, String privateDnsHost) {
14126         if (!mHasFeature) {
14127             return PRIVATE_DNS_SET_ERROR_FAILURE_SETTING;
14128         }
14129 
14130         Preconditions.checkNotNull(who, "ComponentName is null");
14131         enforceDeviceOwner(who);
14132 
14133         final int returnCode;
14134 
14135         switch (mode) {
14136             case PRIVATE_DNS_MODE_OPPORTUNISTIC:
14137                 if (!TextUtils.isEmpty(privateDnsHost)) {
14138                     throw new IllegalArgumentException(
14139                             "Host provided for opportunistic mode, but is not needed.");
14140                 }
14141                 putPrivateDnsSettings(ConnectivityManager.PRIVATE_DNS_MODE_OPPORTUNISTIC, null);
14142                 return PRIVATE_DNS_SET_NO_ERROR;
14143             case PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
14144                 if (TextUtils.isEmpty(privateDnsHost)
14145                         || !NetworkUtils.isWeaklyValidatedHostname(privateDnsHost)) {
14146                     throw new IllegalArgumentException(
14147                             String.format("Provided hostname %s is not valid", privateDnsHost));
14148                 }
14149 
14150                 // Connectivity check will have been performed in the DevicePolicyManager before
14151                 // the call here.
14152                 putPrivateDnsSettings(
14153                         ConnectivityManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME,
14154                         privateDnsHost);
14155                 return PRIVATE_DNS_SET_NO_ERROR;
14156             default:
14157                 throw new IllegalArgumentException(
14158                         String.format("Provided mode, %d, is not a valid mode.", mode));
14159         }
14160     }
14161 
14162     @Override
getGlobalPrivateDnsMode(@onNull ComponentName who)14163     public int getGlobalPrivateDnsMode(@NonNull ComponentName who) {
14164         if (!mHasFeature) {
14165             return PRIVATE_DNS_MODE_UNKNOWN;
14166         }
14167 
14168         Preconditions.checkNotNull(who, "ComponentName is null");
14169         enforceDeviceOwner(who);
14170         String currentMode = mInjector.settingsGlobalGetString(PRIVATE_DNS_MODE);
14171         if (currentMode == null) {
14172             currentMode = ConnectivityManager.PRIVATE_DNS_DEFAULT_MODE_FALLBACK;
14173         }
14174         switch (currentMode) {
14175             case ConnectivityManager.PRIVATE_DNS_MODE_OFF:
14176                 return PRIVATE_DNS_MODE_OFF;
14177             case ConnectivityManager.PRIVATE_DNS_MODE_OPPORTUNISTIC:
14178                 return PRIVATE_DNS_MODE_OPPORTUNISTIC;
14179             case ConnectivityManager.PRIVATE_DNS_MODE_PROVIDER_HOSTNAME:
14180                 return PRIVATE_DNS_MODE_PROVIDER_HOSTNAME;
14181         }
14182 
14183         return PRIVATE_DNS_MODE_UNKNOWN;
14184     }
14185 
14186     @Override
getGlobalPrivateDnsHost(@onNull ComponentName who)14187     public String getGlobalPrivateDnsHost(@NonNull ComponentName who) {
14188         if (!mHasFeature) {
14189             return null;
14190         }
14191 
14192         Preconditions.checkNotNull(who, "ComponentName is null");
14193         enforceDeviceOwner(who);
14194 
14195         return mInjector.settingsGlobalGetString(PRIVATE_DNS_SPECIFIER);
14196     }
14197 
14198     @Override
installUpdateFromFile(ComponentName admin, ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback)14199     public void installUpdateFromFile(ComponentName admin,
14200             ParcelFileDescriptor updateFileDescriptor, StartInstallingUpdateCallback callback) {
14201         DevicePolicyEventLogger
14202                 .createEvent(DevicePolicyEnums.INSTALL_SYSTEM_UPDATE)
14203                 .setAdmin(admin)
14204                 .setBoolean(isDeviceAB())
14205                 .write();
14206         enforceDeviceOwner(admin);
14207         final long id = mInjector.binderClearCallingIdentity();
14208         try {
14209             UpdateInstaller updateInstaller;
14210             if (isDeviceAB()) {
14211                 updateInstaller = new AbUpdateInstaller(
14212                         mContext, updateFileDescriptor, callback, mInjector, mConstants);
14213             } else {
14214                 updateInstaller = new NonAbUpdateInstaller(
14215                         mContext, updateFileDescriptor, callback, mInjector, mConstants);
14216             }
14217             updateInstaller.startInstallUpdate();
14218         } finally {
14219             mInjector.binderRestoreCallingIdentity(id);
14220         }
14221     }
14222 
isDeviceAB()14223     private boolean isDeviceAB() {
14224         return "true".equalsIgnoreCase(android.os.SystemProperties
14225                 .get(AB_DEVICE_KEY, ""));
14226     }
14227 
14228     @Override
setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames)14229     public void setCrossProfileCalendarPackages(ComponentName who, List<String> packageNames) {
14230         if (!mHasFeature) {
14231             return;
14232         }
14233         Preconditions.checkNotNull(who, "ComponentName is null");
14234 
14235         synchronized (getLockObject()) {
14236             final ActiveAdmin admin = getActiveAdminForCallerLocked(
14237                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
14238             admin.mCrossProfileCalendarPackages = packageNames;
14239             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
14240         }
14241         DevicePolicyEventLogger
14242                 .createEvent(DevicePolicyEnums.SET_CROSS_PROFILE_CALENDAR_PACKAGES)
14243                 .setAdmin(who)
14244                 .setStrings(packageNames == null ? null
14245                         : packageNames.toArray(new String[packageNames.size()]))
14246                 .write();
14247     }
14248 
14249     @Override
getCrossProfileCalendarPackages(ComponentName who)14250     public List<String> getCrossProfileCalendarPackages(ComponentName who) {
14251         if (!mHasFeature) {
14252             return Collections.emptyList();
14253         }
14254         Preconditions.checkNotNull(who, "ComponentName is null");
14255 
14256         synchronized (getLockObject()) {
14257             final ActiveAdmin admin = getActiveAdminForCallerLocked(
14258                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
14259             return admin.mCrossProfileCalendarPackages;
14260         }
14261     }
14262 
14263     @Override
isPackageAllowedToAccessCalendarForUser(String packageName, int userHandle)14264     public boolean isPackageAllowedToAccessCalendarForUser(String packageName,
14265             int userHandle) {
14266         if (!mHasFeature) {
14267             return false;
14268         }
14269         Preconditions.checkStringNotEmpty(packageName, "Package name is null or empty");
14270 
14271         enforceCrossUsersPermission(userHandle);
14272         synchronized (getLockObject()) {
14273             if (mInjector.settingsSecureGetIntForUser(
14274                     Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED, 0, userHandle) == 0) {
14275                 return false;
14276             }
14277             final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
14278             if (admin != null) {
14279                 if (admin.mCrossProfileCalendarPackages == null) {
14280                     return true;
14281                 }
14282                 return admin.mCrossProfileCalendarPackages.contains(packageName);
14283             }
14284         }
14285         return false;
14286     }
14287 
14288     @Override
getCrossProfileCalendarPackagesForUser(int userHandle)14289     public List<String> getCrossProfileCalendarPackagesForUser(int userHandle) {
14290         if (!mHasFeature) {
14291             return Collections.emptyList();
14292         }
14293         enforceCrossUsersPermission(userHandle);
14294         synchronized (getLockObject()) {
14295             final ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
14296             if (admin != null) {
14297                 return admin.mCrossProfileCalendarPackages;
14298             }
14299         }
14300         return Collections.emptyList();
14301     }
14302 
14303     @Override
isManagedKiosk()14304     public boolean isManagedKiosk() {
14305         if (!mHasFeature) {
14306             return false;
14307         }
14308         enforceManageUsers();
14309         long id = mInjector.binderClearCallingIdentity();
14310         try {
14311             return isManagedKioskInternal();
14312         } catch (RemoteException e) {
14313             throw new IllegalStateException(e);
14314         } finally {
14315             mInjector.binderRestoreCallingIdentity(id);
14316         }
14317     }
14318 
14319     @Override
isUnattendedManagedKiosk()14320     public boolean isUnattendedManagedKiosk() {
14321         if (!mHasFeature) {
14322             return false;
14323         }
14324         enforceManageUsers();
14325         long id = mInjector.binderClearCallingIdentity();
14326         try {
14327             return isManagedKioskInternal()
14328                     && getPowerManagerInternal().wasDeviceIdleFor(UNATTENDED_MANAGED_KIOSK_MS);
14329         } catch (RemoteException e) {
14330             throw new IllegalStateException(e);
14331         } finally {
14332             mInjector.binderRestoreCallingIdentity(id);
14333         }
14334     }
14335 
14336     /**
14337      * Returns whether the device is currently being used as a publicly-accessible dedicated device.
14338      * Assumes that feature checks and permission checks have already been performed, and that the
14339      * calling identity has been cleared.
14340      */
isManagedKioskInternal()14341     private boolean isManagedKioskInternal() throws RemoteException {
14342         return mOwners.hasDeviceOwner()
14343                 && mInjector.getIActivityManager().getLockTaskModeState()
14344                         == ActivityManager.LOCK_TASK_MODE_LOCKED
14345                 && !isLockTaskFeatureEnabled(DevicePolicyManager.LOCK_TASK_FEATURE_SYSTEM_INFO)
14346                 && !deviceHasKeyguard()
14347                 && !inEphemeralUserSession();
14348     }
14349 
isLockTaskFeatureEnabled(int lockTaskFeature)14350     private boolean isLockTaskFeatureEnabled(int lockTaskFeature) throws RemoteException {
14351         int lockTaskFeatures =
14352                 getUserData(mInjector.getIActivityManager().getCurrentUser().id).mLockTaskFeatures;
14353         return (lockTaskFeatures & lockTaskFeature) == lockTaskFeature;
14354     }
14355 
deviceHasKeyguard()14356     private boolean deviceHasKeyguard() {
14357         for (UserInfo userInfo : mUserManager.getUsers()) {
14358             if (mLockPatternUtils.isSecure(userInfo.id)) {
14359                 return true;
14360             }
14361         }
14362         return false;
14363     }
14364 
inEphemeralUserSession()14365     private boolean inEphemeralUserSession() {
14366         for (UserInfo userInfo : mUserManager.getUsers()) {
14367             if (mInjector.getUserManager().isUserEphemeral(userInfo.id)) {
14368                 return true;
14369             }
14370         }
14371         return false;
14372     }
14373 
getPowerManagerInternal()14374     private PowerManagerInternal getPowerManagerInternal() {
14375         return mInjector.getPowerManagerInternal();
14376     }
14377 
14378     @Override
startViewCalendarEventInManagedProfile(String packageName, long eventId, long start, long end, boolean allDay, int flags)14379     public boolean startViewCalendarEventInManagedProfile(String packageName, long eventId,
14380             long start, long end, boolean allDay, int flags) {
14381         if (!mHasFeature) {
14382             return false;
14383         }
14384         Preconditions.checkStringNotEmpty(packageName, "Package name is empty");
14385 
14386         final int callingUid = mInjector.binderGetCallingUid();
14387         final int callingUserId = mInjector.userHandleGetCallingUserId();
14388         if (!isCallingFromPackage(packageName, callingUid)) {
14389             throw new SecurityException("Input package name doesn't align with actual "
14390                     + "calling package.");
14391         }
14392         final long identity = mInjector.binderClearCallingIdentity();
14393         try {
14394             final int workProfileUserId = getManagedUserId(callingUserId);
14395             if (workProfileUserId < 0) {
14396                 return false;
14397             }
14398             if (!isPackageAllowedToAccessCalendarForUser(packageName, workProfileUserId)) {
14399                 Log.d(LOG_TAG, String.format("Package %s is not allowed to access cross-profile"
14400                         + "calendar APIs", packageName));
14401                 return false;
14402             }
14403             final Intent intent = new Intent(
14404                     CalendarContract.ACTION_VIEW_MANAGED_PROFILE_CALENDAR_EVENT);
14405             intent.setPackage(packageName);
14406             intent.putExtra(CalendarContract.EXTRA_EVENT_ID, eventId);
14407             intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, start);
14408             intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, end);
14409             intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, allDay);
14410             intent.setFlags(flags);
14411             try {
14412                 mContext.startActivityAsUser(intent, UserHandle.of(workProfileUserId));
14413             } catch (ActivityNotFoundException e) {
14414                 Log.e(LOG_TAG, "View event activity not found", e);
14415                 return false;
14416             }
14417         } finally {
14418             mInjector.binderRestoreCallingIdentity(identity);
14419         }
14420         return true;
14421     }
14422 
isCallingFromPackage(String packageName, int callingUid)14423     private boolean isCallingFromPackage(String packageName, int callingUid) {
14424         try {
14425             final int packageUid = mInjector.getPackageManager().getPackageUidAsUser(
14426                     packageName, UserHandle.getUserId(callingUid));
14427             return packageUid == callingUid;
14428         } catch (NameNotFoundException e) {
14429             Log.d(LOG_TAG, "Calling package not found", e);
14430             return false;
14431         }
14432     }
14433 
loadConstants()14434     private DevicePolicyConstants loadConstants() {
14435         return DevicePolicyConstants.loadFromString(
14436                 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
14437     }
14438 }
14439