OSDN Git Service

Merge "Prevent getting data from Clipboard if device is locked" into lmp-dev am:...
[android-x86/frameworks-base.git] / services / devicepolicy / java / com / android / server / devicepolicy / DevicePolicyManagerService.java
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.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY;
22 import static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED;
23 import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE;
24 import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED;
25 import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER;
26 import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED;
27 import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED;
28 import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS;
29 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER;
30 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT;
31 import static android.app.admin.DevicePolicyManager.CODE_OK;
32 import static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
33 import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER;
34 import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER;
35 import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING;
36 import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED;
37 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
38 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
39 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
40 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
41 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
42 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
43 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
44 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
45 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
46 import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
47 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
48 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
49 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
50
51 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
52 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
53 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
54 import static org.xmlpull.v1.XmlPullParser.END_TAG;
55 import static org.xmlpull.v1.XmlPullParser.TEXT;
56
57 import android.Manifest.permission;
58 import android.accessibilityservice.AccessibilityServiceInfo;
59 import android.accounts.Account;
60 import android.accounts.AccountManager;
61 import android.annotation.NonNull;
62 import android.annotation.Nullable;
63 import android.annotation.UserIdInt;
64 import android.app.Activity;
65 import android.app.ActivityManager;
66 import android.app.ActivityManagerInternal;
67 import android.app.AlarmManager;
68 import android.app.AppGlobals;
69 import android.app.IActivityManager;
70 import android.app.IApplicationThread;
71 import android.app.IServiceConnection;
72 import android.app.Notification;
73 import android.app.NotificationManager;
74 import android.app.PendingIntent;
75 import android.app.StatusBarManager;
76 import android.app.admin.DeviceAdminInfo;
77 import android.app.admin.DeviceAdminReceiver;
78 import android.app.admin.DevicePolicyManager;
79 import android.app.admin.DevicePolicyManagerInternal;
80 import android.app.admin.IDevicePolicyManager;
81 import android.app.admin.NetworkEvent;
82 import android.app.admin.PasswordMetrics;
83 import android.app.admin.SystemUpdateInfo;
84 import android.app.admin.SecurityLog;
85 import android.app.admin.SecurityLog.SecurityEvent;
86 import android.app.admin.SystemUpdatePolicy;
87 import android.app.backup.IBackupManager;
88 import android.app.trust.TrustManager;
89 import android.content.BroadcastReceiver;
90 import android.content.ComponentName;
91 import android.content.Context;
92 import android.content.Intent;
93 import android.content.IntentFilter;
94 import android.content.pm.ActivityInfo;
95 import android.content.pm.ApplicationInfo;
96 import android.content.pm.IPackageManager;
97 import android.content.pm.PackageInfo;
98 import android.content.pm.PackageManager;
99 import android.content.pm.PackageManager.NameNotFoundException;
100 import android.content.pm.PackageManagerInternal;
101 import android.content.pm.ParceledListSlice;
102 import android.content.pm.PermissionInfo;
103 import android.content.pm.ResolveInfo;
104 import android.content.pm.ServiceInfo;
105 import android.content.pm.StringParceledListSlice;
106 import android.content.pm.UserInfo;
107 import android.content.res.Resources;
108 import android.database.ContentObserver;
109 import android.graphics.Bitmap;
110 import android.graphics.Color;
111 import android.media.AudioManager;
112 import android.media.IAudioService;
113 import android.net.ConnectivityManager;
114 import android.net.IIpConnectivityMetrics;
115 import android.net.ProxyInfo;
116 import android.net.Uri;
117 import android.net.metrics.IpConnectivityLog;
118 import android.net.wifi.WifiInfo;
119 import android.net.wifi.WifiManager;
120 import android.os.Binder;
121 import android.os.Build;
122 import android.os.Bundle;
123 import android.os.Environment;
124 import android.os.FileUtils;
125 import android.os.Handler;
126 import android.os.IBinder;
127 import android.os.Looper;
128 import android.os.ParcelFileDescriptor;
129 import android.os.PersistableBundle;
130 import android.os.PowerManager;
131 import android.os.PowerManagerInternal;
132 import android.os.Process;
133 import android.os.RecoverySystem;
134 import android.os.RemoteCallback;
135 import android.os.RemoteException;
136 import android.os.ServiceManager;
137 import android.os.SystemClock;
138 import android.os.SystemProperties;
139 import android.os.UserHandle;
140 import android.os.UserManager;
141 import android.os.UserManagerInternal;
142 import android.os.storage.StorageManager;
143 import android.provider.ContactsContract.QuickContact;
144 import android.provider.ContactsInternal;
145 import android.provider.Settings;
146 import android.provider.Settings.Global;
147 import android.security.IKeyChainAliasCallback;
148 import android.security.IKeyChainService;
149 import android.security.KeyChain;
150 import android.security.KeyChain.KeyChainConnection;
151 import android.service.persistentdata.PersistentDataBlockManager;
152 import android.telephony.TelephonyManager;
153 import android.text.TextUtils;
154 import android.util.ArrayMap;
155 import android.util.ArraySet;
156 import android.util.EventLog;
157 import android.util.Log;
158 import android.util.Pair;
159 import android.util.Slog;
160 import android.util.SparseArray;
161 import android.util.Xml;
162 import android.view.IWindowManager;
163 import android.view.accessibility.AccessibilityManager;
164 import android.view.accessibility.IAccessibilityManager;
165 import android.view.inputmethod.InputMethodInfo;
166 import android.view.inputmethod.InputMethodManager;
167
168 import com.android.internal.R;
169 import com.android.internal.annotations.GuardedBy;
170 import com.android.internal.annotations.VisibleForTesting;
171 import com.android.internal.logging.MetricsLogger;
172 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
173 import com.android.internal.notification.SystemNotificationChannels;
174 import com.android.internal.os.BackgroundThread;
175 import com.android.internal.statusbar.IStatusBarService;
176 import com.android.internal.util.DumpUtils;
177 import com.android.internal.util.FastXmlSerializer;
178 import com.android.internal.util.JournaledFile;
179 import com.android.internal.util.Preconditions;
180 import com.android.internal.util.XmlUtils;
181 import com.android.internal.widget.LockPatternUtils;
182 import com.android.server.LocalServices;
183 import com.android.server.SystemService;
184 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
185 import com.android.server.pm.UserRestrictionsUtils;
186 import com.google.android.collect.Sets;
187
188 import org.xmlpull.v1.XmlPullParser;
189 import org.xmlpull.v1.XmlPullParserException;
190 import org.xmlpull.v1.XmlSerializer;
191
192 import java.io.File;
193 import java.io.FileDescriptor;
194 import java.io.FileInputStream;
195 import java.io.FileNotFoundException;
196 import java.io.FileOutputStream;
197 import java.io.IOException;
198 import java.io.PrintWriter;
199 import java.nio.charset.StandardCharsets;
200 import java.text.DateFormat;
201 import java.util.ArrayList;
202 import java.util.Arrays;
203 import java.util.Collection;
204 import java.util.Collections;
205 import java.util.Date;
206 import java.util.List;
207 import java.util.Map.Entry;
208 import java.util.Set;
209 import java.util.concurrent.TimeUnit;
210 import java.util.concurrent.atomic.AtomicBoolean;
211
212 /**
213  * Implementation of the device policy APIs.
214  */
215 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
216
217     protected static final String LOG_TAG = "DevicePolicyManager";
218
219     private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
220
221     private static final String DEVICE_POLICIES_XML = "device_policies.xml";
222
223     private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
224
225     private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
226
227     private static final String TAG_STATUS_BAR = "statusbar";
228
229     private static final String ATTR_DISABLED = "disabled";
230
231     private static final String ATTR_NAME = "name";
232
233     private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
234             "do-not-ask-credentials-on-boot";
235
236     private static final String TAG_AFFILIATION_ID = "affiliation-id";
237
238     private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval";
239
240     private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request";
241
242     private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval";
243
244     private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
245
246     private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set";
247
248     private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert";
249
250     private static final String ATTR_ID = "id";
251
252     private static final String ATTR_VALUE = "value";
253
254     private static final String ATTR_ALIAS = "alias";
255
256     private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
257
258     private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token";
259
260     private static final String TAG_PASSWORD_VALIDITY = "password-validity";
261
262     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
263
264     private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
265
266     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
267
268     private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
269             = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
270
271     private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
272     private static final String ATTR_SETUP_COMPLETE = "setup-complete";
273     private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
274     private static final String ATTR_PERMISSION_POLICY = "permission-policy";
275     private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
276             "device-provisioning-config-applied";
277     private static final String ATTR_DEVICE_PAIRED = "device-paired";
278     private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
279     private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
280             = "application-restrictions-manager";
281
282     // Comprehensive list of delegations.
283     private static final String DELEGATIONS[] = {
284         DELEGATION_CERT_INSTALL,
285         DELEGATION_APP_RESTRICTIONS,
286         DELEGATION_BLOCK_UNINSTALL,
287         DELEGATION_ENABLE_SYSTEM_APP,
288         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
289         DELEGATION_PACKAGE_ACCESS,
290         DELEGATION_PERMISSION_GRANT
291     };
292
293     /**
294      *  System property whose value is either "true" or "false", indicating whether
295      *  device owner is present.
296      */
297     private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
298
299     private static final int STATUS_BAR_DISABLE_MASK =
300             StatusBarManager.DISABLE_EXPAND |
301             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
302             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
303             StatusBarManager.DISABLE_SEARCH;
304
305     private static final int STATUS_BAR_DISABLE2_MASK =
306             StatusBarManager.DISABLE2_QUICK_SETTINGS;
307
308     private static final Set<String> SECURE_SETTINGS_WHITELIST;
309     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
310     private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
311     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
312     static {
313         SECURE_SETTINGS_WHITELIST = new ArraySet<>();
314         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
315         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
316         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
317
318         SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
319         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
320         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
321
322         GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
323         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
324         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
325         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
326         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
327         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
328         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
329         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
330         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
331
332         GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
333         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
334         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
335         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
336         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
337         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
338     }
339
340     /**
341      * Keyguard features that when set on a profile affect the profile content or challenge only.
342      * These cannot be set on the managed profile's parent DPM instance
343      */
344     private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
345             DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
346
347     /** Keyguard features that are allowed to be set on a managed profile */
348     private static final int PROFILE_KEYGUARD_FEATURES =
349             PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
350
351     private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
352
353     /**
354      * Minimum timeout in milliseconds after which unlocking with weak auth times out,
355      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
356      */
357     private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
358
359     /**
360      * Strings logged with {@link
361      * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}.
362      */
363     private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
364     private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
365
366     final Context mContext;
367     final Injector mInjector;
368     final IPackageManager mIPackageManager;
369     final UserManager mUserManager;
370     final UserManagerInternal mUserManagerInternal;
371     final TelephonyManager mTelephonyManager;
372     private final LockPatternUtils mLockPatternUtils;
373     private final DevicePolicyConstants mConstants;
374     private final DeviceAdminServiceController mDeviceAdminServiceController;
375
376     /**
377      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
378      * is requested for user u.
379      */
380     private final Set<Pair<String, Integer>> mPackagesToRemove =
381             new ArraySet<Pair<String, Integer>>();
382
383     final LocalService mLocalService;
384
385     // Stores and loads state on device and profile owners.
386     @VisibleForTesting
387     final Owners mOwners;
388
389     private final Binder mToken = new Binder();
390
391     /**
392      * Whether or not device admin feature is supported. If it isn't return defaults for all
393      * public methods.
394      */
395     boolean mHasFeature;
396
397     /**
398      * Whether or not this device is a watch.
399      */
400     boolean mIsWatch;
401
402     private final CertificateMonitor mCertificateMonitor;
403     private final SecurityLogMonitor mSecurityLogMonitor;
404     private NetworkLogger mNetworkLogger;
405
406     private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
407     private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
408
409     private SetupContentObserver mSetupContentObserver;
410
411     private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
412         @Override
413         public void run() {
414             if(mRemoteBugreportServiceIsActive.get()) {
415                 onBugreportFailed();
416             }
417         }
418     };
419
420     /** Listens only if mHasFeature == true. */
421     private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
422
423         @Override
424         public void onReceive(Context context, Intent intent) {
425             if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
426                     && mRemoteBugreportServiceIsActive.get()) {
427                 onBugreportFinished(intent);
428             }
429         }
430     };
431
432     /** Listens only if mHasFeature == true. */
433     private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
434
435         @Override
436         public void onReceive(Context context, Intent intent) {
437             String action = intent.getAction();
438             mInjector.getNotificationManager().cancel(LOG_TAG,
439                     RemoteBugreportUtils.NOTIFICATION_ID);
440             if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
441                 onBugreportSharingAccepted();
442             } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
443                 onBugreportSharingDeclined();
444             }
445             mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
446         }
447     };
448
449     public static final class Lifecycle extends SystemService {
450         private DevicePolicyManagerService mService;
451
452         public Lifecycle(Context context) {
453             super(context);
454             mService = new DevicePolicyManagerService(context);
455         }
456
457         @Override
458         public void onStart() {
459             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
460         }
461
462         @Override
463         public void onBootPhase(int phase) {
464             mService.systemReady(phase);
465         }
466
467         @Override
468         public void onStartUser(int userHandle) {
469             mService.handleStartUser(userHandle);
470         }
471
472         @Override
473         public void onUnlockUser(int userHandle) {
474             mService.handleUnlockUser(userHandle);
475         }
476
477         @Override
478         public void onStopUser(int userHandle) {
479             mService.handleStopUser(userHandle);
480         }
481     }
482
483     public static class DevicePolicyData {
484         @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics();
485         int mFailedPasswordAttempts = 0;
486         boolean mPasswordStateHasBeenSetSinceBoot = false;
487         boolean mPasswordValidAtLastCheckpoint = false;
488
489         int mUserHandle;
490         int mPasswordOwner = -1;
491         long mLastMaximumTimeToLock = -1;
492         boolean mUserSetupComplete = false;
493         boolean mPaired = false;
494         int mUserProvisioningState;
495         int mPermissionPolicy;
496
497         boolean mDeviceProvisioningConfigApplied = false;
498
499         final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
500         final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
501         final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
502
503         // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
504         final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
505
506         // This is the list of component allowed to start lock task mode.
507         List<String> mLockTaskPackages = new ArrayList<>();
508
509         boolean mStatusBarDisabled = false;
510
511         ComponentName mRestrictionsProvider;
512
513         // Map of delegate package to delegation scopes
514         final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>();
515
516         boolean doNotAskCredentialsOnBoot = false;
517
518         Set<String> mAffiliationIds = new ArraySet<>();
519
520         long mLastSecurityLogRetrievalTime = -1;
521
522         long mLastBugReportRequestTime = -1;
523
524         long mLastNetworkLogsRetrievalTime = -1;
525
526         boolean mCurrentInputMethodSet = false;
527
528         // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
529         Set<String> mOwnerInstalledCaCerts = new ArraySet<>();
530
531         // Used for initialization of users created by createAndManageUser.
532         boolean mAdminBroadcastPending = false;
533         PersistableBundle mInitBundle = null;
534
535         long mPasswordTokenHandle = 0;
536
537         public DevicePolicyData(int userHandle) {
538             mUserHandle = userHandle;
539         }
540     }
541
542     final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
543
544     final Handler mHandler;
545     final Handler mBackgroundHandler;
546
547     /** Listens only if mHasFeature == true. */
548     final BroadcastReceiver mReceiver = new BroadcastReceiver() {
549         @Override
550         public void onReceive(Context context, Intent intent) {
551             final String action = intent.getAction();
552             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
553                     getSendingUserId());
554
555             /*
556              * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
557              * however it's too early in the boot process to register with IIpConnectivityMetrics
558              * to listen for events.
559              */
560             if (Intent.ACTION_USER_STARTED.equals(action)
561                     && userHandle == mOwners.getDeviceOwnerUserId()) {
562                 synchronized (DevicePolicyManagerService.this) {
563                     if (isNetworkLoggingEnabledInternalLocked()) {
564                         setNetworkLoggingActiveInternal(true);
565                     }
566                 }
567             }
568             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
569                     && userHandle == mOwners.getDeviceOwnerUserId()
570                     && getDeviceOwnerRemoteBugreportUri() != null) {
571                 IntentFilter filterConsent = new IntentFilter();
572                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
573                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
574                 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
575                 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
576                         RemoteBugreportUtils.NOTIFICATION_ID,
577                         RemoteBugreportUtils.buildNotification(mContext,
578                                 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
579                                 UserHandle.ALL);
580             }
581             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
582                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
583                 if (VERBOSE_LOG) {
584                     Slog.v(LOG_TAG, "Sending password expiration notifications for action "
585                             + action + " for user " + userHandle);
586                 }
587                 mHandler.post(new Runnable() {
588                     @Override
589                     public void run() {
590                         handlePasswordExpirationNotification(userHandle);
591                     }
592                 });
593             }
594
595             if (Intent.ACTION_USER_ADDED.equals(action)) {
596                 sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
597                 synchronized (DevicePolicyManagerService.this) {
598                     // It might take a while for the user to become affiliated. Make security
599                     // and network logging unavailable in the meantime.
600                     maybePauseDeviceWideLoggingLocked();
601                 }
602             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
603                 sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
604                 synchronized (DevicePolicyManagerService.this) {
605                     // Check whether the user is affiliated, *before* removing its data.
606                     boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
607                     removeUserData(userHandle);
608                     if (!isRemovedUserAffiliated) {
609                         // We discard the logs when unaffiliated users are deleted (so that the
610                         // device owner cannot retrieve data about that user after it's gone).
611                         discardDeviceWideLogsLocked();
612                         // Resume logging if all remaining users are affiliated.
613                         maybeResumeDeviceWideLoggingLocked();
614                     }
615                 }
616             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
617                 synchronized (DevicePolicyManagerService.this) {
618                     // Reset the policy data
619                     mUserData.remove(userHandle);
620                     sendAdminEnabledBroadcastLocked(userHandle);
621                 }
622                 handlePackagesChanged(null /* check all admins */, userHandle);
623             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
624                 handlePackagesChanged(null /* check all admins */, userHandle);
625             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
626                     || (Intent.ACTION_PACKAGE_ADDED.equals(action)
627                             && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
628                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
629             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
630                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
631                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
632             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
633                 clearWipeProfileNotification();
634             }
635         }
636
637         private void sendUserAddedOrRemovedCommand(String action, int userHandle) {
638             synchronized (DevicePolicyManagerService.this) {
639                 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
640                 if (deviceOwner != null) {
641                     Bundle extras = new Bundle();
642                     extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
643                     sendAdminCommandLocked(deviceOwner, action, extras, null);
644                 }
645             }
646         }
647     };
648
649     static class ActiveAdmin {
650         private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
651         private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
652         private static final String TAG_DISABLE_CAMERA = "disable-camera";
653         private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
654         private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
655         private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
656                 = "disable-bt-contacts-sharing";
657         private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
658         private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
659         private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
660         private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
661         private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
662         private static final String TAG_ACCOUNT_TYPE = "account-type";
663         private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
664                 = "permitted-accessiblity-services";
665         private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
666         private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
667         private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
668         private static final String TAG_TRUST_AGENT_COMPONENT = "component";
669         private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
670         private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
671         private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
672         private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
673         private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
674         private static final String TAG_PERMITTED_IMES = "permitted-imes";
675         private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS =
676                 "permitted-notification-listeners";
677         private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
678         private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
679         private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
680         private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
681         private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
682         private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
683         private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
684         private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
685         private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
686         private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
687         private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
688         private static final String ATTR_VALUE = "value";
689         private static final String TAG_PASSWORD_QUALITY = "password-quality";
690         private static final String TAG_POLICIES = "policies";
691         private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
692                 "cross-profile-widget-providers";
693         private static final String TAG_PROVIDER = "provider";
694         private static final String TAG_PACKAGE_LIST_ITEM  = "item";
695         private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
696         private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
697         private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS =
698                 "default-enabled-user-restrictions";
699         private static final String TAG_RESTRICTION = "restriction";
700         private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
701         private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
702         private static final String TAG_PARENT_ADMIN = "parent-admin";
703         private static final String TAG_ORGANIZATION_COLOR = "organization-color";
704         private static final String TAG_ORGANIZATION_NAME = "organization-name";
705         private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
706         private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
707
708         final DeviceAdminInfo info;
709
710
711         static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
712         int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
713
714         static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
715         static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
716         static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
717         static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
718         static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
719         static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
720         static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
721         @NonNull
722         PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
723                 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
724                 DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
725                 DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
726                 DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
727
728         static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
729         long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
730
731         long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
732
733         static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
734         int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
735
736         static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
737         long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
738
739         static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
740         long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
741
742         static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
743
744         int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
745
746         boolean encryptionRequested = false;
747         boolean testOnlyAdmin = false;
748         boolean disableCamera = false;
749         boolean disableCallerId = false;
750         boolean disableContactsSearch = false;
751         boolean disableBluetoothContactSharing = true;
752         boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
753         boolean requireAutoTime = false; // Can only be set by a device owner.
754         boolean forceEphemeralUsers = false; // Can only be set by a device owner.
755         boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
756
757         // one notification after enabling + one more after reboots
758         static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2;
759         int numNetworkLoggingNotifications = 0;
760         long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
761
762         ActiveAdmin parentAdmin;
763         final boolean isParent;
764
765         static class TrustAgentInfo {
766             public PersistableBundle options;
767             TrustAgentInfo(PersistableBundle bundle) {
768                 options = bundle;
769             }
770         }
771
772         final Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
773
774         // The list of permitted accessibility services package namesas set by a profile
775         // or device owner. Null means all accessibility services are allowed, empty means
776         // none except system services are allowed.
777         List<String> permittedAccessiblityServices;
778
779         // The list of permitted input methods package names as set by a profile or device owner.
780         // Null means all input methods are allowed, empty means none except system imes are
781         // allowed.
782         List<String> permittedInputMethods;
783
784         // The list of packages allowed to use a NotificationListenerService to receive events for
785         // notifications from this user. Null means that all packages are allowed. Empty list means
786         // that only packages from the system are allowed.
787         List<String> permittedNotificationListeners;
788
789         // List of package names to keep cached.
790         List<String> keepUninstalledPackages;
791
792         // TODO: review implementation decisions with frameworks team
793         boolean specifiesGlobalProxy = false;
794         String globalProxySpec = null;
795         String globalProxyExclusionList = null;
796
797         ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
798
799         List<String> crossProfileWidgetProviders;
800
801         Bundle userRestrictions;
802
803         // User restrictions that have already been enabled by default for this admin (either when
804         // setting the device or profile owner, or during a system update if one of those "enabled
805         // by default" restrictions is newly added).
806         final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>();
807
808         // Support text provided by the admin to display to the user.
809         CharSequence shortSupportMessage = null;
810         CharSequence longSupportMessage = null;
811
812         // Background color of confirm credentials screen. Default: teal.
813         static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
814         int organizationColor = DEF_ORGANIZATION_COLOR;
815
816         // Default title of confirm credentials screen
817         String organizationName = null;
818
819         ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
820             info = _info;
821             isParent = parent;
822         }
823
824         ActiveAdmin getParentActiveAdmin() {
825             Preconditions.checkState(!isParent);
826
827             if (parentAdmin == null) {
828                 parentAdmin = new ActiveAdmin(info, /* parent */ true);
829             }
830             return parentAdmin;
831         }
832
833         boolean hasParentActiveAdmin() {
834             return parentAdmin != null;
835         }
836
837         int getUid() { return info.getActivityInfo().applicationInfo.uid; }
838
839         public UserHandle getUserHandle() {
840             return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
841         }
842
843         void writeToXml(XmlSerializer out)
844                 throws IllegalArgumentException, IllegalStateException, IOException {
845             out.startTag(null, TAG_POLICIES);
846             info.writePoliciesToXml(out);
847             out.endTag(null, TAG_POLICIES);
848             if (minimumPasswordMetrics.quality
849                     != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
850                 out.startTag(null, TAG_PASSWORD_QUALITY);
851                 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
852                 out.endTag(null, TAG_PASSWORD_QUALITY);
853                 if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
854                     out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
855                     out.attribute(
856                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
857                     out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
858                 }
859                 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
860                     out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
861                     out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
862                     out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
863                 }
864                 if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
865                     out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
866                     out.attribute(
867                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
868                     out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
869                 }
870                 if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
871                     out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
872                     out.attribute(
873                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
874                     out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
875                 }
876                 if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
877                     out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
878                     out.attribute(
879                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
880                     out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
881                 }
882                 if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
883                     out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
884                     out.attribute(
885                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
886                     out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
887                 }
888                 if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
889                     out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
890                     out.attribute(
891                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
892                     out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
893                 }
894                 if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
895                     out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
896                     out.attribute(
897                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
898                     out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
899                 }
900             }
901             if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
902                 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
903                 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
904                 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
905             }
906             if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
907                 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
908                 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
909                 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
910             }
911             if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
912                 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
913                 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
914                 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
915             }
916             if (specifiesGlobalProxy) {
917                 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
918                 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
919                 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
920                 if (globalProxySpec != null) {
921                     out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
922                     out.attribute(null, ATTR_VALUE, globalProxySpec);
923                     out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
924                 }
925                 if (globalProxyExclusionList != null) {
926                     out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
927                     out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
928                     out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
929                 }
930             }
931             if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
932                 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
933                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
934                 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
935             }
936             if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
937                 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
938                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
939                 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
940             }
941             if (encryptionRequested) {
942                 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
943                 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
944                 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
945             }
946             if (testOnlyAdmin) {
947                 out.startTag(null, TAG_TEST_ONLY_ADMIN);
948                 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
949                 out.endTag(null, TAG_TEST_ONLY_ADMIN);
950             }
951             if (disableCamera) {
952                 out.startTag(null, TAG_DISABLE_CAMERA);
953                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
954                 out.endTag(null, TAG_DISABLE_CAMERA);
955             }
956             if (disableCallerId) {
957                 out.startTag(null, TAG_DISABLE_CALLER_ID);
958                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
959                 out.endTag(null, TAG_DISABLE_CALLER_ID);
960             }
961             if (disableContactsSearch) {
962                 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
963                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
964                 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
965             }
966             if (!disableBluetoothContactSharing) {
967                 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
968                 out.attribute(null, ATTR_VALUE,
969                         Boolean.toString(disableBluetoothContactSharing));
970                 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
971             }
972             if (disableScreenCapture) {
973                 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
974                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
975                 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
976             }
977             if (requireAutoTime) {
978                 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
979                 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
980                 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
981             }
982             if (forceEphemeralUsers) {
983                 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
984                 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
985                 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
986             }
987             if (isNetworkLoggingEnabled) {
988                 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
989                 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
990                 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
991                         Integer.toString(numNetworkLoggingNotifications));
992                 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
993                         Long.toString(lastNetworkLoggingNotificationTimeMs));
994                 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
995             }
996             if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
997                 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
998                 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
999                 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1000             }
1001             if (!accountTypesWithManagementDisabled.isEmpty()) {
1002                 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
1003                 writeAttributeValuesToXml(
1004                         out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1005                 out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
1006             }
1007             if (!trustAgentInfos.isEmpty()) {
1008                 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
1009                 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1010                 for (Entry<String, TrustAgentInfo> entry : set) {
1011                     TrustAgentInfo trustAgentInfo = entry.getValue();
1012                     out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
1013                     out.attribute(null, ATTR_VALUE, entry.getKey());
1014                     if (trustAgentInfo.options != null) {
1015                         out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1016                         try {
1017                             trustAgentInfo.options.saveToXml(out);
1018                         } catch (XmlPullParserException e) {
1019                             Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
1020                         }
1021                         out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1022                     }
1023                     out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
1024                 }
1025                 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1026             }
1027             if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
1028                 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1029                 writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders);
1030                 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1031             }
1032             writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
1033                     permittedAccessiblityServices);
1034             writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
1035             writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS,
1036                     permittedNotificationListeners);
1037             writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
1038             if (hasUserRestrictions()) {
1039                 UserRestrictionsUtils.writeRestrictions(
1040                         out, userRestrictions, TAG_USER_RESTRICTIONS);
1041             }
1042             if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) {
1043                 out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1044                 writeAttributeValuesToXml(
1045                         out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1046                 out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1047             }
1048             if (!TextUtils.isEmpty(shortSupportMessage)) {
1049                 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1050                 out.text(shortSupportMessage.toString());
1051                 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1052             }
1053             if (!TextUtils.isEmpty(longSupportMessage)) {
1054                 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
1055                 out.text(longSupportMessage.toString());
1056                 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
1057             }
1058             if (parentAdmin != null) {
1059                 out.startTag(null, TAG_PARENT_ADMIN);
1060                 parentAdmin.writeToXml(out);
1061                 out.endTag(null, TAG_PARENT_ADMIN);
1062             }
1063             if (organizationColor != DEF_ORGANIZATION_COLOR) {
1064                 out.startTag(null, TAG_ORGANIZATION_COLOR);
1065                 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
1066                 out.endTag(null, TAG_ORGANIZATION_COLOR);
1067             }
1068             if (organizationName != null) {
1069                 out.startTag(null, TAG_ORGANIZATION_NAME);
1070                 out.text(organizationName);
1071                 out.endTag(null, TAG_ORGANIZATION_NAME);
1072             }
1073         }
1074
1075         void writePackageListToXml(XmlSerializer out, String outerTag,
1076                 List<String> packageList)
1077                 throws IllegalArgumentException, IllegalStateException, IOException {
1078             if (packageList == null) {
1079                 return;
1080             }
1081
1082             out.startTag(null, outerTag);
1083             writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList);
1084             out.endTag(null, outerTag);
1085         }
1086
1087         void writeAttributeValuesToXml(XmlSerializer out, String tag,
1088                 @NonNull Collection<String> values) throws IOException {
1089             for (String value : values) {
1090                 out.startTag(null, tag);
1091                 out.attribute(null, ATTR_VALUE, value);
1092                 out.endTag(null, tag);
1093             }
1094         }
1095
1096         void readFromXml(XmlPullParser parser)
1097                 throws XmlPullParserException, IOException {
1098             int outerDepth = parser.getDepth();
1099             int type;
1100             while ((type=parser.next()) != END_DOCUMENT
1101                    && (type != END_TAG || parser.getDepth() > outerDepth)) {
1102                 if (type == END_TAG || type == TEXT) {
1103                     continue;
1104                 }
1105                 String tag = parser.getName();
1106                 if (TAG_POLICIES.equals(tag)) {
1107                     info.readPoliciesFromXml(parser);
1108                 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1109                     minimumPasswordMetrics.quality = Integer.parseInt(
1110                             parser.getAttributeValue(null, ATTR_VALUE));
1111                 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1112                     minimumPasswordMetrics.length = Integer.parseInt(
1113                             parser.getAttributeValue(null, ATTR_VALUE));
1114                 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1115                     passwordHistoryLength = Integer.parseInt(
1116                             parser.getAttributeValue(null, ATTR_VALUE));
1117                 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1118                     minimumPasswordMetrics.upperCase = Integer.parseInt(
1119                             parser.getAttributeValue(null, ATTR_VALUE));
1120                 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1121                     minimumPasswordMetrics.lowerCase = Integer.parseInt(
1122                             parser.getAttributeValue(null, ATTR_VALUE));
1123                 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1124                     minimumPasswordMetrics.letters = Integer.parseInt(
1125                             parser.getAttributeValue(null, ATTR_VALUE));
1126                 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1127                     minimumPasswordMetrics.numeric = Integer.parseInt(
1128                             parser.getAttributeValue(null, ATTR_VALUE));
1129                 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1130                     minimumPasswordMetrics.symbols = Integer.parseInt(
1131                             parser.getAttributeValue(null, ATTR_VALUE));
1132                 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1133                     minimumPasswordMetrics.nonLetter = Integer.parseInt(
1134                             parser.getAttributeValue(null, ATTR_VALUE));
1135                 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1136                     maximumTimeToUnlock = Long.parseLong(
1137                             parser.getAttributeValue(null, ATTR_VALUE));
1138                 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1139                     strongAuthUnlockTimeout = Long.parseLong(
1140                             parser.getAttributeValue(null, ATTR_VALUE));
1141                 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1142                     maximumFailedPasswordsForWipe = Integer.parseInt(
1143                             parser.getAttributeValue(null, ATTR_VALUE));
1144                 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1145                     specifiesGlobalProxy = Boolean.parseBoolean(
1146                             parser.getAttributeValue(null, ATTR_VALUE));
1147                 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1148                     globalProxySpec =
1149                         parser.getAttributeValue(null, ATTR_VALUE);
1150                 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1151                     globalProxyExclusionList =
1152                         parser.getAttributeValue(null, ATTR_VALUE);
1153                 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1154                     passwordExpirationTimeout = Long.parseLong(
1155                             parser.getAttributeValue(null, ATTR_VALUE));
1156                 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1157                     passwordExpirationDate = Long.parseLong(
1158                             parser.getAttributeValue(null, ATTR_VALUE));
1159                 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1160                     encryptionRequested = Boolean.parseBoolean(
1161                             parser.getAttributeValue(null, ATTR_VALUE));
1162                 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1163                     testOnlyAdmin = Boolean.parseBoolean(
1164                             parser.getAttributeValue(null, ATTR_VALUE));
1165                 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1166                     disableCamera = Boolean.parseBoolean(
1167                             parser.getAttributeValue(null, ATTR_VALUE));
1168                 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1169                     disableCallerId = Boolean.parseBoolean(
1170                             parser.getAttributeValue(null, ATTR_VALUE));
1171                 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1172                     disableContactsSearch = Boolean.parseBoolean(
1173                             parser.getAttributeValue(null, ATTR_VALUE));
1174                 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1175                     disableBluetoothContactSharing = Boolean.parseBoolean(parser
1176                             .getAttributeValue(null, ATTR_VALUE));
1177                 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1178                     disableScreenCapture = Boolean.parseBoolean(
1179                             parser.getAttributeValue(null, ATTR_VALUE));
1180                 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1181                     requireAutoTime = Boolean.parseBoolean(
1182                             parser.getAttributeValue(null, ATTR_VALUE));
1183                 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1184                     forceEphemeralUsers = Boolean.parseBoolean(
1185                             parser.getAttributeValue(null, ATTR_VALUE));
1186                 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1187                     isNetworkLoggingEnabled = Boolean.parseBoolean(
1188                             parser.getAttributeValue(null, ATTR_VALUE));
1189                     lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1190                             parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1191                     numNetworkLoggingNotifications = Integer.parseInt(
1192                             parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1193                 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1194                     disabledKeyguardFeatures = Integer.parseInt(
1195                             parser.getAttributeValue(null, ATTR_VALUE));
1196                 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1197                     readAttributeValues(
1198                             parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1199                 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1200                     trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1201                 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1202                     crossProfileWidgetProviders = new ArrayList<>();
1203                     readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders);
1204                 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1205                     permittedAccessiblityServices = readPackageList(parser, tag);
1206                 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1207                     permittedInputMethods = readPackageList(parser, tag);
1208                 } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) {
1209                     permittedNotificationListeners = readPackageList(parser, tag);
1210                 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1211                     keepUninstalledPackages = readPackageList(parser, tag);
1212                 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1213                     userRestrictions = UserRestrictionsUtils.readRestrictions(parser);
1214                 } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) {
1215                     readAttributeValues(
1216                             parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1217                 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1218                     type = parser.next();
1219                     if (type == XmlPullParser.TEXT) {
1220                         shortSupportMessage = parser.getText();
1221                     } else {
1222                         Log.w(LOG_TAG, "Missing text when loading short support message");
1223                     }
1224                 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1225                     type = parser.next();
1226                     if (type == XmlPullParser.TEXT) {
1227                         longSupportMessage = parser.getText();
1228                     } else {
1229                         Log.w(LOG_TAG, "Missing text when loading long support message");
1230                     }
1231                 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1232                     Preconditions.checkState(!isParent);
1233
1234                     parentAdmin = new ActiveAdmin(info, /* parent */ true);
1235                     parentAdmin.readFromXml(parser);
1236                 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1237                     organizationColor = Integer.parseInt(
1238                             parser.getAttributeValue(null, ATTR_VALUE));
1239                 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1240                     type = parser.next();
1241                     if (type == XmlPullParser.TEXT) {
1242                         organizationName = parser.getText();
1243                     } else {
1244                         Log.w(LOG_TAG, "Missing text when loading organization name");
1245                     }
1246                 } else {
1247                     Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1248                     XmlUtils.skipCurrentTag(parser);
1249                 }
1250             }
1251         }
1252
1253         private List<String> readPackageList(XmlPullParser parser,
1254                 String tag) throws XmlPullParserException, IOException {
1255             List<String> result = new ArrayList<String>();
1256             int outerDepth = parser.getDepth();
1257             int outerType;
1258             while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1259                     && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1260                 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1261                     continue;
1262                 }
1263                 String outerTag = parser.getName();
1264                 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1265                     String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1266                     if (packageName != null) {
1267                         result.add(packageName);
1268                     } else {
1269                         Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1270                     }
1271                 } else {
1272                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
1273                 }
1274             }
1275             return result;
1276         }
1277
1278         private void readAttributeValues(
1279                 XmlPullParser parser, String tag, Collection<String> result)
1280                 throws XmlPullParserException, IOException {
1281             result.clear();
1282             int outerDepthDAM = parser.getDepth();
1283             int typeDAM;
1284             while ((typeDAM=parser.next()) != END_DOCUMENT
1285                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1286                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1287                     continue;
1288                 }
1289                 String tagDAM = parser.getName();
1290                 if (tag.equals(tagDAM)) {
1291                     result.add(parser.getAttributeValue(null, ATTR_VALUE));
1292                 } else {
1293                     Slog.e(LOG_TAG, "Expected tag " + tag +  " but found " + tagDAM);
1294                 }
1295             }
1296         }
1297
1298         private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1299                 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1300             int outerDepthDAM = parser.getDepth();
1301             int typeDAM;
1302             final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1303             while ((typeDAM=parser.next()) != END_DOCUMENT
1304                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1305                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1306                     continue;
1307                 }
1308                 String tagDAM = parser.getName();
1309                 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1310                     final String component = parser.getAttributeValue(null, ATTR_VALUE);
1311                     final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1312                     result.put(component, trustAgentInfo);
1313                 } else {
1314                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1315                 }
1316             }
1317             return result;
1318         }
1319
1320         private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1321                 throws XmlPullParserException, IOException  {
1322             int outerDepthDAM = parser.getDepth();
1323             int typeDAM;
1324             TrustAgentInfo result = new TrustAgentInfo(null);
1325             while ((typeDAM=parser.next()) != END_DOCUMENT
1326                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1327                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1328                     continue;
1329                 }
1330                 String tagDAM = parser.getName();
1331                 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1332                     result.options = PersistableBundle.restoreFromXml(parser);
1333                 } else {
1334                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1335                 }
1336             }
1337             return result;
1338         }
1339
1340         boolean hasUserRestrictions() {
1341             return userRestrictions != null && userRestrictions.size() > 0;
1342         }
1343
1344         Bundle ensureUserRestrictions() {
1345             if (userRestrictions == null) {
1346                 userRestrictions = new Bundle();
1347             }
1348             return userRestrictions;
1349         }
1350
1351         void dump(String prefix, PrintWriter pw) {
1352             pw.print(prefix); pw.print("uid="); pw.println(getUid());
1353             pw.print(prefix); pw.print("testOnlyAdmin=");
1354             pw.println(testOnlyAdmin);
1355             pw.print(prefix); pw.println("policies:");
1356             ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1357             if (pols != null) {
1358                 for (int i=0; i<pols.size(); i++) {
1359                     pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
1360                 }
1361             }
1362             pw.print(prefix); pw.print("passwordQuality=0x");
1363                     pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
1364             pw.print(prefix); pw.print("minimumPasswordLength=");
1365                     pw.println(minimumPasswordMetrics.length);
1366             pw.print(prefix); pw.print("passwordHistoryLength=");
1367                     pw.println(passwordHistoryLength);
1368             pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1369                     pw.println(minimumPasswordMetrics.upperCase);
1370             pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1371                     pw.println(minimumPasswordMetrics.lowerCase);
1372             pw.print(prefix); pw.print("minimumPasswordLetters=");
1373                     pw.println(minimumPasswordMetrics.letters);
1374             pw.print(prefix); pw.print("minimumPasswordNumeric=");
1375                     pw.println(minimumPasswordMetrics.numeric);
1376             pw.print(prefix); pw.print("minimumPasswordSymbols=");
1377                     pw.println(minimumPasswordMetrics.symbols);
1378             pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1379                     pw.println(minimumPasswordMetrics.nonLetter);
1380             pw.print(prefix); pw.print("maximumTimeToUnlock=");
1381                     pw.println(maximumTimeToUnlock);
1382             pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1383                     pw.println(strongAuthUnlockTimeout);
1384             pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1385                     pw.println(maximumFailedPasswordsForWipe);
1386             pw.print(prefix); pw.print("specifiesGlobalProxy=");
1387                     pw.println(specifiesGlobalProxy);
1388             pw.print(prefix); pw.print("passwordExpirationTimeout=");
1389                     pw.println(passwordExpirationTimeout);
1390             pw.print(prefix); pw.print("passwordExpirationDate=");
1391                     pw.println(passwordExpirationDate);
1392             if (globalProxySpec != null) {
1393                 pw.print(prefix); pw.print("globalProxySpec=");
1394                         pw.println(globalProxySpec);
1395             }
1396             if (globalProxyExclusionList != null) {
1397                 pw.print(prefix); pw.print("globalProxyEclusionList=");
1398                         pw.println(globalProxyExclusionList);
1399             }
1400             pw.print(prefix); pw.print("encryptionRequested=");
1401                     pw.println(encryptionRequested);
1402             pw.print(prefix); pw.print("disableCamera=");
1403                     pw.println(disableCamera);
1404             pw.print(prefix); pw.print("disableCallerId=");
1405                     pw.println(disableCallerId);
1406             pw.print(prefix); pw.print("disableContactsSearch=");
1407                     pw.println(disableContactsSearch);
1408             pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1409                     pw.println(disableBluetoothContactSharing);
1410             pw.print(prefix); pw.print("disableScreenCapture=");
1411                     pw.println(disableScreenCapture);
1412             pw.print(prefix); pw.print("requireAutoTime=");
1413                     pw.println(requireAutoTime);
1414             pw.print(prefix); pw.print("forceEphemeralUsers=");
1415                     pw.println(forceEphemeralUsers);
1416             pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1417                     pw.println(isNetworkLoggingEnabled);
1418             pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1419                     pw.println(disabledKeyguardFeatures);
1420             pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1421                     pw.println(crossProfileWidgetProviders);
1422             if (permittedAccessiblityServices != null) {
1423                 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1424                     pw.println(permittedAccessiblityServices);
1425             }
1426             if (permittedInputMethods != null) {
1427                 pw.print(prefix); pw.print("permittedInputMethods=");
1428                     pw.println(permittedInputMethods);
1429             }
1430             if (permittedNotificationListeners != null) {
1431                 pw.print(prefix); pw.print("permittedNotificationListeners=");
1432                 pw.println(permittedNotificationListeners);
1433             }
1434             if (keepUninstalledPackages != null) {
1435                 pw.print(prefix); pw.print("keepUninstalledPackages=");
1436                     pw.println(keepUninstalledPackages);
1437             }
1438             pw.print(prefix); pw.print("organizationColor=");
1439                     pw.println(organizationColor);
1440             if (organizationName != null) {
1441                 pw.print(prefix); pw.print("organizationName=");
1442                     pw.println(organizationName);
1443             }
1444             pw.print(prefix); pw.println("userRestrictions:");
1445             UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
1446             pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet=");
1447                     pw.println(defaultEnabledRestrictionsAlreadySet);
1448             pw.print(prefix); pw.print("isParent=");
1449                     pw.println(isParent);
1450             if (parentAdmin != null) {
1451                 pw.print(prefix);  pw.println("parentAdmin:");
1452                 parentAdmin.dump(prefix + "  ", pw);
1453             }
1454         }
1455     }
1456
1457     private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1458         boolean removedAdmin = false;
1459         if (VERBOSE_LOG) {
1460             Slog.d(LOG_TAG, "Handling package changes package " + packageName
1461                     + " for user " + userHandle);
1462         }
1463         DevicePolicyData policy = getUserData(userHandle);
1464         synchronized (this) {
1465             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1466                 ActiveAdmin aa = policy.mAdminList.get(i);
1467                 try {
1468                     // If we're checking all packages or if the specific one we're checking matches,
1469                     // then check if the package and receiver still exist.
1470                     final String adminPackage = aa.info.getPackageName();
1471                     if (packageName == null || packageName.equals(adminPackage)) {
1472                         if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1473                                 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1474                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
1475                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1476                                 userHandle) == null) {
1477                             removedAdmin = true;
1478                             policy.mAdminList.remove(i);
1479                             policy.mAdminMap.remove(aa.info.getComponent());
1480                         }
1481                     }
1482                 } catch (RemoteException re) {
1483                     // Shouldn't happen.
1484                 }
1485             }
1486             if (removedAdmin) {
1487                 validatePasswordOwnerLocked(policy);
1488             }
1489
1490             boolean removedDelegate = false;
1491
1492             // Check if a delegate was removed.
1493             for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1494                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
1495                 if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1496                     policy.mDelegationMap.removeAt(i);
1497                     removedDelegate = true;
1498                 }
1499             }
1500
1501             // If it's an owner package, we may need to refresh the bound connection.
1502             final ComponentName owner = getOwnerComponent(userHandle);
1503             if ((packageName != null) && (owner != null)
1504                     && (owner.getPackageName().equals(packageName))) {
1505                 startOwnerService(userHandle, "package-broadcast");
1506             }
1507
1508             // Persist updates if the removed package was an admin or delegate.
1509             if (removedAdmin || removedDelegate) {
1510                 saveSettingsLocked(policy.mUserHandle);
1511             }
1512         }
1513         if (removedAdmin) {
1514             // The removed admin might have disabled camera, so update user restrictions.
1515             pushUserRestrictions(userHandle);
1516         }
1517     }
1518
1519     private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1520         try {
1521             return targetPackage != null
1522                     && (changedPackage == null || changedPackage.equals(targetPackage))
1523                     && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1524         } catch (RemoteException e) {
1525             // Shouldn't happen
1526         }
1527
1528         return false;
1529     }
1530
1531     /**
1532      * Unit test will subclass it to inject mocks.
1533      */
1534     @VisibleForTesting
1535     static class Injector {
1536
1537         public final Context mContext;
1538
1539         Injector(Context context) {
1540             mContext = context;
1541         }
1542
1543         Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1544             final String packageName = mContext.getPackageName();
1545             return mContext.createPackageContextAsUser(packageName, 0, user);
1546         }
1547
1548         Resources getResources() {
1549             return mContext.getResources();
1550         }
1551
1552         Owners newOwners() {
1553             return new Owners(getUserManager(), getUserManagerInternal(),
1554                     getPackageManagerInternal());
1555         }
1556
1557         UserManager getUserManager() {
1558             return UserManager.get(mContext);
1559         }
1560
1561         UserManagerInternal getUserManagerInternal() {
1562             return LocalServices.getService(UserManagerInternal.class);
1563         }
1564
1565         PackageManagerInternal getPackageManagerInternal() {
1566             return LocalServices.getService(PackageManagerInternal.class);
1567         }
1568
1569         NotificationManager getNotificationManager() {
1570             return mContext.getSystemService(NotificationManager.class);
1571         }
1572
1573         IIpConnectivityMetrics getIIpConnectivityMetrics() {
1574             return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1575                 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1576         }
1577
1578         PackageManager getPackageManager() {
1579             return mContext.getPackageManager();
1580         }
1581
1582         PowerManagerInternal getPowerManagerInternal() {
1583             return LocalServices.getService(PowerManagerInternal.class);
1584         }
1585
1586         TelephonyManager getTelephonyManager() {
1587             return TelephonyManager.from(mContext);
1588         }
1589
1590         TrustManager getTrustManager() {
1591             return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1592         }
1593
1594         AlarmManager getAlarmManager() {
1595             return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1596         }
1597
1598         IWindowManager getIWindowManager() {
1599             return IWindowManager.Stub
1600                     .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1601         }
1602
1603         IActivityManager getIActivityManager() {
1604             return ActivityManager.getService();
1605         }
1606
1607         IPackageManager getIPackageManager() {
1608             return AppGlobals.getPackageManager();
1609         }
1610
1611         IBackupManager getIBackupManager() {
1612             return IBackupManager.Stub.asInterface(
1613                     ServiceManager.getService(Context.BACKUP_SERVICE));
1614         }
1615
1616         IAudioService getIAudioService() {
1617             return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1618         }
1619
1620         boolean isBuildDebuggable() {
1621             return Build.IS_DEBUGGABLE;
1622         }
1623
1624         LockPatternUtils newLockPatternUtils() {
1625             return new LockPatternUtils(mContext);
1626         }
1627
1628         boolean storageManagerIsFileBasedEncryptionEnabled() {
1629             return StorageManager.isFileEncryptedNativeOnly();
1630         }
1631
1632         boolean storageManagerIsNonDefaultBlockEncrypted() {
1633             long identity = Binder.clearCallingIdentity();
1634             try {
1635                 return StorageManager.isNonDefaultBlockEncrypted();
1636             } finally {
1637                 Binder.restoreCallingIdentity(identity);
1638             }
1639         }
1640
1641         boolean storageManagerIsEncrypted() {
1642             return StorageManager.isEncrypted();
1643         }
1644
1645         boolean storageManagerIsEncryptable() {
1646             return StorageManager.isEncryptable();
1647         }
1648
1649         Looper getMyLooper() {
1650             return Looper.myLooper();
1651         }
1652
1653         WifiManager getWifiManager() {
1654             return mContext.getSystemService(WifiManager.class);
1655         }
1656
1657         long binderClearCallingIdentity() {
1658             return Binder.clearCallingIdentity();
1659         }
1660
1661         void binderRestoreCallingIdentity(long token) {
1662             Binder.restoreCallingIdentity(token);
1663         }
1664
1665         int binderGetCallingUid() {
1666             return Binder.getCallingUid();
1667         }
1668
1669         int binderGetCallingPid() {
1670             return Binder.getCallingPid();
1671         }
1672
1673         UserHandle binderGetCallingUserHandle() {
1674             return Binder.getCallingUserHandle();
1675         }
1676
1677         boolean binderIsCallingUidMyUid() {
1678             return getCallingUid() == Process.myUid();
1679         }
1680
1681         final int userHandleGetCallingUserId() {
1682             return UserHandle.getUserId(binderGetCallingUid());
1683         }
1684
1685         File environmentGetUserSystemDirectory(int userId) {
1686             return Environment.getUserSystemDirectory(userId);
1687         }
1688
1689         void powerManagerGoToSleep(long time, int reason, int flags) {
1690             mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1691         }
1692
1693         void powerManagerReboot(String reason) {
1694             mContext.getSystemService(PowerManager.class).reboot(reason);
1695         }
1696
1697         void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1698                 boolean wipeEuicc) throws IOException {
1699             RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc);
1700         }
1701
1702         boolean systemPropertiesGetBoolean(String key, boolean def) {
1703             return SystemProperties.getBoolean(key, def);
1704         }
1705
1706         long systemPropertiesGetLong(String key, long def) {
1707             return SystemProperties.getLong(key, def);
1708         }
1709
1710         String systemPropertiesGet(String key, String def) {
1711             return SystemProperties.get(key, def);
1712         }
1713
1714         String systemPropertiesGet(String key) {
1715             return SystemProperties.get(key);
1716         }
1717
1718         void systemPropertiesSet(String key, String value) {
1719             SystemProperties.set(key, value);
1720         }
1721
1722         boolean userManagerIsSplitSystemUser() {
1723             return UserManager.isSplitSystemUser();
1724         }
1725
1726         String getDevicePolicyFilePathForSystemUser() {
1727             return "/data/system/";
1728         }
1729
1730         PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1731                 @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
1732             return PendingIntent.getActivityAsUser(
1733                     context, requestCode, intent, flags, options, user);
1734         }
1735
1736         void registerContentObserver(Uri uri, boolean notifyForDescendents,
1737                 ContentObserver observer, int userHandle) {
1738             mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1739                     observer, userHandle);
1740         }
1741
1742         int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1743             return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1744                     name, def, userHandle);
1745         }
1746
1747         String settingsSecureGetStringForUser(String name, int userHandle) {
1748             return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
1749                     userHandle);
1750         }
1751
1752         void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1753             Settings.Secure.putIntForUser(mContext.getContentResolver(),
1754                     name, value, userHandle);
1755         }
1756
1757         void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1758             Settings.Secure.putStringForUser(mContext.getContentResolver(),
1759                     name, value, userHandle);
1760         }
1761
1762         void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1763             Settings.Global.putStringForUser(mContext.getContentResolver(),
1764                     name, value, userHandle);
1765         }
1766
1767         void settingsSecurePutInt(String name, int value) {
1768             Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1769         }
1770
1771         int settingsGlobalGetInt(String name, int def) {
1772             return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1773         }
1774
1775         String settingsGlobalGetString(String name) {
1776             return Settings.Global.getString(mContext.getContentResolver(), name);
1777         }
1778
1779         void settingsGlobalPutInt(String name, int value) {
1780             Settings.Global.putInt(mContext.getContentResolver(), name, value);
1781         }
1782
1783         void settingsSecurePutString(String name, String value) {
1784             Settings.Secure.putString(mContext.getContentResolver(), name, value);
1785         }
1786
1787         void settingsGlobalPutString(String name, String value) {
1788             Settings.Global.putString(mContext.getContentResolver(), name, value);
1789         }
1790
1791         void securityLogSetLoggingEnabledProperty(boolean enabled) {
1792             SecurityLog.setLoggingEnabledProperty(enabled);
1793         }
1794
1795         boolean securityLogGetLoggingEnabledProperty() {
1796             return SecurityLog.getLoggingEnabledProperty();
1797         }
1798
1799         boolean securityLogIsLoggingEnabled() {
1800             return SecurityLog.isLoggingEnabled();
1801         }
1802
1803         KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
1804             return KeyChain.bindAsUser(mContext, user);
1805         }
1806     }
1807
1808     /**
1809      * Instantiates the service.
1810      */
1811     public DevicePolicyManagerService(Context context) {
1812         this(new Injector(context));
1813     }
1814
1815     @VisibleForTesting
1816     DevicePolicyManagerService(Injector injector) {
1817         mInjector = injector;
1818         mContext = Preconditions.checkNotNull(injector.mContext);
1819         mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1820         mConstants = DevicePolicyConstants.loadFromString(
1821                 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
1822
1823         mOwners = Preconditions.checkNotNull(injector.newOwners());
1824
1825         mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1826         mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1827         mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1828         mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1829
1830         mLocalService = new LocalService();
1831         mLockPatternUtils = injector.newLockPatternUtils();
1832
1833         // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
1834         mSecurityLogMonitor = new SecurityLogMonitor(this);
1835
1836         mHasFeature = mInjector.getPackageManager()
1837                 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1838         mIsWatch = mInjector.getPackageManager()
1839                 .hasSystemFeature(PackageManager.FEATURE_WATCH);
1840         mBackgroundHandler = BackgroundThread.getHandler();
1841
1842         // Needed when mHasFeature == false, because it controls the certificate warning text.
1843         mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
1844
1845         mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
1846
1847         if (!mHasFeature) {
1848             // Skip the rest of the initialization
1849             return;
1850         }
1851
1852         IntentFilter filter = new IntentFilter();
1853         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1854         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1855         filter.addAction(Intent.ACTION_USER_ADDED);
1856         filter.addAction(Intent.ACTION_USER_REMOVED);
1857         filter.addAction(Intent.ACTION_USER_STARTED);
1858         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1859         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1860         filter = new IntentFilter();
1861         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1862         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1863         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1864         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1865         filter.addDataScheme("package");
1866         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1867         filter = new IntentFilter();
1868         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1869         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1870
1871         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1872
1873         mSetupContentObserver = new SetupContentObserver(mHandler);
1874     }
1875
1876     /**
1877      * Creates and loads the policy data from xml.
1878      * @param userHandle the user for whom to load the policy data
1879      * @return
1880      */
1881     @NonNull
1882     DevicePolicyData getUserData(int userHandle) {
1883         synchronized (this) {
1884             DevicePolicyData policy = mUserData.get(userHandle);
1885             if (policy == null) {
1886                 policy = new DevicePolicyData(userHandle);
1887                 mUserData.append(userHandle, policy);
1888                 loadSettingsLocked(policy, userHandle);
1889             }
1890             return policy;
1891         }
1892     }
1893
1894     /**
1895      * Creates and loads the policy data from xml for data that is shared between
1896      * various profiles of a user. In contrast to {@link #getUserData(int)}
1897      * it allows access to data of users other than the calling user.
1898      *
1899      * This function should only be used for shared data, e.g. everything regarding
1900      * passwords and should be removed once multiple screen locks are present.
1901      * @param userHandle the user for whom to load the policy data
1902      * @return
1903      */
1904     DevicePolicyData getUserDataUnchecked(int userHandle) {
1905         long ident = mInjector.binderClearCallingIdentity();
1906         try {
1907             return getUserData(userHandle);
1908         } finally {
1909             mInjector.binderRestoreCallingIdentity(ident);
1910         }
1911     }
1912
1913     void removeUserData(int userHandle) {
1914         synchronized (this) {
1915             if (userHandle == UserHandle.USER_SYSTEM) {
1916                 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1917                 return;
1918             }
1919             mOwners.removeProfileOwner(userHandle);
1920             mOwners.writeProfileOwner(userHandle);
1921
1922             DevicePolicyData policy = mUserData.get(userHandle);
1923             if (policy != null) {
1924                 mUserData.remove(userHandle);
1925             }
1926             File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1927                     DEVICE_POLICIES_XML);
1928             policyFile.delete();
1929             Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1930         }
1931         updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1932     }
1933
1934     void loadOwners() {
1935         synchronized (this) {
1936             mOwners.load();
1937             setDeviceOwnerSystemPropertyLocked();
1938             findOwnerComponentIfNecessaryLocked();
1939             migrateUserRestrictionsIfNecessaryLocked();
1940             maybeSetDefaultDeviceOwnerUserRestrictionsLocked();
1941
1942             // TODO PO may not have a class name either due to b/17652534.  Address that too.
1943
1944             updateDeviceOwnerLocked();
1945         }
1946     }
1947
1948     /** Apply default restrictions that haven't been applied to device owners yet. */
1949     private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() {
1950         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
1951         if (deviceOwner != null) {
1952             maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(),
1953                     deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner());
1954         }
1955     }
1956
1957     /** Apply default restrictions that haven't been applied to profile owners yet. */
1958     private void maybeSetDefaultProfileOwnerUserRestrictions() {
1959         synchronized (this) {
1960             for (final int userId : mOwners.getProfileOwnerKeys()) {
1961                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
1962                 // The following restrictions used to be applied to managed profiles by different
1963                 // means (via Settings or by disabling components). Now they are proper user
1964                 // restrictions so we apply them to managed profile owners. Non-managed secondary
1965                 // users didn't have those restrictions so we skip them to keep existing behavior.
1966                 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
1967                     continue;
1968                 }
1969                 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner,
1970                         UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
1971                 ensureUnknownSourcesRestrictionForProfileOwnerLocked(
1972                         userId, profileOwner, false /* newOwner */);
1973             }
1974         }
1975     }
1976
1977     /**
1978      * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
1979      * set of restrictions for this profile owner.
1980      */
1981     private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
1982             ActiveAdmin profileOwner, boolean newOwner) {
1983         if (newOwner || mInjector.settingsSecureGetIntForUser(
1984                 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
1985             profileOwner.ensureUserRestrictions().putBoolean(
1986                     UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
1987             saveUserRestrictionsLocked(userId);
1988             mInjector.settingsSecurePutIntForUser(
1989                     Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
1990         }
1991     }
1992
1993     /**
1994      * Apply default restrictions that haven't been applied to a given admin yet.
1995      */
1996     private void maybeSetDefaultRestrictionsForAdminLocked(
1997             int userId, ActiveAdmin admin, Set<String> defaultRestrictions) {
1998         if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
1999             return; // The same set of default restrictions has been already applied.
2000         }
2001         Slog.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
2002
2003         if (VERBOSE_LOG) {
2004             Slog.d(LOG_TAG,"Default enabled restrictions: "
2005                     + defaultRestrictions
2006                     + ". Restrictions already enabled: "
2007                     + admin.defaultEnabledRestrictionsAlreadySet);
2008         }
2009
2010         final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
2011         restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
2012         if (!restrictionsToSet.isEmpty()) {
2013             for (final String restriction : restrictionsToSet) {
2014                 admin.ensureUserRestrictions().putBoolean(restriction, true);
2015             }
2016             admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
2017             Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
2018             saveUserRestrictionsLocked(userId);
2019         }
2020     }
2021
2022     private void setDeviceOwnerSystemPropertyLocked() {
2023         final boolean deviceProvisioned =
2024                 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2025         // If the device is not provisioned and there is currently no device owner, do not set the
2026         // read-only system property yet, since Device owner may still be provisioned. For Wear
2027         // devices, if there is already a device owner then it's OK to set the property to true now,
2028         // regardless the provision state.
2029         final boolean isWatchWithDeviceOwner = mIsWatch && mOwners.hasDeviceOwner();
2030         if (!isWatchWithDeviceOwner && !deviceProvisioned) {
2031             return;
2032         }
2033         // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
2034         // always false at this point.
2035         if (StorageManager.inCryptKeeperBounce()) {
2036             return;
2037         }
2038
2039         if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
2040             Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
2041         } else {
2042             if (mOwners.hasDeviceOwner()) {
2043                 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
2044                 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
2045
2046                 if (mInjector.securityLogGetLoggingEnabledProperty()) {
2047                     mSecurityLogMonitor.start();
2048                     maybePauseDeviceWideLoggingLocked();
2049                 }
2050             } else {
2051                 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
2052                 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
2053             }
2054         }
2055     }
2056
2057     private void findOwnerComponentIfNecessaryLocked() {
2058         if (!mOwners.hasDeviceOwner()) {
2059             return;
2060         }
2061         final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
2062
2063         if (!TextUtils.isEmpty(doComponentName.getClassName())) {
2064             return; // Already a full component name.
2065         }
2066
2067         final ComponentName doComponent = findAdminComponentWithPackageLocked(
2068                 doComponentName.getPackageName(),
2069                 mOwners.getDeviceOwnerUserId());
2070         if (doComponent == null) {
2071             Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
2072         } else {
2073             mOwners.setDeviceOwnerWithRestrictionsMigrated(
2074                     doComponent,
2075                     mOwners.getDeviceOwnerName(),
2076                     mOwners.getDeviceOwnerUserId(),
2077                     !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
2078             mOwners.writeDeviceOwner();
2079             if (VERBOSE_LOG) {
2080                 Log.v(LOG_TAG, "Device owner component filled in");
2081             }
2082         }
2083     }
2084
2085     /**
2086      * We didn't use to persist user restrictions for each owners but only persisted in user
2087      * manager.
2088      */
2089     private void migrateUserRestrictionsIfNecessaryLocked() {
2090         boolean migrated = false;
2091         // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
2092         // except for the "system controlled" ones.
2093         if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
2094             if (VERBOSE_LOG) {
2095                 Log.v(LOG_TAG, "Migrating DO user restrictions");
2096             }
2097             migrated = true;
2098
2099             // Migrate user 0 restrictions to DO.
2100             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
2101
2102             migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
2103                     /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
2104
2105             // Push DO user restrictions to user manager.
2106             pushUserRestrictions(UserHandle.USER_SYSTEM);
2107
2108             mOwners.setDeviceOwnerUserRestrictionsMigrated();
2109         }
2110
2111         // Migrate for POs.
2112
2113         // The following restrictions can be set on secondary users by the device owner, so we
2114         // assume they're not from the PO.
2115         final Set<String> secondaryUserExceptionList = Sets.newArraySet(
2116                 UserManager.DISALLOW_OUTGOING_CALLS,
2117                 UserManager.DISALLOW_SMS);
2118
2119         for (UserInfo ui : mUserManager.getUsers()) {
2120             final int userId = ui.id;
2121             if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
2122                 if (VERBOSE_LOG) {
2123                     Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
2124                 }
2125                 migrated = true;
2126
2127                 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
2128
2129                 final Set<String> exceptionList =
2130                         (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
2131
2132                 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
2133                         exceptionList, /* isDeviceOwner =*/ false);
2134
2135                 // Note if a secondary user has no PO but has a DA that disables camera, we
2136                 // don't get here and won't push the camera user restriction to UserManager
2137                 // here.  That's okay because we'll push user restrictions anyway when a user
2138                 // starts.  But we still do it because we want to let user manager persist
2139                 // upon migration.
2140                 pushUserRestrictions(userId);
2141
2142                 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
2143             }
2144         }
2145         if (VERBOSE_LOG && migrated) {
2146             Log.v(LOG_TAG, "User restrictions migrated.");
2147         }
2148     }
2149
2150     private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
2151             Set<String> exceptionList, boolean isDeviceOwner) {
2152         final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
2153                 user.getIdentifier());
2154
2155         final Bundle newBaseRestrictions = new Bundle();
2156         final Bundle newOwnerRestrictions = new Bundle();
2157
2158         for (String key : origRestrictions.keySet()) {
2159             if (!origRestrictions.getBoolean(key)) {
2160                 continue;
2161             }
2162             final boolean canOwnerChange = isDeviceOwner
2163                     ? UserRestrictionsUtils.canDeviceOwnerChange(key)
2164                     : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
2165
2166             if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
2167                 newBaseRestrictions.putBoolean(key, true);
2168             } else {
2169                 newOwnerRestrictions.putBoolean(key, true);
2170             }
2171         }
2172
2173         if (VERBOSE_LOG) {
2174             Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
2175             Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
2176             Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
2177         }
2178         mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
2179                 newBaseRestrictions);
2180
2181         if (admin != null) {
2182             admin.ensureUserRestrictions().clear();
2183             admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
2184         } else {
2185             Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
2186         }
2187         saveSettingsLocked(user.getIdentifier());
2188     }
2189
2190     private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
2191         final DevicePolicyData policy = getUserData(userId);
2192         final int n = policy.mAdminList.size();
2193         ComponentName found = null;
2194         int nFound = 0;
2195         for (int i = 0; i < n; i++) {
2196             final ActiveAdmin admin = policy.mAdminList.get(i);
2197             if (packageName.equals(admin.info.getPackageName())) {
2198                 // Found!
2199                 if (nFound == 0) {
2200                     found = admin.info.getComponent();
2201                 }
2202                 nFound++;
2203             }
2204         }
2205         if (nFound > 1) {
2206             Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
2207         }
2208         return found;
2209     }
2210
2211     /**
2212      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2213      * reminders.  Clears alarm if no expirations are configured.
2214      */
2215     private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2216         final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2217         final long now = System.currentTimeMillis();
2218         final long timeToExpire = expiration - now;
2219         final long alarmTime;
2220         if (expiration == 0) {
2221             // No expirations are currently configured:  Cancel alarm.
2222             alarmTime = 0;
2223         } else if (timeToExpire <= 0) {
2224             // The password has already expired:  Repeat every 24 hours.
2225             alarmTime = now + MS_PER_DAY;
2226         } else {
2227             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2228             // the expiration time.
2229             long alarmInterval = timeToExpire % MS_PER_DAY;
2230             if (alarmInterval == 0) {
2231                 alarmInterval = MS_PER_DAY;
2232             }
2233             alarmTime = now + alarmInterval;
2234         }
2235
2236         long token = mInjector.binderClearCallingIdentity();
2237         try {
2238             int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2239             AlarmManager am = mInjector.getAlarmManager();
2240             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2241                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2242                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2243                     UserHandle.of(affectedUserHandle));
2244             am.cancel(pi);
2245             if (alarmTime != 0) {
2246                 am.set(AlarmManager.RTC, alarmTime, pi);
2247             }
2248         } finally {
2249             mInjector.binderRestoreCallingIdentity(token);
2250         }
2251     }
2252
2253     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2254         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2255         if (admin != null
2256                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2257                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2258             return admin;
2259         }
2260         return null;
2261     }
2262
2263     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2264         if (parent) {
2265             enforceManagedProfile(userHandle, "call APIs on the parent profile");
2266         }
2267         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2268         if (admin != null && parent) {
2269             admin = admin.getParentActiveAdmin();
2270         }
2271         return admin;
2272     }
2273
2274     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2275             throws SecurityException {
2276         final int callingUid = mInjector.binderGetCallingUid();
2277
2278         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2279         if (result != null) {
2280             return result;
2281         }
2282
2283         if (who != null) {
2284             final int userId = UserHandle.getUserId(callingUid);
2285             final DevicePolicyData policy = getUserData(userId);
2286             ActiveAdmin admin = policy.mAdminMap.get(who);
2287             if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2288                 throw new SecurityException("Admin " + admin.info.getComponent()
2289                          + " does not own the device");
2290             }
2291             if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2292                 throw new SecurityException("Admin " + admin.info.getComponent()
2293                         + " does not own the profile");
2294             }
2295             throw new SecurityException("Admin " + admin.info.getComponent()
2296                     + " did not specify uses-policy for: "
2297                     + admin.info.getTagForPolicy(reqPolicy));
2298         } else {
2299             throw new SecurityException("No active admin owned by uid "
2300                     + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2301         }
2302     }
2303
2304     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2305             throws SecurityException {
2306         if (parent) {
2307             enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2308                     "call APIs on the parent profile");
2309         }
2310         ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2311         return parent ? admin.getParentActiveAdmin() : admin;
2312     }
2313     /**
2314      * Find the admin for the component and userId bit of the uid, then check
2315      * the admin's uid matches the uid.
2316      */
2317     private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2318         final int userId = UserHandle.getUserId(uid);
2319         final DevicePolicyData policy = getUserData(userId);
2320         ActiveAdmin admin = policy.mAdminMap.get(who);
2321         if (admin == null) {
2322             throw new SecurityException("No active admin " + who);
2323         }
2324         if (admin.getUid() != uid) {
2325             throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2326         }
2327         return admin;
2328     }
2329
2330     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2331             int uid) {
2332         // Try to find an admin which can use reqPolicy
2333         final int userId = UserHandle.getUserId(uid);
2334         final DevicePolicyData policy = getUserData(userId);
2335         if (who != null) {
2336             ActiveAdmin admin = policy.mAdminMap.get(who);
2337             if (admin == null) {
2338                 throw new SecurityException("No active admin " + who);
2339             }
2340             if (admin.getUid() != uid) {
2341                 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2342             }
2343             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2344                 return admin;
2345             }
2346         } else {
2347             for (ActiveAdmin admin : policy.mAdminList) {
2348                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2349                         userId)) {
2350                     return admin;
2351                 }
2352             }
2353         }
2354
2355         return null;
2356     }
2357
2358     @VisibleForTesting
2359     boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2360             int userId) {
2361         final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2362         final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2363
2364         if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2365             return ownsDevice;
2366         } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2367             // DO always has the PO power.
2368             return ownsDevice || ownsProfile;
2369         } else {
2370             return admin.info.usesPolicy(reqPolicy);
2371         }
2372     }
2373
2374     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2375         sendAdminCommandLocked(admin, action, null);
2376     }
2377
2378     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2379         sendAdminCommandLocked(admin, action, null, result);
2380     }
2381
2382     /**
2383      * Send an update to one specific admin, get notified when that admin returns a result.
2384      */
2385     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2386             BroadcastReceiver result) {
2387         Intent intent = new Intent(action);
2388         intent.setComponent(admin.info.getComponent());
2389         if (UserManager.isDeviceInDemoMode(mContext)) {
2390             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2391         }
2392         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2393             intent.putExtra("expiration", admin.passwordExpirationDate);
2394         }
2395         if (adminExtras != null) {
2396             intent.putExtras(adminExtras);
2397         }
2398         if (result != null) {
2399             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2400                     null, result, mHandler, Activity.RESULT_OK, null, null);
2401         } else {
2402             mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2403         }
2404     }
2405
2406     /**
2407      * Send an update to all admins of a user that enforce a specified policy.
2408      */
2409     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
2410         final DevicePolicyData policy = getUserData(userHandle);
2411         final int count = policy.mAdminList.size();
2412         for (int i = 0; i < count; i++) {
2413             final ActiveAdmin admin = policy.mAdminList.get(i);
2414             if (admin.info.usesPolicy(reqPolicy)) {
2415                 sendAdminCommandLocked(admin, action, adminExtras, null);
2416             }
2417         }
2418     }
2419
2420     /**
2421      * Send an update intent to all admins of a user and its profiles. Only send to admins that
2422      * enforce a specified policy.
2423      */
2424     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2425             int userHandle, Bundle adminExtras) {
2426         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2427         for (int profileId : profileIds) {
2428             sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
2429         }
2430     }
2431
2432     /**
2433      * Sends a broadcast to each profile that share the password unlock with the given user id.
2434      */
2435     private void sendAdminCommandForLockscreenPoliciesLocked(
2436             String action, int reqPolicy, int userHandle) {
2437         final Bundle extras = new Bundle();
2438         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2439         if (isSeparateProfileChallengeEnabled(userHandle)) {
2440             sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
2441         } else {
2442             sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
2443         }
2444     }
2445
2446     void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2447         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2448         DevicePolicyData policy = getUserData(userHandle);
2449         if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2450             policy.mRemovingAdmins.add(adminReceiver);
2451             sendAdminCommandLocked(admin,
2452                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2453                     new BroadcastReceiver() {
2454                         @Override
2455                         public void onReceive(Context context, Intent intent) {
2456                             removeAdminArtifacts(adminReceiver, userHandle);
2457                             removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2458                         }
2459                     });
2460         }
2461     }
2462
2463
2464     public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2465             boolean throwForMissiongPermission) {
2466         if (!mHasFeature) {
2467             return null;
2468         }
2469         enforceFullCrossUsersPermission(userHandle);
2470         ActivityInfo ai = null;
2471         try {
2472             ai = mIPackageManager.getReceiverInfo(adminName,
2473                     PackageManager.GET_META_DATA |
2474                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2475                     PackageManager.MATCH_DIRECT_BOOT_AWARE |
2476                     PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2477         } catch (RemoteException e) {
2478             // shouldn't happen.
2479         }
2480         if (ai == null) {
2481             throw new IllegalArgumentException("Unknown admin: " + adminName);
2482         }
2483
2484         if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2485             final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2486                     + permission.BIND_DEVICE_ADMIN;
2487             Slog.w(LOG_TAG, message);
2488             if (throwForMissiongPermission &&
2489                     ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2490                 throw new IllegalArgumentException(message);
2491             }
2492         }
2493
2494         try {
2495             return new DeviceAdminInfo(mContext, ai);
2496         } catch (XmlPullParserException | IOException e) {
2497             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2498                     e);
2499             return null;
2500         }
2501     }
2502
2503     private JournaledFile makeJournaledFile(int userHandle) {
2504         final String base = userHandle == UserHandle.USER_SYSTEM
2505                 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2506                 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2507                         DEVICE_POLICIES_XML).getAbsolutePath();
2508         if (VERBOSE_LOG) {
2509             Log.v(LOG_TAG, "Opening " + base);
2510         }
2511         return new JournaledFile(new File(base), new File(base + ".tmp"));
2512     }
2513
2514     private void saveSettingsLocked(int userHandle) {
2515         DevicePolicyData policy = getUserData(userHandle);
2516         JournaledFile journal = makeJournaledFile(userHandle);
2517         FileOutputStream stream = null;
2518         try {
2519             stream = new FileOutputStream(journal.chooseForWrite(), false);
2520             XmlSerializer out = new FastXmlSerializer();
2521             out.setOutput(stream, StandardCharsets.UTF_8.name());
2522             out.startDocument(null, true);
2523
2524             out.startTag(null, "policies");
2525             if (policy.mRestrictionsProvider != null) {
2526                 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2527                         policy.mRestrictionsProvider.flattenToString());
2528             }
2529             if (policy.mUserSetupComplete) {
2530                 out.attribute(null, ATTR_SETUP_COMPLETE,
2531                         Boolean.toString(true));
2532             }
2533             if (policy.mPaired) {
2534                 out.attribute(null, ATTR_DEVICE_PAIRED,
2535                         Boolean.toString(true));
2536             }
2537             if (policy.mDeviceProvisioningConfigApplied) {
2538                 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2539                         Boolean.toString(true));
2540             }
2541             if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2542                 out.attribute(null, ATTR_PROVISIONING_STATE,
2543                         Integer.toString(policy.mUserProvisioningState));
2544             }
2545             if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2546                 out.attribute(null, ATTR_PERMISSION_POLICY,
2547                         Integer.toString(policy.mPermissionPolicy));
2548             }
2549
2550             // Serialize delegations.
2551             for (int i = 0; i < policy.mDelegationMap.size(); ++i) {
2552                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
2553                 final List<String> scopes = policy.mDelegationMap.valueAt(i);
2554
2555                 // Every "delegation" tag serializes the information of one delegate-scope pair.
2556                 for (String scope : scopes) {
2557                     out.startTag(null, "delegation");
2558                     out.attribute(null, "delegatePackage", delegatePackage);
2559                     out.attribute(null, "scope", scope);
2560                     out.endTag(null, "delegation");
2561                 }
2562             }
2563
2564             final int N = policy.mAdminList.size();
2565             for (int i=0; i<N; i++) {
2566                 ActiveAdmin ap = policy.mAdminList.get(i);
2567                 if (ap != null) {
2568                     out.startTag(null, "admin");
2569                     out.attribute(null, "name", ap.info.getComponent().flattenToString());
2570                     ap.writeToXml(out);
2571                     out.endTag(null, "admin");
2572                 }
2573             }
2574
2575             if (policy.mPasswordOwner >= 0) {
2576                 out.startTag(null, "password-owner");
2577                 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2578                 out.endTag(null, "password-owner");
2579             }
2580
2581             if (policy.mFailedPasswordAttempts != 0) {
2582                 out.startTag(null, "failed-password-attempts");
2583                 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2584                 out.endTag(null, "failed-password-attempts");
2585             }
2586
2587             // For FDE devices only, we save this flag so we can report on password sufficiency
2588             // before the user enters their password for the first time after a reboot.  For
2589             // security reasons, we don't want to store the full set of active password metrics.
2590             if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2591                 out.startTag(null, TAG_PASSWORD_VALIDITY);
2592                 out.attribute(null, ATTR_VALUE,
2593                         Boolean.toString(policy.mPasswordValidAtLastCheckpoint));
2594                 out.endTag(null, TAG_PASSWORD_VALIDITY);
2595             }
2596
2597             for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2598                 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2599                 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2600                 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2601             }
2602
2603             for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2604                 String component = policy.mLockTaskPackages.get(i);
2605                 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2606                 out.attribute(null, "name", component);
2607                 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2608             }
2609
2610             if (policy.mStatusBarDisabled) {
2611                 out.startTag(null, TAG_STATUS_BAR);
2612                 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2613                 out.endTag(null, TAG_STATUS_BAR);
2614             }
2615
2616             if (policy.doNotAskCredentialsOnBoot) {
2617                 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2618                 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2619             }
2620
2621             for (String id : policy.mAffiliationIds) {
2622                 out.startTag(null, TAG_AFFILIATION_ID);
2623                 out.attribute(null, ATTR_ID, id);
2624                 out.endTag(null, TAG_AFFILIATION_ID);
2625             }
2626
2627             if (policy.mLastSecurityLogRetrievalTime >= 0) {
2628                 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2629                 out.attribute(null, ATTR_VALUE,
2630                         Long.toString(policy.mLastSecurityLogRetrievalTime));
2631                 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2632             }
2633
2634             if (policy.mLastBugReportRequestTime >= 0) {
2635                 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2636                 out.attribute(null, ATTR_VALUE,
2637                         Long.toString(policy.mLastBugReportRequestTime));
2638                 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2639             }
2640
2641             if (policy.mLastNetworkLogsRetrievalTime >= 0) {
2642                 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2643                 out.attribute(null, ATTR_VALUE,
2644                         Long.toString(policy.mLastNetworkLogsRetrievalTime));
2645                 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2646             }
2647
2648             if (policy.mAdminBroadcastPending) {
2649                 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2650                 out.attribute(null, ATTR_VALUE,
2651                         Boolean.toString(policy.mAdminBroadcastPending));
2652                 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2653             }
2654
2655             if (policy.mInitBundle != null) {
2656                 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2657                 policy.mInitBundle.saveToXml(out);
2658                 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2659             }
2660
2661             if (policy.mPasswordTokenHandle != 0) {
2662                 out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE);
2663                 out.attribute(null, ATTR_VALUE,
2664                         Long.toString(policy.mPasswordTokenHandle));
2665                 out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE);
2666             }
2667
2668             if (policy.mCurrentInputMethodSet) {
2669                 out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET);
2670                 out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET);
2671             }
2672
2673             for (final String cert : policy.mOwnerInstalledCaCerts) {
2674                 out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT);
2675                 out.attribute(null, ATTR_ALIAS, cert);
2676                 out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT);
2677             }
2678
2679             out.endTag(null, "policies");
2680
2681             out.endDocument();
2682             stream.flush();
2683             FileUtils.sync(stream);
2684             stream.close();
2685             journal.commit();
2686             sendChangedNotification(userHandle);
2687         } catch (XmlPullParserException | IOException e) {
2688             Slog.w(LOG_TAG, "failed writing file", e);
2689             try {
2690                 if (stream != null) {
2691                     stream.close();
2692                 }
2693             } catch (IOException ex) {
2694                 // Ignore
2695             }
2696             journal.rollback();
2697         }
2698     }
2699
2700     private void sendChangedNotification(int userHandle) {
2701         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2702         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2703         long ident = mInjector.binderClearCallingIdentity();
2704         try {
2705             mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2706         } finally {
2707             mInjector.binderRestoreCallingIdentity(ident);
2708         }
2709     }
2710
2711     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2712         JournaledFile journal = makeJournaledFile(userHandle);
2713         FileInputStream stream = null;
2714         File file = journal.chooseForRead();
2715         boolean needsRewrite = false;
2716         try {
2717             stream = new FileInputStream(file);
2718             XmlPullParser parser = Xml.newPullParser();
2719             parser.setInput(stream, StandardCharsets.UTF_8.name());
2720
2721             int type;
2722             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2723                     && type != XmlPullParser.START_TAG) {
2724             }
2725             String tag = parser.getName();
2726             if (!"policies".equals(tag)) {
2727                 throw new XmlPullParserException(
2728                         "Settings do not start with policies tag: found " + tag);
2729             }
2730
2731             // Extract the permission provider component name if available
2732             String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2733             if (permissionProvider != null) {
2734                 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2735             }
2736             String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2737             if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2738                 policy.mUserSetupComplete = true;
2739             }
2740             String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2741             if (paired != null && Boolean.toString(true).equals(paired)) {
2742                 policy.mPaired = true;
2743             }
2744             String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2745                     ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2746             if (deviceProvisioningConfigApplied != null
2747                     && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2748                 policy.mDeviceProvisioningConfigApplied = true;
2749             }
2750             String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2751             if (!TextUtils.isEmpty(provisioningState)) {
2752                 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2753             }
2754             String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2755             if (!TextUtils.isEmpty(permissionPolicy)) {
2756                 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2757             }
2758             // Check for delegation compatibility with pre-O.
2759             // TODO(edmanp) remove in P.
2760             {
2761                 final String certDelegate = parser.getAttributeValue(null,
2762                         ATTR_DELEGATED_CERT_INSTALLER);
2763                 if (certDelegate != null) {
2764                     List<String> scopes = policy.mDelegationMap.get(certDelegate);
2765                     if (scopes == null) {
2766                         scopes = new ArrayList<>();
2767                         policy.mDelegationMap.put(certDelegate, scopes);
2768                     }
2769                     if (!scopes.contains(DELEGATION_CERT_INSTALL)) {
2770                         scopes.add(DELEGATION_CERT_INSTALL);
2771                         needsRewrite = true;
2772                     }
2773                 }
2774                 final String appRestrictionsDelegate = parser.getAttributeValue(null,
2775                         ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2776                 if (appRestrictionsDelegate != null) {
2777                     List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate);
2778                     if (scopes == null) {
2779                         scopes = new ArrayList<>();
2780                         policy.mDelegationMap.put(appRestrictionsDelegate, scopes);
2781                     }
2782                     if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) {
2783                         scopes.add(DELEGATION_APP_RESTRICTIONS);
2784                         needsRewrite = true;
2785                     }
2786                 }
2787             }
2788
2789             type = parser.next();
2790             int outerDepth = parser.getDepth();
2791             policy.mLockTaskPackages.clear();
2792             policy.mAdminList.clear();
2793             policy.mAdminMap.clear();
2794             policy.mAffiliationIds.clear();
2795             policy.mOwnerInstalledCaCerts.clear();
2796             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2797                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2798                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2799                     continue;
2800                 }
2801                 tag = parser.getName();
2802                 if ("admin".equals(tag)) {
2803                     String name = parser.getAttributeValue(null, "name");
2804                     try {
2805                         DeviceAdminInfo dai = findAdmin(
2806                                 ComponentName.unflattenFromString(name), userHandle,
2807                                 /* throwForMissionPermission= */ false);
2808                         if (VERBOSE_LOG
2809                                 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2810                                 != userHandle)) {
2811                             Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2812                                     + dai.getActivityInfo().applicationInfo.uid + " for user "
2813                                     + userHandle);
2814                         }
2815                         if (dai != null) {
2816                             ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2817                             ap.readFromXml(parser);
2818                             policy.mAdminMap.put(ap.info.getComponent(), ap);
2819                         }
2820                     } catch (RuntimeException e) {
2821                         Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2822                     }
2823                 } else if ("delegation".equals(tag)) {
2824                     // Parse delegation info.
2825                     final String delegatePackage = parser.getAttributeValue(null,
2826                             "delegatePackage");
2827                     final String scope = parser.getAttributeValue(null, "scope");
2828
2829                     // Get a reference to the scopes list for the delegatePackage.
2830                     List<String> scopes = policy.mDelegationMap.get(delegatePackage);
2831                     // Or make a new list if none was found.
2832                     if (scopes == null) {
2833                         scopes = new ArrayList<>();
2834                         policy.mDelegationMap.put(delegatePackage, scopes);
2835                     }
2836                     // Add the new scope to the list of delegatePackage if it's not already there.
2837                     if (!scopes.contains(scope)) {
2838                         scopes.add(scope);
2839                     }
2840                 } else if ("failed-password-attempts".equals(tag)) {
2841                     policy.mFailedPasswordAttempts = Integer.parseInt(
2842                             parser.getAttributeValue(null, "value"));
2843                 } else if ("password-owner".equals(tag)) {
2844                     policy.mPasswordOwner = Integer.parseInt(
2845                             parser.getAttributeValue(null, "value"));
2846                 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2847                     policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2848                 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2849                     policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2850                 } else if (TAG_STATUS_BAR.equals(tag)) {
2851                     policy.mStatusBarDisabled = Boolean.parseBoolean(
2852                             parser.getAttributeValue(null, ATTR_DISABLED));
2853                 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2854                     policy.doNotAskCredentialsOnBoot = true;
2855                 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2856                     policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID));
2857                 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) {
2858                     policy.mLastSecurityLogRetrievalTime = Long.parseLong(
2859                             parser.getAttributeValue(null, ATTR_VALUE));
2860                 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) {
2861                     policy.mLastBugReportRequestTime = Long.parseLong(
2862                             parser.getAttributeValue(null, ATTR_VALUE));
2863                 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) {
2864                     policy.mLastNetworkLogsRetrievalTime = Long.parseLong(
2865                             parser.getAttributeValue(null, ATTR_VALUE));
2866                 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2867                     String pending = parser.getAttributeValue(null, ATTR_VALUE);
2868                     policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2869                 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2870                     policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2871                 } else if ("active-password".equals(tag)) {
2872                     // Remove password metrics from saved settings, as we no longer wish to store
2873                     // these on disk
2874                     needsRewrite = true;
2875                 } else if (TAG_PASSWORD_VALIDITY.equals(tag)) {
2876                     if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2877                         // This flag is only used for FDE devices
2878                         policy.mPasswordValidAtLastCheckpoint = Boolean.parseBoolean(
2879                                 parser.getAttributeValue(null, ATTR_VALUE));
2880                     }
2881                 } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) {
2882                     policy.mPasswordTokenHandle = Long.parseLong(
2883                             parser.getAttributeValue(null, ATTR_VALUE));
2884                 } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) {
2885                     policy.mCurrentInputMethodSet = true;
2886                 } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) {
2887                     policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS));
2888                 } else {
2889                     Slog.w(LOG_TAG, "Unknown tag: " + tag);
2890                     XmlUtils.skipCurrentTag(parser);
2891                 }
2892             }
2893         } catch (FileNotFoundException e) {
2894             // Don't be noisy, this is normal if we haven't defined any policies.
2895         } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2896                 | IndexOutOfBoundsException e) {
2897             Slog.w(LOG_TAG, "failed parsing " + file, e);
2898         }
2899         try {
2900             if (stream != null) {
2901                 stream.close();
2902             }
2903         } catch (IOException e) {
2904             // Ignore
2905         }
2906
2907         // Generate a list of admins from the admin map
2908         policy.mAdminList.addAll(policy.mAdminMap.values());
2909
2910         // Might need to upgrade the file by rewriting it
2911         if (needsRewrite) {
2912             saveSettingsLocked(userHandle);
2913         }
2914
2915         validatePasswordOwnerLocked(policy);
2916         updateMaximumTimeToLockLocked(userHandle);
2917         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2918         if (policy.mStatusBarDisabled) {
2919             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2920         }
2921     }
2922
2923     private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2924         long ident = mInjector.binderClearCallingIdentity();
2925         try {
2926             mInjector.getIActivityManager()
2927                     .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2928         } catch (RemoteException e) {
2929             // Not gonna happen.
2930         } finally {
2931             mInjector.binderRestoreCallingIdentity(ident);
2932         }
2933     }
2934
2935     private void updateDeviceOwnerLocked() {
2936         long ident = mInjector.binderClearCallingIdentity();
2937         try {
2938             // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2939             // user id and also protect all other DAs too.
2940             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2941             if (deviceOwnerComponent != null) {
2942                 mInjector.getIActivityManager()
2943                         .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2944             }
2945         } catch (RemoteException e) {
2946             // Not gonna happen.
2947         } finally {
2948             mInjector.binderRestoreCallingIdentity(ident);
2949         }
2950     }
2951
2952     static void validateQualityConstant(int quality) {
2953         switch (quality) {
2954             case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2955             case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2956             case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2957             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2958             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2959             case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2960             case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2961             case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2962             case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2963                 return;
2964         }
2965         throw new IllegalArgumentException("Invalid quality constant: 0x"
2966                 + Integer.toHexString(quality));
2967     }
2968
2969     void validatePasswordOwnerLocked(DevicePolicyData policy) {
2970         if (policy.mPasswordOwner >= 0) {
2971             boolean haveOwner = false;
2972             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2973                 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2974                     haveOwner = true;
2975                     break;
2976                 }
2977             }
2978             if (!haveOwner) {
2979                 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2980                         + " no longer active; disabling");
2981                 policy.mPasswordOwner = -1;
2982             }
2983         }
2984     }
2985
2986     @VisibleForTesting
2987     void systemReady(int phase) {
2988         if (!mHasFeature) {
2989             return;
2990         }
2991         switch (phase) {
2992             case SystemService.PHASE_LOCK_SETTINGS_READY:
2993                 onLockSettingsReady();
2994                 break;
2995             case SystemService.PHASE_BOOT_COMPLETED:
2996                 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2997                 break;
2998         }
2999     }
3000
3001     private void onLockSettingsReady() {
3002         getUserData(UserHandle.USER_SYSTEM);
3003         loadOwners();
3004         cleanUpOldUsers();
3005         maybeSetDefaultProfileOwnerUserRestrictions();
3006         handleStartUser(UserHandle.USER_SYSTEM);
3007
3008         // Register an observer for watching for user setup complete and settings changes.
3009         mSetupContentObserver.register();
3010         // Initialize the user setup state, to handle the upgrade case.
3011         updateUserSetupCompleteAndPaired();
3012
3013         List<String> packageList;
3014         synchronized (this) {
3015             packageList = getKeepUninstalledPackagesLocked();
3016         }
3017         if (packageList != null) {
3018             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3019         }
3020
3021         synchronized (this) {
3022             // push the force-ephemeral-users policy to the user manager.
3023             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3024             if (deviceOwner != null) {
3025                 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3026             }
3027         }
3028     }
3029
3030     private void ensureDeviceOwnerUserStarted() {
3031         final int userId;
3032         synchronized (this) {
3033             if (!mOwners.hasDeviceOwner()) {
3034                 return;
3035             }
3036             userId = mOwners.getDeviceOwnerUserId();
3037         }
3038         if (VERBOSE_LOG) {
3039             Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
3040         }
3041         if (userId != UserHandle.USER_SYSTEM) {
3042             try {
3043                 mInjector.getIActivityManager().startUserInBackground(userId);
3044
3045                 // STOPSHIP Prevent the DO user from being killed.
3046
3047             } catch (RemoteException e) {
3048                 Slog.w(LOG_TAG, "Exception starting user", e);
3049             }
3050         }
3051     }
3052
3053     void handleStartUser(int userId) {
3054         updateScreenCaptureDisabledInWindowManager(userId,
3055                 getScreenCaptureDisabled(null, userId));
3056         pushUserRestrictions(userId);
3057
3058         startOwnerService(userId, "start-user");
3059     }
3060
3061     void handleUnlockUser(int userId) {
3062         startOwnerService(userId, "unlock-user");
3063     }
3064
3065     void handleStopUser(int userId) {
3066         stopOwnerService(userId, "stop-user");
3067     }
3068
3069     private void startOwnerService(int userId, String actionForLog) {
3070         final ComponentName owner = getOwnerComponent(userId);
3071         if (owner != null) {
3072             mDeviceAdminServiceController.startServiceForOwner(
3073                     owner.getPackageName(), userId, actionForLog);
3074         }
3075     }
3076
3077     private void stopOwnerService(int userId, String actionForLog) {
3078         mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog);
3079     }
3080
3081     private void cleanUpOldUsers() {
3082         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3083         // before reboot
3084         Set<Integer> usersWithProfileOwners;
3085         Set<Integer> usersWithData;
3086         synchronized(this) {
3087             usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3088             usersWithData = new ArraySet<>();
3089             for (int i = 0; i < mUserData.size(); i++) {
3090                 usersWithData.add(mUserData.keyAt(i));
3091             }
3092         }
3093         List<UserInfo> allUsers = mUserManager.getUsers();
3094
3095         Set<Integer> deletedUsers = new ArraySet<>();
3096         deletedUsers.addAll(usersWithProfileOwners);
3097         deletedUsers.addAll(usersWithData);
3098         for (UserInfo userInfo : allUsers) {
3099             deletedUsers.remove(userInfo.id);
3100         }
3101         for (Integer userId : deletedUsers) {
3102             removeUserData(userId);
3103         }
3104     }
3105
3106     private void handlePasswordExpirationNotification(int userHandle) {
3107         final Bundle adminExtras = new Bundle();
3108         adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3109
3110         synchronized (this) {
3111             final long now = System.currentTimeMillis();
3112
3113             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3114                     userHandle, /* parent */ false);
3115             final int N = admins.size();
3116             for (int i = 0; i < N; i++) {
3117                 ActiveAdmin admin = admins.get(i);
3118                 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
3119                         && admin.passwordExpirationTimeout > 0L
3120                         && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3121                         && admin.passwordExpirationDate > 0L) {
3122                     sendAdminCommandLocked(admin,
3123                             DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3124                 }
3125             }
3126             setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3127         }
3128     }
3129
3130     /**
3131      * Clean up internal state when the set of installed trusted CA certificates changes.
3132      *
3133      * @param userHandle user to check for. This must be a real user and not, for example,
3134      *        {@link UserHandle#ALL}.
3135      * @param installedCertificates the full set of certificate authorities currently installed for
3136      *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3137      *        correspond to some subset of this.
3138      */
3139     protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3140             final @NonNull Collection<String> installedCertificates) {
3141         if (!mHasFeature) {
3142             return;
3143         }
3144         enforceManageUsers();
3145
3146         synchronized (this) {
3147             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3148
3149             boolean changed = false;
3150             changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3151             changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3152             if (changed) {
3153                 saveSettingsLocked(userHandle.getIdentifier());
3154             }
3155         }
3156     }
3157
3158     /**
3159      * Internal method used by {@link CertificateMonitor}.
3160      */
3161     protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3162         if (!mHasFeature) {
3163             return Collections.<String> emptySet();
3164         }
3165         synchronized (this) {
3166             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3167             return policy.mAcceptedCaCertificates;
3168         }
3169     }
3170
3171     /**
3172      * @param adminReceiver The admin to add
3173      * @param refreshing true = update an active admin, no error
3174      */
3175     @Override
3176     public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
3177         if (!mHasFeature) {
3178             return;
3179         }
3180         setActiveAdmin(adminReceiver, refreshing, userHandle, null);
3181     }
3182
3183     private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
3184             Bundle onEnableData) {
3185         mContext.enforceCallingOrSelfPermission(
3186                 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3187         enforceFullCrossUsersPermission(userHandle);
3188
3189         DevicePolicyData policy = getUserData(userHandle);
3190         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3191                 /* throwForMissionPermission= */ true);
3192         if (info == null) {
3193             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3194         }
3195         if (!info.getActivityInfo().applicationInfo.isInternal()) {
3196             throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3197                     + adminReceiver);
3198         }
3199         if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3200             throw new IllegalArgumentException("Instant apps cannot be device admins: "
3201                     + adminReceiver);
3202         }
3203         synchronized (this) {
3204             long ident = mInjector.binderClearCallingIdentity();
3205             try {
3206                 final ActiveAdmin existingAdmin
3207                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3208                 if (!refreshing && existingAdmin != null) {
3209                     throw new IllegalArgumentException("Admin is already added");
3210                 }
3211                 if (policy.mRemovingAdmins.contains(adminReceiver)) {
3212                     throw new IllegalArgumentException(
3213                             "Trying to set an admin which is being removed");
3214                 }
3215                 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3216                 newAdmin.testOnlyAdmin =
3217                         (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3218                                 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3219                 policy.mAdminMap.put(adminReceiver, newAdmin);
3220                 int replaceIndex = -1;
3221                 final int N = policy.mAdminList.size();
3222                 for (int i=0; i < N; i++) {
3223                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3224                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3225                         replaceIndex = i;
3226                         break;
3227                     }
3228                 }
3229                 if (replaceIndex == -1) {
3230                     policy.mAdminList.add(newAdmin);
3231                     enableIfNecessary(info.getPackageName(), userHandle);
3232                 } else {
3233                     policy.mAdminList.set(replaceIndex, newAdmin);
3234                 }
3235                 saveSettingsLocked(userHandle);
3236                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3237                         onEnableData, null);
3238             } finally {
3239                 mInjector.binderRestoreCallingIdentity(ident);
3240             }
3241         }
3242     }
3243
3244     @Override
3245     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3246         if (!mHasFeature) {
3247             return false;
3248         }
3249         enforceFullCrossUsersPermission(userHandle);
3250         synchronized (this) {
3251             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3252         }
3253     }
3254
3255     @Override
3256     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3257         if (!mHasFeature) {
3258             return false;
3259         }
3260         enforceFullCrossUsersPermission(userHandle);
3261         synchronized (this) {
3262             DevicePolicyData policyData = getUserData(userHandle);
3263             return policyData.mRemovingAdmins.contains(adminReceiver);
3264         }
3265     }
3266
3267     @Override
3268     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3269         if (!mHasFeature) {
3270             return false;
3271         }
3272         enforceFullCrossUsersPermission(userHandle);
3273         synchronized (this) {
3274             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3275             if (administrator == null) {
3276                 throw new SecurityException("No active admin " + adminReceiver);
3277             }
3278             return administrator.info.usesPolicy(policyId);
3279         }
3280     }
3281
3282     @Override
3283     @SuppressWarnings("unchecked")
3284     public List<ComponentName> getActiveAdmins(int userHandle) {
3285         if (!mHasFeature) {
3286             return Collections.EMPTY_LIST;
3287         }
3288
3289         enforceFullCrossUsersPermission(userHandle);
3290         synchronized (this) {
3291             DevicePolicyData policy = getUserData(userHandle);
3292             final int N = policy.mAdminList.size();
3293             if (N <= 0) {
3294                 return null;
3295             }
3296             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3297             for (int i=0; i<N; i++) {
3298                 res.add(policy.mAdminList.get(i).info.getComponent());
3299             }
3300             return res;
3301         }
3302     }
3303
3304     @Override
3305     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3306         if (!mHasFeature) {
3307             return false;
3308         }
3309         enforceFullCrossUsersPermission(userHandle);
3310         synchronized (this) {
3311             DevicePolicyData policy = getUserData(userHandle);
3312             final int N = policy.mAdminList.size();
3313             for (int i=0; i<N; i++) {
3314                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3315                     return true;
3316                 }
3317             }
3318             return false;
3319         }
3320     }
3321
3322     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3323         if (!mHasFeature) {
3324             return;
3325         }
3326         Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3327         enforceShell("forceRemoveActiveAdmin");
3328         long ident = mInjector.binderClearCallingIdentity();
3329         try {
3330             synchronized (this)  {
3331                 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3332                     throw new SecurityException("Attempt to remove non-test admin "
3333                             + adminReceiver + " " + userHandle);
3334                 }
3335
3336                 // If admin is a device or profile owner tidy that up first.
3337                 if (isDeviceOwner(adminReceiver, userHandle)) {
3338                     clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3339                 }
3340                 if (isProfileOwner(adminReceiver, userHandle)) {
3341                     final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3342                             userHandle, /* parent */ false);
3343                     clearProfileOwnerLocked(admin, userHandle);
3344                 }
3345             }
3346             // Remove the admin skipping sending the broadcast.
3347             removeAdminArtifacts(adminReceiver, userHandle);
3348             Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3349         } finally {
3350             mInjector.binderRestoreCallingIdentity(ident);
3351         }
3352     }
3353
3354     private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) {
3355         // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state
3356         if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
3357             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle);
3358         }
3359     }
3360
3361     /**
3362      * Return if a given package has testOnly="true", in which case we'll relax certain rules
3363      * for CTS.
3364      *
3365      * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
3366      * to check wehter an active admin is test-only or not.
3367      *
3368      * The system allows this flag to be changed when an app is updated, which is not good
3369      * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3370      * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3371      */
3372     private boolean isPackageTestOnly(String packageName, int userHandle) {
3373         final ApplicationInfo ai;
3374         try {
3375             ai = mIPackageManager.getApplicationInfo(packageName,
3376                     (PackageManager.MATCH_DIRECT_BOOT_AWARE
3377                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3378         } catch (RemoteException e) {
3379             throw new IllegalStateException(e);
3380         }
3381         if (ai == null) {
3382             throw new IllegalStateException("Couldn't find package: "
3383                     + packageName + " on user " + userHandle);
3384         }
3385         return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3386     }
3387
3388     /**
3389      * See {@link #isPackageTestOnly}.
3390      */
3391     private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3392         final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3393         return (admin != null) && admin.testOnlyAdmin;
3394     }
3395
3396     private void enforceShell(String method) {
3397         final int callingUid = Binder.getCallingUid();
3398         if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3399             throw new SecurityException("Non-shell user attempted to call " + method);
3400         }
3401     }
3402
3403     @Override
3404     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3405         if (!mHasFeature) {
3406             return;
3407         }
3408         enforceFullCrossUsersPermission(userHandle);
3409         enforceUserUnlocked(userHandle);
3410         synchronized (this) {
3411             ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3412             if (admin == null) {
3413                 return;
3414             }
3415             // Active device/profile owners must remain active admins.
3416             if (isDeviceOwner(adminReceiver, userHandle)
3417                     || isProfileOwner(adminReceiver, userHandle)) {
3418                 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3419                         adminReceiver);
3420                 return;
3421             }
3422             if (admin.getUid() != mInjector.binderGetCallingUid()) {
3423                 mContext.enforceCallingOrSelfPermission(
3424                         android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3425             }
3426             long ident = mInjector.binderClearCallingIdentity();
3427             try {
3428                 removeActiveAdminLocked(adminReceiver, userHandle);
3429             } finally {
3430                 mInjector.binderRestoreCallingIdentity(ident);
3431             }
3432         }
3433     }
3434
3435     @Override
3436     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3437         ComponentName profileOwner = getProfileOwner(userHandle);
3438         // Profile challenge is supported on N or newer release.
3439         return profileOwner != null &&
3440                 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3441     }
3442
3443     @Override
3444     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3445         if (!mHasFeature) {
3446             return;
3447         }
3448         Preconditions.checkNotNull(who, "ComponentName is null");
3449         validateQualityConstant(quality);
3450
3451         synchronized (this) {
3452             ActiveAdmin ap = getActiveAdminForCallerLocked(
3453                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3454             if (ap.minimumPasswordMetrics.quality != quality) {
3455                 ap.minimumPasswordMetrics.quality = quality;
3456                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3457                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3458             }
3459         }
3460     }
3461
3462     /**
3463      * Updates flag in memory that tells us whether the user's password currently satisfies the
3464      * requirements set by all of the user's active admins.  This should be called before
3465      * {@link #saveSettingsLocked} whenever the password or the admin policies have changed.
3466      */
3467     @GuardedBy("DevicePolicyManagerService.this")
3468     private void updatePasswordValidityCheckpointLocked(int userHandle) {
3469         DevicePolicyData policy = getUserData(userHandle);
3470         policy.mPasswordValidAtLastCheckpoint = isActivePasswordSufficientForUserLocked(
3471                 policy, policy.mUserHandle, false);
3472     }
3473
3474     @Override
3475     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3476         if (!mHasFeature) {
3477             return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3478         }
3479         enforceFullCrossUsersPermission(userHandle);
3480         synchronized (this) {
3481             int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3482
3483             if (who != null) {
3484                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3485                 return admin != null ? admin.minimumPasswordMetrics.quality : mode;
3486             }
3487
3488             // Return the strictest policy across all participating admins.
3489             List<ActiveAdmin> admins =
3490                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3491             final int N = admins.size();
3492             for (int i = 0; i < N; i++) {
3493                 ActiveAdmin admin = admins.get(i);
3494                 if (mode < admin.minimumPasswordMetrics.quality) {
3495                     mode = admin.minimumPasswordMetrics.quality;
3496                 }
3497             }
3498             return mode;
3499         }
3500     }
3501
3502     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3503             int userHandle, boolean parent) {
3504         if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3505             // If this user has a separate challenge, only return its restrictions.
3506             return getUserDataUnchecked(userHandle).mAdminList;
3507         } else {
3508             // Return all admins for this user and the profiles that are visible from this
3509             // user that do not use a separate work challenge.
3510             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3511             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3512                 DevicePolicyData policy = getUserData(userInfo.id);
3513                 if (!userInfo.isManagedProfile()) {
3514                     admins.addAll(policy.mAdminList);
3515                 } else {
3516                     // For managed profiles, we always include the policies set on the parent
3517                     // profile. Additionally, we include the ones set on the managed profile
3518                     // if no separate challenge is in place.
3519                     boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3520                     final int N = policy.mAdminList.size();
3521                     for (int i = 0; i < N; i++) {
3522                         ActiveAdmin admin = policy.mAdminList.get(i);
3523                         if (admin.hasParentActiveAdmin()) {
3524                             admins.add(admin.getParentActiveAdmin());
3525                         }
3526                         if (!hasSeparateChallenge) {
3527                             admins.add(admin);
3528                         }
3529                     }
3530                 }
3531             }
3532             return admins;
3533         }
3534     }
3535
3536     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3537         long ident = mInjector.binderClearCallingIdentity();
3538         try {
3539             return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3540         } finally {
3541             mInjector.binderRestoreCallingIdentity(ident);
3542         }
3543     }
3544
3545     @Override
3546     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3547         if (!mHasFeature) {
3548             return;
3549         }
3550         Preconditions.checkNotNull(who, "ComponentName is null");
3551         synchronized (this) {
3552             ActiveAdmin ap = getActiveAdminForCallerLocked(
3553                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3554             if (ap.minimumPasswordMetrics.length != length) {
3555                 ap.minimumPasswordMetrics.length = length;
3556                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3557                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3558             }
3559         }
3560     }
3561
3562     @Override
3563     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3564         if (!mHasFeature) {
3565             return 0;
3566         }
3567         enforceFullCrossUsersPermission(userHandle);
3568         synchronized (this) {
3569             int length = 0;
3570
3571             if (who != null) {
3572                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3573                 return admin != null ? admin.minimumPasswordMetrics.length : length;
3574             }
3575
3576             // Return the strictest policy across all participating admins.
3577             List<ActiveAdmin> admins =
3578                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3579             final int N = admins.size();
3580             for (int i = 0; i < N; i++) {
3581                 ActiveAdmin admin = admins.get(i);
3582                 if (length < admin.minimumPasswordMetrics.length) {
3583                     length = admin.minimumPasswordMetrics.length;
3584                 }
3585             }
3586             return length;
3587         }
3588     }
3589
3590     @Override
3591     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3592         if (!mHasFeature) {
3593             return;
3594         }
3595         Preconditions.checkNotNull(who, "ComponentName is null");
3596         synchronized (this) {
3597             ActiveAdmin ap = getActiveAdminForCallerLocked(
3598                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3599             if (ap.passwordHistoryLength != length) {
3600                 ap.passwordHistoryLength = length;
3601                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3602                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3603             }
3604         }
3605     }
3606
3607     @Override
3608     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3609         if (!mHasFeature) {
3610             return 0;
3611         }
3612         enforceFullCrossUsersPermission(userHandle);
3613         synchronized (this) {
3614             int length = 0;
3615
3616             if (who != null) {
3617                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3618                 return admin != null ? admin.passwordHistoryLength : length;
3619             }
3620
3621             // Return the strictest policy across all participating admins.
3622             List<ActiveAdmin> admins =
3623                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3624             final int N = admins.size();
3625             for (int i = 0; i < N; i++) {
3626                 ActiveAdmin admin = admins.get(i);
3627                 if (length < admin.passwordHistoryLength) {
3628                     length = admin.passwordHistoryLength;
3629                 }
3630             }
3631
3632             return length;
3633         }
3634     }
3635
3636     @Override
3637     public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3638         if (!mHasFeature) {
3639             return;
3640         }
3641         Preconditions.checkNotNull(who, "ComponentName is null");
3642         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3643         final int userHandle = mInjector.userHandleGetCallingUserId();
3644         synchronized (this) {
3645             ActiveAdmin ap = getActiveAdminForCallerLocked(
3646                     who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3647             // Calling this API automatically bumps the expiration date
3648             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3649             ap.passwordExpirationDate = expiration;
3650             ap.passwordExpirationTimeout = timeout;
3651             if (timeout > 0L) {
3652                 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3653                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3654                         .format(new Date(expiration)));
3655             }
3656             saveSettingsLocked(userHandle);
3657
3658             // in case this is the first one, set the alarm on the appropriate user.
3659             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3660         }
3661     }
3662
3663     /**
3664      * Return a single admin's expiration cycle time, or the min of all cycle times.
3665      * Returns 0 if not configured.
3666      */
3667     @Override
3668     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3669         if (!mHasFeature) {
3670             return 0L;
3671         }
3672         enforceFullCrossUsersPermission(userHandle);
3673         synchronized (this) {
3674             long timeout = 0L;
3675
3676             if (who != null) {
3677                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3678                 return admin != null ? admin.passwordExpirationTimeout : timeout;
3679             }
3680
3681             // Return the strictest policy across all participating admins.
3682             List<ActiveAdmin> admins =
3683                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3684             final int N = admins.size();
3685             for (int i = 0; i < N; i++) {
3686                 ActiveAdmin admin = admins.get(i);
3687                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3688                         && timeout > admin.passwordExpirationTimeout)) {
3689                     timeout = admin.passwordExpirationTimeout;
3690                 }
3691             }
3692             return timeout;
3693         }
3694     }
3695
3696     @Override
3697     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3698         final int userId = UserHandle.getCallingUserId();
3699         List<String> changedProviders = null;
3700
3701         synchronized (this) {
3702             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3703                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3704             if (activeAdmin.crossProfileWidgetProviders == null) {
3705                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3706             }
3707             List<String> providers = activeAdmin.crossProfileWidgetProviders;
3708             if (!providers.contains(packageName)) {
3709                 providers.add(packageName);
3710                 changedProviders = new ArrayList<>(providers);
3711                 saveSettingsLocked(userId);
3712             }
3713         }
3714
3715         if (changedProviders != null) {
3716             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3717             return true;
3718         }
3719
3720         return false;
3721     }
3722
3723     @Override
3724     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3725         final int userId = UserHandle.getCallingUserId();
3726         List<String> changedProviders = null;
3727
3728         synchronized (this) {
3729             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3730                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3731             if (activeAdmin.crossProfileWidgetProviders == null
3732                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3733                 return false;
3734             }
3735             List<String> providers = activeAdmin.crossProfileWidgetProviders;
3736             if (providers.remove(packageName)) {
3737                 changedProviders = new ArrayList<>(providers);
3738                 saveSettingsLocked(userId);
3739             }
3740         }
3741
3742         if (changedProviders != null) {
3743             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3744             return true;
3745         }
3746
3747         return false;
3748     }
3749
3750     @Override
3751     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3752         synchronized (this) {
3753             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3754                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3755             if (activeAdmin.crossProfileWidgetProviders == null
3756                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3757                 return null;
3758             }
3759             if (mInjector.binderIsCallingUidMyUid()) {
3760                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3761             } else {
3762                 return activeAdmin.crossProfileWidgetProviders;
3763             }
3764         }
3765     }
3766
3767     /**
3768      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3769      * Returns 0 if not configured.
3770      */
3771     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3772         long timeout = 0L;
3773
3774         if (who != null) {
3775             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3776             return admin != null ? admin.passwordExpirationDate : timeout;
3777         }
3778
3779         // Return the strictest policy across all participating admins.
3780         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3781         final int N = admins.size();
3782         for (int i = 0; i < N; i++) {
3783             ActiveAdmin admin = admins.get(i);
3784             if (timeout == 0L || (admin.passwordExpirationDate != 0
3785                     && timeout > admin.passwordExpirationDate)) {
3786                 timeout = admin.passwordExpirationDate;
3787             }
3788         }
3789         return timeout;
3790     }
3791
3792     @Override
3793     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3794         if (!mHasFeature) {
3795             return 0L;
3796         }
3797         enforceFullCrossUsersPermission(userHandle);
3798         synchronized (this) {
3799             return getPasswordExpirationLocked(who, userHandle, parent);
3800         }
3801     }
3802
3803     @Override
3804     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3805         if (!mHasFeature) {
3806             return;
3807         }
3808         Preconditions.checkNotNull(who, "ComponentName is null");
3809         synchronized (this) {
3810             ActiveAdmin ap = getActiveAdminForCallerLocked(
3811                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3812             if (ap.minimumPasswordMetrics.upperCase != length) {
3813                 ap.minimumPasswordMetrics.upperCase = length;
3814                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3815                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3816             }
3817         }
3818     }
3819
3820     @Override
3821     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3822         if (!mHasFeature) {
3823             return 0;
3824         }
3825         enforceFullCrossUsersPermission(userHandle);
3826         synchronized (this) {
3827             int length = 0;
3828
3829             if (who != null) {
3830                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3831                 return admin != null ? admin.minimumPasswordMetrics.upperCase : length;
3832             }
3833
3834             // Return the strictest policy across all participating admins.
3835             List<ActiveAdmin> admins =
3836                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3837             final int N = admins.size();
3838             for (int i = 0; i < N; i++) {
3839                 ActiveAdmin admin = admins.get(i);
3840                 if (length < admin.minimumPasswordMetrics.upperCase) {
3841                     length = admin.minimumPasswordMetrics.upperCase;
3842                 }
3843             }
3844             return length;
3845         }
3846     }
3847
3848     @Override
3849     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3850         Preconditions.checkNotNull(who, "ComponentName is null");
3851         synchronized (this) {
3852             ActiveAdmin ap = getActiveAdminForCallerLocked(
3853                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3854             if (ap.minimumPasswordMetrics.lowerCase != length) {
3855                 ap.minimumPasswordMetrics.lowerCase = length;
3856                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3857                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3858             }
3859         }
3860     }
3861
3862     @Override
3863     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3864         if (!mHasFeature) {
3865             return 0;
3866         }
3867         enforceFullCrossUsersPermission(userHandle);
3868         synchronized (this) {
3869             int length = 0;
3870
3871             if (who != null) {
3872                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3873                 return admin != null ? admin.minimumPasswordMetrics.lowerCase : length;
3874             }
3875
3876             // Return the strictest policy across all participating admins.
3877             List<ActiveAdmin> admins =
3878                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3879             final int N = admins.size();
3880             for (int i = 0; i < N; i++) {
3881                 ActiveAdmin admin = admins.get(i);
3882                 if (length < admin.minimumPasswordMetrics.lowerCase) {
3883                     length = admin.minimumPasswordMetrics.lowerCase;
3884                 }
3885             }
3886             return length;
3887         }
3888     }
3889
3890     @Override
3891     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3892         if (!mHasFeature) {
3893             return;
3894         }
3895         Preconditions.checkNotNull(who, "ComponentName is null");
3896         synchronized (this) {
3897             ActiveAdmin ap = getActiveAdminForCallerLocked(
3898                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3899             if (ap.minimumPasswordMetrics.letters != length) {
3900                 ap.minimumPasswordMetrics.letters = length;
3901                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3902                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3903             }
3904         }
3905     }
3906
3907     @Override
3908     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3909         if (!mHasFeature) {
3910             return 0;
3911         }
3912         enforceFullCrossUsersPermission(userHandle);
3913         synchronized (this) {
3914             int length = 0;
3915
3916             if (who != null) {
3917                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3918                 return admin != null ? admin.minimumPasswordMetrics.letters : length;
3919             }
3920
3921             // Return the strictest policy across all participating admins.
3922             List<ActiveAdmin> admins =
3923                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3924             final int N = admins.size();
3925             for (int i = 0; i < N; i++) {
3926                 ActiveAdmin admin = admins.get(i);
3927                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3928                     continue;
3929                 }
3930                 if (length < admin.minimumPasswordMetrics.letters) {
3931                     length = admin.minimumPasswordMetrics.letters;
3932                 }
3933             }
3934             return length;
3935         }
3936     }
3937
3938     @Override
3939     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3940         if (!mHasFeature) {
3941             return;
3942         }
3943         Preconditions.checkNotNull(who, "ComponentName is null");
3944         synchronized (this) {
3945             ActiveAdmin ap = getActiveAdminForCallerLocked(
3946                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3947             if (ap.minimumPasswordMetrics.numeric != length) {
3948                 ap.minimumPasswordMetrics.numeric = length;
3949                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3950                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3951             }
3952         }
3953     }
3954
3955     @Override
3956     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3957         if (!mHasFeature) {
3958             return 0;
3959         }
3960         enforceFullCrossUsersPermission(userHandle);
3961         synchronized (this) {
3962             int length = 0;
3963
3964             if (who != null) {
3965                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3966                 return admin != null ? admin.minimumPasswordMetrics.numeric : length;
3967             }
3968
3969             // Return the strictest policy across all participating admins.
3970             List<ActiveAdmin> admins =
3971                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3972             final int N = admins.size();
3973             for (int i = 0; i < N; i++) {
3974                 ActiveAdmin admin = admins.get(i);
3975                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3976                     continue;
3977                 }
3978                 if (length < admin.minimumPasswordMetrics.numeric) {
3979                     length = admin.minimumPasswordMetrics.numeric;
3980                 }
3981             }
3982             return length;
3983         }
3984     }
3985
3986     @Override
3987     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3988         if (!mHasFeature) {
3989             return;
3990         }
3991         Preconditions.checkNotNull(who, "ComponentName is null");
3992         synchronized (this) {
3993             ActiveAdmin ap = getActiveAdminForCallerLocked(
3994                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3995             if (ap.minimumPasswordMetrics.symbols != length) {
3996                 ap.minimumPasswordMetrics.symbols = length;
3997                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
3998                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3999             }
4000         }
4001     }
4002
4003     @Override
4004     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
4005         if (!mHasFeature) {
4006             return 0;
4007         }
4008         enforceFullCrossUsersPermission(userHandle);
4009         synchronized (this) {
4010             int length = 0;
4011
4012             if (who != null) {
4013                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4014                 return admin != null ? admin.minimumPasswordMetrics.symbols : length;
4015             }
4016
4017             // Return the strictest policy across all participating admins.
4018             List<ActiveAdmin> admins =
4019                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4020             final int N = admins.size();
4021             for (int i = 0; i < N; i++) {
4022                 ActiveAdmin admin = admins.get(i);
4023                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
4024                     continue;
4025                 }
4026                 if (length < admin.minimumPasswordMetrics.symbols) {
4027                     length = admin.minimumPasswordMetrics.symbols;
4028                 }
4029             }
4030             return length;
4031         }
4032     }
4033
4034     @Override
4035     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
4036         if (!mHasFeature) {
4037             return;
4038         }
4039         Preconditions.checkNotNull(who, "ComponentName is null");
4040         synchronized (this) {
4041             ActiveAdmin ap = getActiveAdminForCallerLocked(
4042                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4043             if (ap.minimumPasswordMetrics.nonLetter != length) {
4044                 ap.minimumPasswordMetrics.nonLetter = length;
4045                 updatePasswordValidityCheckpointLocked(mInjector.userHandleGetCallingUserId());
4046                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4047             }
4048         }
4049     }
4050
4051     @Override
4052     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
4053         if (!mHasFeature) {
4054             return 0;
4055         }
4056         enforceFullCrossUsersPermission(userHandle);
4057         synchronized (this) {
4058             int length = 0;
4059
4060             if (who != null) {
4061                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4062                 return admin != null ? admin.minimumPasswordMetrics.nonLetter : length;
4063             }
4064
4065             // Return the strictest policy across all participating admins.
4066             List<ActiveAdmin> admins =
4067                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4068             final int N = admins.size();
4069             for (int i = 0; i < N; i++) {
4070                 ActiveAdmin admin = admins.get(i);
4071                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
4072                     continue;
4073                 }
4074                 if (length < admin.minimumPasswordMetrics.nonLetter) {
4075                     length = admin.minimumPasswordMetrics.nonLetter;
4076                 }
4077             }
4078             return length;
4079         }
4080     }
4081
4082     @Override
4083     public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
4084         if (!mHasFeature) {
4085             return true;
4086         }
4087         enforceFullCrossUsersPermission(userHandle);
4088
4089         synchronized (this) {
4090             // This API can only be called by an active device admin,
4091             // so try to retrieve it to check that the caller is one.
4092             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4093             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4094             return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
4095         }
4096     }
4097
4098     @Override
4099     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
4100         if (!mHasFeature) {
4101             return true;
4102         }
4103         enforceFullCrossUsersPermission(userHandle);
4104         enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
4105
4106         synchronized (this) {
4107             int targetUser = getProfileParentId(userHandle);
4108             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
4109             return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
4110         }
4111     }
4112
4113     private boolean isActivePasswordSufficientForUserLocked(
4114             DevicePolicyData policy, int userHandle, boolean parent) {
4115         enforceUserUnlocked(userHandle, parent);
4116
4117         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
4118                 && !policy.mPasswordStateHasBeenSetSinceBoot) {
4119             // Before user enters their password for the first time after a reboot, return the
4120             // value of this flag, which tells us whether the password was valid the last time
4121             // settings were saved.  If DPC changes password requirements on boot so that the
4122             // current password no longer meets the requirements, this value will be stale until
4123             // the next time the password is entered.
4124             return policy.mPasswordValidAtLastCheckpoint;
4125         }
4126
4127         final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
4128         if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) {
4129             return false;
4130         }
4131         if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
4132                 && policy.mActivePasswordMetrics.length < getPasswordMinimumLength(
4133                         null, userHandle, parent)) {
4134             return false;
4135         }
4136         if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4137             return true;
4138         }
4139         return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase(
4140                     null, userHandle, parent)
4141                 && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase(
4142                         null, userHandle, parent)
4143                 && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters(
4144                         null, userHandle, parent)
4145                 && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric(
4146                         null, userHandle, parent)
4147                 && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols(
4148                         null, userHandle, parent)
4149                 && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter(
4150                         null, userHandle, parent);
4151     }
4152
4153     @Override
4154     public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4155         enforceFullCrossUsersPermission(userHandle);
4156         synchronized (this) {
4157             if (!isCallerWithSystemUid()) {
4158                 // This API can only be called by an active device admin,
4159                 // so try to retrieve it to check that the caller is one.
4160                 getActiveAdminForCallerLocked(
4161                         null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4162             }
4163
4164             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4165
4166             return policy.mFailedPasswordAttempts;
4167         }
4168     }
4169
4170     @Override
4171     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4172         if (!mHasFeature) {
4173             return;
4174         }
4175         Preconditions.checkNotNull(who, "ComponentName is null");
4176         synchronized (this) {
4177             // This API can only be called by an active device admin,
4178             // so try to retrieve it to check that the caller is one.
4179             getActiveAdminForCallerLocked(
4180                     who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4181             ActiveAdmin ap = getActiveAdminForCallerLocked(
4182                     who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4183             if (ap.maximumFailedPasswordsForWipe != num) {
4184                 ap.maximumFailedPasswordsForWipe = num;
4185                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
4186             }
4187         }
4188     }
4189
4190     @Override
4191     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
4192         if (!mHasFeature) {
4193             return 0;
4194         }
4195         enforceFullCrossUsersPermission(userHandle);
4196         synchronized (this) {
4197             ActiveAdmin admin = (who != null)
4198                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
4199                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
4200             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
4201         }
4202     }
4203
4204     @Override
4205     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
4206         if (!mHasFeature) {
4207             return UserHandle.USER_NULL;
4208         }
4209         enforceFullCrossUsersPermission(userHandle);
4210         synchronized (this) {
4211             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4212                     userHandle, parent);
4213             return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
4214         }
4215     }
4216
4217     /**
4218      * Returns the admin with the strictest policy on maximum failed passwords for:
4219      * <ul>
4220      *   <li>this user if it has a separate profile challenge, or
4221      *   <li>this user and all profiles that don't have their own challenge otherwise.
4222      * </ul>
4223      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
4224      * the primary profile.
4225      * Returns {@code null} if no participating admin has that policy set.
4226      */
4227     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
4228             int userHandle, boolean parent) {
4229         int count = 0;
4230         ActiveAdmin strictestAdmin = null;
4231
4232         // Return the strictest policy across all participating admins.
4233         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4234         final int N = admins.size();
4235         for (int i = 0; i < N; i++) {
4236             ActiveAdmin admin = admins.get(i);
4237             if (admin.maximumFailedPasswordsForWipe ==
4238                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
4239                 continue;  // No max number of failed passwords policy set for this profile.
4240             }
4241
4242             // We always favor the primary profile if several profiles have the same value set.
4243             int userId = admin.getUserHandle().getIdentifier();
4244             if (count == 0 ||
4245                     count > admin.maximumFailedPasswordsForWipe ||
4246                     (count == admin.maximumFailedPasswordsForWipe &&
4247                             getUserInfo(userId).isPrimary())) {
4248                 count = admin.maximumFailedPasswordsForWipe;
4249                 strictestAdmin = admin;
4250             }
4251         }
4252         return strictestAdmin;
4253     }
4254
4255     private UserInfo getUserInfo(@UserIdInt int userId) {
4256         final long token = mInjector.binderClearCallingIdentity();
4257         try {
4258             return mUserManager.getUserInfo(userId);
4259         } finally {
4260             mInjector.binderRestoreCallingIdentity(token);
4261         }
4262     }
4263
4264     @Override
4265     public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
4266         final int callingUid = mInjector.binderGetCallingUid();
4267         final int userHandle = mInjector.userHandleGetCallingUserId();
4268
4269         String password = passwordOrNull != null ? passwordOrNull : "";
4270
4271         // Password resetting to empty/null is not allowed for managed profiles.
4272         if (TextUtils.isEmpty(password)) {
4273             enforceNotManagedProfile(userHandle, "clear the active password");
4274         }
4275
4276         synchronized (this) {
4277             // If caller has PO (or DO) it can change the password, so see if that's the case first.
4278             ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
4279                     null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
4280             final boolean preN;
4281             if (admin != null) {
4282                 final int targetSdk = getTargetSdk(admin.info.getPackageName(), userHandle);
4283                 if (targetSdk >= Build.VERSION_CODES.O) {
4284                     throw new SecurityException("resetPassword() is deprecated for DPC targeting O"
4285                             + " or later");
4286                 }
4287                 preN = targetSdk <= android.os.Build.VERSION_CODES.M;
4288             } else {
4289                 // Otherwise, make sure the caller has any active admin with the right policy.
4290                 admin = getActiveAdminForCallerLocked(null,
4291                         DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
4292                 preN = getTargetSdk(admin.info.getPackageName(),
4293                         userHandle) <= android.os.Build.VERSION_CODES.M;
4294
4295                 // As of N, password resetting to empty/null is not allowed anymore.
4296                 // TODO Should we allow DO/PO to set an empty password?
4297                 if (TextUtils.isEmpty(password)) {
4298                     if (!preN) {
4299                         throw new SecurityException("Cannot call with null password");
4300                     } else {
4301                         Slog.e(LOG_TAG, "Cannot call with null password");
4302                         return false;
4303                     }
4304                 }
4305                 // As of N, password cannot be changed by the admin if it is already set.
4306                 if (isLockScreenSecureUnchecked(userHandle)) {
4307                     if (!preN) {
4308                         throw new SecurityException("Admin cannot change current password");
4309                     } else {
4310                         Slog.e(LOG_TAG, "Admin cannot change current password");
4311                         return false;
4312                     }
4313                 }
4314             }
4315             // Do not allow to reset password when current user has a managed profile
4316             if (!isManagedProfile(userHandle)) {
4317                 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4318                     if (userInfo.isManagedProfile()) {
4319                         if (!preN) {
4320                             throw new IllegalStateException(
4321                                     "Cannot reset password on user has managed profile");
4322                         } else {
4323                             Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4324                             return false;
4325                         }
4326                     }
4327                 }
4328             }
4329             // Do not allow to reset password when user is locked
4330             if (!mUserManager.isUserUnlocked(userHandle)) {
4331                 if (!preN) {
4332                     throw new IllegalStateException("Cannot reset password when user is locked");
4333                 } else {
4334                     Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4335                     return false;
4336                 }
4337             }
4338         }
4339
4340         return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle);
4341     }
4342
4343     private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
4344             int flags, int callingUid, int userHandle) {
4345         int quality;
4346         synchronized (this) {
4347             quality = getPasswordQuality(null, userHandle, /* parent */ false);
4348             if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4349                 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4350             }
4351             final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
4352             if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
4353                 final int realQuality = metrics.quality;
4354                 if (realQuality < quality
4355                         && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4356                     Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4357                             + Integer.toHexString(realQuality)
4358                             + " does not meet required quality 0x"
4359                             + Integer.toHexString(quality));
4360                     return false;
4361                 }
4362                 quality = Math.max(realQuality, quality);
4363             }
4364             int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4365             if (password.length() < length) {
4366                 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4367                         + " does not meet required length " + length);
4368                 return false;
4369             }
4370             if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4371                 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4372                 if(metrics.letters < neededLetters) {
4373                     Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
4374                             + " does not meet required number of letters " + neededLetters);
4375                     return false;
4376                 }
4377                 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4378                 if (metrics.numeric < neededNumeric) {
4379                     Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
4380                             + " does not meet required number of numerical digits "
4381                             + neededNumeric);
4382                     return false;
4383                 }
4384                 int neededLowerCase = getPasswordMinimumLowerCase(
4385                         null, userHandle, /* parent */ false);
4386                 if (metrics.lowerCase < neededLowerCase) {
4387                     Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
4388                             + metrics.lowerCase
4389                             + " does not meet required number of lowercase letters "
4390                             + neededLowerCase);
4391                     return false;
4392                 }
4393                 int neededUpperCase = getPasswordMinimumUpperCase(
4394                         null, userHandle, /* parent */ false);
4395                 if (metrics.upperCase < neededUpperCase) {
4396                     Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
4397                             + metrics.upperCase
4398                             + " does not meet required number of uppercase letters "
4399                             + neededUpperCase);
4400                     return false;
4401                 }
4402                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4403                 if (metrics.symbols < neededSymbols) {
4404                     Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
4405                             + " does not meet required number of special symbols " + neededSymbols);
4406                     return false;
4407                 }
4408                 int neededNonLetter = getPasswordMinimumNonLetter(
4409                         null, userHandle, /* parent */ false);
4410                 if (metrics.nonLetter < neededNonLetter) {
4411                     Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
4412                             + metrics.nonLetter
4413                             + " does not meet required number of non-letter characters "
4414                             + neededNonLetter);
4415                     return false;
4416                 }
4417             }
4418         }
4419
4420         DevicePolicyData policy = getUserData(userHandle);
4421         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4422             Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4423             return false;
4424         }
4425
4426         boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4427         boolean doNotAskCredentialsOnBoot =
4428                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4429         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4430             setDoNotAskCredentialsOnBoot();
4431         }
4432
4433         // Don't do this with the lock held, because it is going to call
4434         // back in to the service.
4435         final long ident = mInjector.binderClearCallingIdentity();
4436         final boolean result;
4437         try {
4438             if (token == null) {
4439                 if (!TextUtils.isEmpty(password)) {
4440                     mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4441                 } else {
4442                     mLockPatternUtils.clearLock(null, userHandle);
4443                 }
4444                 result = true;
4445             } else {
4446                 result = mLockPatternUtils.setLockCredentialWithToken(password,
4447                         TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE
4448                                 : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
4449                         tokenHandle, token, userHandle);
4450             }
4451             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4452             if (requireEntry) {
4453                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4454                         UserHandle.USER_ALL);
4455             }
4456             synchronized (this) {
4457                 int newOwner = requireEntry ? callingUid : -1;
4458                 if (policy.mPasswordOwner != newOwner) {
4459                     policy.mPasswordOwner = newOwner;
4460                     saveSettingsLocked(userHandle);
4461                 }
4462             }
4463         } finally {
4464             mInjector.binderRestoreCallingIdentity(ident);
4465         }
4466         return result;
4467     }
4468
4469     private boolean isLockScreenSecureUnchecked(int userId) {
4470         long ident = mInjector.binderClearCallingIdentity();
4471         try {
4472             return mLockPatternUtils.isSecure(userId);
4473         } finally {
4474             mInjector.binderRestoreCallingIdentity(ident);
4475         }
4476     }
4477
4478     private void setDoNotAskCredentialsOnBoot() {
4479         synchronized (this) {
4480             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4481             if (!policyData.doNotAskCredentialsOnBoot) {
4482                 policyData.doNotAskCredentialsOnBoot = true;
4483                 saveSettingsLocked(UserHandle.USER_SYSTEM);
4484             }
4485         }
4486     }
4487
4488     @Override
4489     public boolean getDoNotAskCredentialsOnBoot() {
4490         mContext.enforceCallingOrSelfPermission(
4491                 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4492         synchronized (this) {
4493             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4494             return policyData.doNotAskCredentialsOnBoot;
4495         }
4496     }
4497
4498     @Override
4499     public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4500         if (!mHasFeature) {
4501             return;
4502         }
4503         Preconditions.checkNotNull(who, "ComponentName is null");
4504         final int userHandle = mInjector.userHandleGetCallingUserId();
4505         synchronized (this) {
4506             ActiveAdmin ap = getActiveAdminForCallerLocked(
4507                     who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4508             if (ap.maximumTimeToUnlock != timeMs) {
4509                 ap.maximumTimeToUnlock = timeMs;
4510                 saveSettingsLocked(userHandle);
4511                 updateMaximumTimeToLockLocked(userHandle);
4512             }
4513         }
4514     }
4515
4516     void updateMaximumTimeToLockLocked(int userHandle) {
4517         // Calculate the min timeout for all profiles - including the ones with a separate
4518         // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4519         // challenge only and keep the screen on. However there is no easy way of doing that at the
4520         // moment so we set the screen off timeout regardless of whether it affects the parent user
4521         // or the profile challenge only.
4522         long timeMs = Long.MAX_VALUE;
4523         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4524         for (int profileId : profileIds) {
4525             DevicePolicyData policy = getUserDataUnchecked(profileId);
4526             final int N = policy.mAdminList.size();
4527             for (int i = 0; i < N; i++) {
4528                 ActiveAdmin admin = policy.mAdminList.get(i);
4529                 if (admin.maximumTimeToUnlock > 0
4530                         && timeMs > admin.maximumTimeToUnlock) {
4531                     timeMs = admin.maximumTimeToUnlock;
4532                 }
4533                 // If userInfo.id is a managed profile, we also need to look at
4534                 // the policies set on the parent.
4535                 if (admin.hasParentActiveAdmin()) {
4536                     final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4537                     if (parentAdmin.maximumTimeToUnlock > 0
4538                             && timeMs > parentAdmin.maximumTimeToUnlock) {
4539                         timeMs = parentAdmin.maximumTimeToUnlock;
4540                     }
4541                 }
4542             }
4543         }
4544
4545         // We only store the last maximum time to lock on the parent profile. So if calling from a
4546         // managed profile, retrieve the policy for the parent.
4547         DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4548         if (policy.mLastMaximumTimeToLock == timeMs) {
4549             return;
4550         }
4551         policy.mLastMaximumTimeToLock = timeMs;
4552
4553         final long ident = mInjector.binderClearCallingIdentity();
4554         try {
4555             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4556                 // Make sure KEEP_SCREEN_ON is disabled, since that
4557                 // would allow bypassing of the maximum time to lock.
4558                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4559             }
4560
4561             mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4562                     (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4563         } finally {
4564             mInjector.binderRestoreCallingIdentity(ident);
4565         }
4566     }
4567
4568     @Override
4569     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4570         if (!mHasFeature) {
4571             return 0;
4572         }
4573         enforceFullCrossUsersPermission(userHandle);
4574         synchronized (this) {
4575             if (who != null) {
4576                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4577                 return admin != null ? admin.maximumTimeToUnlock : 0;
4578             }
4579             // Return the strictest policy across all participating admins.
4580             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4581                     userHandle, parent);
4582             return getMaximumTimeToLockPolicyFromAdmins(admins);
4583         }
4584     }
4585
4586     @Override
4587     public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4588         if (!mHasFeature) {
4589             return 0;
4590         }
4591         enforceFullCrossUsersPermission(userHandle);
4592         synchronized (this) {
4593             // All admins for this user.
4594             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4595             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4596                 DevicePolicyData policy = getUserData(userInfo.id);
4597                 admins.addAll(policy.mAdminList);
4598                 // If it is a managed profile, it may have parent active admins
4599                 if (userInfo.isManagedProfile()) {
4600                     for (ActiveAdmin admin : policy.mAdminList) {
4601                         if (admin.hasParentActiveAdmin()) {
4602                             admins.add(admin.getParentActiveAdmin());
4603                         }
4604                     }
4605                 }
4606             }
4607             return getMaximumTimeToLockPolicyFromAdmins(admins);
4608         }
4609     }
4610
4611     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4612         long time = 0;
4613         final int N = admins.size();
4614         for (int i = 0; i < N; i++) {
4615             ActiveAdmin admin = admins.get(i);
4616             if (time == 0) {
4617                 time = admin.maximumTimeToUnlock;
4618             } else if (admin.maximumTimeToUnlock != 0
4619                     && time > admin.maximumTimeToUnlock) {
4620                 time = admin.maximumTimeToUnlock;
4621             }
4622         }
4623         return time;
4624     }
4625
4626     @Override
4627     public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4628             boolean parent) {
4629         if (!mHasFeature) {
4630             return;
4631         }
4632         Preconditions.checkNotNull(who, "ComponentName is null");
4633         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4634         // timeoutMs with value 0 means that the admin doesn't participate
4635         // timeoutMs is clamped to the interval in case the internal constants change in the future
4636         final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
4637         if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
4638             timeoutMs = minimumStrongAuthTimeout;
4639         }
4640         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4641             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4642         }
4643
4644         final int userHandle = mInjector.userHandleGetCallingUserId();
4645         synchronized (this) {
4646             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4647                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4648             if (ap.strongAuthUnlockTimeout != timeoutMs) {
4649                 ap.strongAuthUnlockTimeout = timeoutMs;
4650                 saveSettingsLocked(userHandle);
4651             }
4652         }
4653     }
4654
4655     /**
4656      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4657      * admins if who is null.
4658      * Returns 0 if not configured for the provided admin.
4659      */
4660     @Override
4661     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4662         if (!mHasFeature) {
4663             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4664         }
4665         enforceFullCrossUsersPermission(userId);
4666         synchronized (this) {
4667             if (who != null) {
4668                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4669                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
4670             }
4671
4672             // Return the strictest policy across all participating admins.
4673             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4674
4675             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4676             for (int i = 0; i < admins.size(); i++) {
4677                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
4678                 if (timeout != 0) { // take only participating admins into account
4679                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4680                 }
4681             }
4682             return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
4683         }
4684     }
4685
4686     private long getMinimumStrongAuthTimeoutMs() {
4687         if (!mInjector.isBuildDebuggable()) {
4688             return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4689         }
4690         // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
4691         // name cannot be longer than 31 characters
4692         return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
4693                 MINIMUM_STRONG_AUTH_TIMEOUT_MS),
4694                 MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4695     }
4696
4697     @Override
4698     public void lockNow(int flags, boolean parent) {
4699         if (!mHasFeature) {
4700             return;
4701         }
4702
4703         final int callingUserId = mInjector.userHandleGetCallingUserId();
4704         synchronized (this) {
4705             // This API can only be called by an active device admin,
4706             // so try to retrieve it to check that the caller is one.
4707             final ActiveAdmin admin = getActiveAdminForCallerLocked(
4708                     null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4709
4710             final long ident = mInjector.binderClearCallingIdentity();
4711             try {
4712                 // Evict key
4713                 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
4714                     enforceManagedProfile(
4715                             callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
4716                     if (!isProfileOwner(admin.info.getComponent(), callingUserId)) {
4717                         throw new SecurityException("Only profile owner admins can set "
4718                                 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
4719                     }
4720                     if (parent) {
4721                         throw new IllegalArgumentException(
4722                                 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
4723                     }
4724                     if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
4725                         throw new UnsupportedOperationException(
4726                                 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices");
4727                     }
4728                     mUserManager.evictCredentialEncryptionKey(callingUserId);
4729                 }
4730
4731                 // Lock all users unless this is a managed profile with a separate challenge
4732                 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
4733                         ? UserHandle.USER_ALL : callingUserId);
4734                 mLockPatternUtils.requireStrongAuth(
4735                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4736
4737                 // Require authentication for the device or profile
4738                 if (userToLock == UserHandle.USER_ALL) {
4739                     // Power off the display
4740                     mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4741                             PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4742                     mInjector.getIWindowManager().lockNow(null);
4743                 } else {
4744                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4745                 }
4746             } catch (RemoteException e) {
4747             } finally {
4748                 mInjector.binderRestoreCallingIdentity(ident);
4749             }
4750         }
4751     }
4752
4753     @Override
4754     public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
4755         if (who == null) {
4756             if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
4757                 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4758             }
4759         } else {
4760             enforceProfileOrDeviceOwner(who);
4761         }
4762     }
4763
4764     private void enforceProfileOrDeviceOwner(ComponentName who) {
4765         synchronized (this) {
4766             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4767         }
4768     }
4769
4770     @Override
4771     public boolean approveCaCert(String alias, int userId, boolean approval) {
4772         enforceManageUsers();
4773         synchronized (this) {
4774             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4775             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4776             if (!changed) {
4777                 return false;
4778             }
4779             saveSettingsLocked(userId);
4780         }
4781         mCertificateMonitor.onCertificateApprovalsChanged(userId);
4782         return true;
4783     }
4784
4785     @Override
4786     public boolean isCaCertApproved(String alias, int userId) {
4787         enforceManageUsers();
4788         synchronized (this) {
4789             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4790         }
4791     }
4792
4793     private void removeCaApprovalsIfNeeded(int userId) {
4794         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4795             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4796             if (userInfo.isManagedProfile()){
4797                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4798             }
4799             if (!isSecure) {
4800                 synchronized (this) {
4801                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4802                     saveSettingsLocked(userInfo.id);
4803                 }
4804                 mCertificateMonitor.onCertificateApprovalsChanged(userId);
4805             }
4806         }
4807     }
4808
4809     @Override
4810     public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)
4811             throws RemoteException {
4812         if (!mHasFeature) {
4813             return false;
4814         }
4815         enforceCanManageCaCerts(admin, callerPackage);
4816
4817         final String alias;
4818
4819         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
4820         final long id = mInjector.binderClearCallingIdentity();
4821         try {
4822             alias = mCertificateMonitor.installCaCert(userHandle, certBuffer);
4823             if (alias == null) {
4824                 Log.w(LOG_TAG, "Problem installing cert");
4825                 return false;
4826             }
4827         } finally {
4828             mInjector.binderRestoreCallingIdentity(id);
4829         }
4830
4831         synchronized (this) {
4832             getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias);
4833             saveSettingsLocked(userHandle.getIdentifier());
4834         }
4835         return true;
4836     }
4837
4838     @Override
4839     public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
4840         if (!mHasFeature) {
4841             return;
4842         }
4843         enforceCanManageCaCerts(admin, callerPackage);
4844
4845         final int userId = mInjector.userHandleGetCallingUserId();
4846         final long id = mInjector.binderClearCallingIdentity();
4847         try {
4848             mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases);
4849         } finally {
4850             mInjector.binderRestoreCallingIdentity(id);
4851         }
4852
4853         synchronized (this) {
4854             if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) {
4855                 saveSettingsLocked(userId);
4856             }
4857         }
4858     }
4859
4860     @Override
4861     public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
4862             byte[] cert, byte[] chain, String alias, boolean requestAccess) {
4863         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4864                 DELEGATION_CERT_INSTALL);
4865
4866
4867         final int callingUid = mInjector.binderGetCallingUid();
4868         final long id = mInjector.binderClearCallingIdentity();
4869         try {
4870             final KeyChainConnection keyChainConnection =
4871                     KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4872             try {
4873                 IKeyChainService keyChain = keyChainConnection.getService();
4874                 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4875                     return false;
4876                 }
4877                 if (requestAccess) {
4878                     keyChain.setGrant(callingUid, alias, true);
4879                 }
4880                 return true;
4881             } catch (RemoteException e) {
4882                 Log.e(LOG_TAG, "Installing certificate", e);
4883             } finally {
4884                 keyChainConnection.close();
4885             }
4886         } catch (InterruptedException e) {
4887             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4888             Thread.currentThread().interrupt();
4889         } finally {
4890             mInjector.binderRestoreCallingIdentity(id);
4891         }
4892         return false;
4893     }
4894
4895     @Override
4896     public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
4897         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
4898                 DELEGATION_CERT_INSTALL);
4899
4900         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4901         final long id = Binder.clearCallingIdentity();
4902         try {
4903             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4904             try {
4905                 IKeyChainService keyChain = keyChainConnection.getService();
4906                 return keyChain.removeKeyPair(alias);
4907             } catch (RemoteException e) {
4908                 Log.e(LOG_TAG, "Removing keypair", e);
4909             } finally {
4910                 keyChainConnection.close();
4911             }
4912         } catch (InterruptedException e) {
4913             Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4914             Thread.currentThread().interrupt();
4915         } finally {
4916             Binder.restoreCallingIdentity(id);
4917         }
4918         return false;
4919     }
4920
4921     @Override
4922     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4923             final IBinder response) {
4924         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4925         if (!isCallerWithSystemUid()) {
4926             return;
4927         }
4928
4929         final UserHandle caller = mInjector.binderGetCallingUserHandle();
4930         // If there is a profile owner, redirect to that; otherwise query the device owner.
4931         ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4932         if (aliasChooser == null && caller.isSystem()) {
4933             ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4934             if (deviceOwnerAdmin != null) {
4935                 aliasChooser = deviceOwnerAdmin.info.getComponent();
4936             }
4937         }
4938         if (aliasChooser == null) {
4939             sendPrivateKeyAliasResponse(null, response);
4940             return;
4941         }
4942
4943         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4944         intent.setComponent(aliasChooser);
4945         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4946         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4947         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4948         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4949         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4950
4951         final long id = mInjector.binderClearCallingIdentity();
4952         try {
4953             mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4954                 @Override
4955                 public void onReceive(Context context, Intent intent) {
4956                     final String chosenAlias = getResultData();
4957                     sendPrivateKeyAliasResponse(chosenAlias, response);
4958                 }
4959             }, null, Activity.RESULT_OK, null, null);
4960         } finally {
4961             mInjector.binderRestoreCallingIdentity(id);
4962         }
4963     }
4964
4965     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4966         final IKeyChainAliasCallback keyChainAliasResponse =
4967                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4968         // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
4969         // is oneway, which means it won't block if the recipient lives in another process.
4970         try {
4971             keyChainAliasResponse.alias(alias);
4972         } catch (Exception e) {
4973             // Caller could throw RuntimeException or RemoteException back across processes. Catch
4974             // everything just to be sure.
4975             Log.e(LOG_TAG, "error while responding to callback", e);
4976         }
4977     }
4978
4979     /**
4980      * Determine whether DPMS should check if a delegate package is already installed before
4981      * granting it new delegations via {@link #setDelegatedScopes}.
4982      */
4983     private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
4984             int targetSdk, List<String> scopes) {
4985         // 1) Never skip is installed check from N.
4986         if (targetSdk >= Build.VERSION_CODES.N) {
4987             return true;
4988         }
4989         // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
4990         if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
4991             return false;
4992         }
4993         // 3) Skip if all previously granted scopes are being cleared.
4994         if (scopes.isEmpty()) {
4995             return false;
4996         }
4997         // Otherwise it should check that delegatePackage is installed.
4998         return true;
4999     }
5000
5001     /**
5002      * Set the scopes of a device owner or profile owner delegate.
5003      *
5004      * @param who the device owner or profile owner.
5005      * @param delegatePackage the name of the delegate package.
5006      * @param scopes the list of delegation scopes to be given to the delegate package.
5007      */
5008     @Override
5009     public void setDelegatedScopes(ComponentName who, String delegatePackage,
5010             List<String> scopes) throws SecurityException {
5011         Preconditions.checkNotNull(who, "ComponentName is null");
5012         Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
5013         Preconditions.checkCollectionElementsNotNull(scopes, "Scopes");
5014         // Remove possible duplicates.
5015         scopes = new ArrayList(new ArraySet(scopes));
5016         // Ensure given scopes are valid.
5017         if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
5018             throw new IllegalArgumentException("Unexpected delegation scopes");
5019         }
5020
5021         // Retrieve the user ID of the calling process.
5022         final int userId = mInjector.userHandleGetCallingUserId();
5023         synchronized (this) {
5024             // Ensure calling process is device/profile owner.
5025             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5026             // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
5027             if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
5028                         getTargetSdk(who.getPackageName(), userId), scopes)) {
5029                 // Throw when the delegate package is not installed.
5030                 if (!isPackageInstalledForUser(delegatePackage, userId)) {
5031                     throw new IllegalArgumentException("Package " + delegatePackage
5032                             + " is not installed on the current user");
5033                 }
5034             }
5035
5036             // Set the new delegate in user policies.
5037             final DevicePolicyData policy = getUserData(userId);
5038             if (!scopes.isEmpty()) {
5039                 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
5040             } else {
5041                 // Remove any delegation info if the given scopes list is empty.
5042                 policy.mDelegationMap.remove(delegatePackage);
5043             }
5044
5045             // Notify delegate package of updates.
5046             final Intent intent = new Intent(
5047                     DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
5048             // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
5049             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
5050             // Limit components this intent resolves to to the delegate package.
5051             intent.setPackage(delegatePackage);
5052             // Include the list of delegated scopes as an extra.
5053             intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES,
5054                     (ArrayList<String>) scopes);
5055             // Send the broadcast.
5056             mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
5057
5058             // Persist updates.
5059             saveSettingsLocked(userId);
5060         }
5061     }
5062
5063     /**
5064      * Get the delegation scopes given to a delegate package by a device owner or profile owner.
5065      *
5066      * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
5067      * passing in {@code null} as the {@code who} parameter and its own name as the
5068      * {@code delegatepackage}.
5069      *
5070      * @param who the device owner or profile owner, or {@code null} if the caller is
5071      *            {@code delegatePackage}.
5072      * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
5073      * @return a list of the delegation scopes currently given to {@code delegatePackage}.
5074      */
5075     @Override
5076     @NonNull
5077     public List<String> getDelegatedScopes(ComponentName who,
5078             String delegatePackage) throws SecurityException {
5079         Preconditions.checkNotNull(delegatePackage, "Delegate package is null");
5080
5081         // Retrieve the user ID of the calling process.
5082         final int callingUid = mInjector.binderGetCallingUid();
5083         final int userId = UserHandle.getUserId(callingUid);
5084         synchronized (this) {
5085             // Ensure calling process is device/profile owner.
5086             if (who != null) {
5087                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5088             // Or ensure calling process is delegatePackage itself.
5089             } else {
5090                 int uid = 0;
5091                 try {
5092                   uid = mInjector.getPackageManager()
5093                           .getPackageUidAsUser(delegatePackage, userId);
5094                 } catch(NameNotFoundException e) {
5095                 }
5096                 if (uid != callingUid) {
5097                     throw new SecurityException("Caller with uid " + callingUid + " is not "
5098                             + delegatePackage);
5099                 }
5100             }
5101             final DevicePolicyData policy = getUserData(userId);
5102             // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
5103             final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5104             return scopes == null ? Collections.EMPTY_LIST : scopes;
5105         }
5106     }
5107
5108     /**
5109      * Get a list of  packages that were given a specific delegation scopes by a device owner or
5110      * profile owner.
5111      *
5112      * @param who the device owner or profile owner.
5113      * @param scope the scope whose delegates are to be retrieved.
5114      * @return a list of the delegate packages currently given the {@code scope} delegation.
5115      */
5116     @NonNull
5117     public List<String> getDelegatePackages(ComponentName who, String scope)
5118             throws SecurityException {
5119         Preconditions.checkNotNull(who, "ComponentName is null");
5120         Preconditions.checkNotNull(scope, "Scope is null");
5121         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5122             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5123         }
5124
5125         // Retrieve the user ID of the calling process.
5126         final int userId = mInjector.userHandleGetCallingUserId();
5127         synchronized (this) {
5128             // Ensure calling process is device/profile owner.
5129             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5130             final DevicePolicyData policy = getUserData(userId);
5131
5132             // Create a list to hold the resulting delegate packages.
5133             final List<String> delegatePackagesWithScope = new ArrayList<>();
5134             // Add all delegations containing scope to the result list.
5135             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5136                 if (policy.mDelegationMap.valueAt(i).contains(scope)) {
5137                     delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
5138                 }
5139             }
5140             return delegatePackagesWithScope;
5141         }
5142     }
5143
5144     /**
5145      * Check whether a caller application has been delegated a given scope via
5146      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
5147      * device owner.
5148      * <p>
5149      * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
5150      * then comparing the calling UID with the UID of {@code callerPackage} as reported by
5151      * {@link PackageManager#getPackageUidAsUser}.
5152      *
5153      * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
5154      * @param scope the delegation scope to be checked.
5155      * @return {@code true} if the calling process is a delegate of {@code scope}.
5156      */
5157     private boolean isCallerDelegate(String callerPackage, String scope) {
5158         Preconditions.checkNotNull(callerPackage, "callerPackage is null");
5159         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5160             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5161         }
5162
5163         // Retrieve the UID and user ID of the calling process.
5164         final int callingUid = mInjector.binderGetCallingUid();
5165         final int userId = UserHandle.getUserId(callingUid);
5166         synchronized (this) {
5167             // Retrieve user policy data.
5168             final DevicePolicyData policy = getUserData(userId);
5169             // Retrieve the list of delegation scopes granted to callerPackage.
5170             final List<String> scopes = policy.mDelegationMap.get(callerPackage);
5171             // Check callingUid only if callerPackage has the required scope delegation.
5172             if (scopes != null && scopes.contains(scope)) {
5173                 try {
5174                     // Retrieve the expected UID for callerPackage.
5175                     final int uid = mInjector.getPackageManager()
5176                             .getPackageUidAsUser(callerPackage, userId);
5177                     // Return true if the caller is actually callerPackage.
5178                     return uid == callingUid;
5179                 } catch (NameNotFoundException e) {
5180                     // Ignore.
5181                 }
5182             }
5183             return false;
5184         }
5185     }
5186
5187     /**
5188      * Throw a security exception if a ComponentName is given and it is not a device/profile owner
5189      * or if the calling process is not a delegate of the given scope.
5190      *
5191      * @param who the device owner of profile owner, or null if {@code callerPackage} is a
5192      *            {@code scope} delegate.
5193      * @param callerPackage the name of the calling package. Required if {@code who} is
5194      *            {@code null}.
5195      * @param reqPolicy the policy used in the API whose access permission is being checked.
5196      * @param scope the delegation scope corresponding to the API being checked.
5197      * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy};
5198      *            or when {@code who} is {@code null} and {@code callerPackage} is not a delegate
5199      *            of {@code scope}.
5200      */
5201     private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy,
5202             String scope) {
5203         // If a ComponentName is given ensure it is a device or profile owner according to policy.
5204         if (who != null) {
5205             synchronized (this) {
5206                 getActiveAdminForCallerLocked(who, reqPolicy);
5207             }
5208         // If no ComponentName is given ensure calling process has scope delegation.
5209         } else if (!isCallerDelegate(callerPackage, scope)) {
5210             throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid()
5211                     + " is not a delegate of scope " + scope + ".");
5212         }
5213     }
5214
5215     /**
5216      * Helper function to preserve delegation behavior pre-O when using the deprecated functions
5217      * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
5218      */
5219     private void setDelegatedScopePreO(ComponentName who,
5220             String delegatePackage, String scope) {
5221         Preconditions.checkNotNull(who, "ComponentName is null");
5222
5223         final int userId = mInjector.userHandleGetCallingUserId();
5224         synchronized(this) {
5225             // Ensure calling process is device/profile owner.
5226             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5227             final DevicePolicyData policy = getUserData(userId);
5228
5229             if (delegatePackage != null) {
5230                 // Set package as a delegate for scope if it is not already one.
5231                 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5232                 if (scopes == null) {
5233                     scopes = new ArrayList<>();
5234                 }
5235                 if (!scopes.contains(scope)) {
5236                     scopes.add(scope);
5237                     setDelegatedScopes(who, delegatePackage, scopes);
5238                 }
5239             }
5240
5241             // Clear any existing scope delegates.
5242             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5243                 final String currentPackage = policy.mDelegationMap.keyAt(i);
5244                 final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
5245
5246                 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
5247                     final List<String> newScopes = new ArrayList(currentScopes);
5248                     newScopes.remove(scope);
5249                     setDelegatedScopes(who, currentPackage, newScopes);
5250                 }
5251             }
5252         }
5253     }
5254
5255     @Override
5256     public void setCertInstallerPackage(ComponentName who, String installerPackage)
5257             throws SecurityException {
5258         setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
5259     }
5260
5261     @Override
5262     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
5263         final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
5264         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
5265     }
5266
5267     /**
5268      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
5269      * not installed and therefore not available.
5270      *
5271      * @throws SecurityException if the caller is not a profile or device owner.
5272      * @throws UnsupportedOperationException if the package does not support being set as always-on.
5273      */
5274     @Override
5275     public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
5276             throws SecurityException {
5277         enforceProfileOrDeviceOwner(admin);
5278
5279         final int userId = mInjector.userHandleGetCallingUserId();
5280         final long token = mInjector.binderClearCallingIdentity();
5281         try {
5282             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
5283                 return false;
5284             }
5285             ConnectivityManager connectivityManager = (ConnectivityManager)
5286                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5287             if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
5288                 throw new UnsupportedOperationException();
5289             }
5290         } finally {
5291             mInjector.binderRestoreCallingIdentity(token);
5292         }
5293         return true;
5294     }
5295
5296     @Override
5297     public String getAlwaysOnVpnPackage(ComponentName admin)
5298             throws SecurityException {
5299         enforceProfileOrDeviceOwner(admin);
5300
5301         final int userId = mInjector.userHandleGetCallingUserId();
5302         final long token = mInjector.binderClearCallingIdentity();
5303         try{
5304             ConnectivityManager connectivityManager = (ConnectivityManager)
5305                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5306             return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
5307         } finally {
5308             mInjector.binderRestoreCallingIdentity(token);
5309         }
5310     }
5311
5312     private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) {
5313         wtfIfInLock();
5314
5315         if (wipeExtRequested) {
5316             StorageManager sm = (StorageManager) mContext.getSystemService(
5317                     Context.STORAGE_SERVICE);
5318             sm.wipeAdoptableDisks();
5319         }
5320         try {
5321             mInjector.recoverySystemRebootWipeUserData(
5322                     /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc);
5323         } catch (IOException | SecurityException e) {
5324             Slog.w(LOG_TAG, "Failed requesting data wipe", e);
5325         }
5326     }
5327
5328     private void forceWipeUser(int userId) {
5329         try {
5330             IActivityManager am = mInjector.getIActivityManager();
5331             if (am.getCurrentUser().id == userId) {
5332                 am.switchUser(UserHandle.USER_SYSTEM);
5333             }
5334
5335             boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
5336             if (!userRemoved) {
5337                 Slog.w(LOG_TAG, "Couldn't remove user " + userId);
5338             } else if (isManagedProfile(userId)) {
5339                 sendWipeProfileNotification();
5340             }
5341         } catch (RemoteException re) {
5342             // Shouldn't happen
5343         }
5344     }
5345
5346     @Override
5347     public void wipeData(int flags) {
5348         if (!mHasFeature) {
5349             return;
5350         }
5351         enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId());
5352
5353         final ActiveAdmin admin;
5354         synchronized (this) {
5355             admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA);
5356         }
5357         String reason = "DevicePolicyManager.wipeData() from "
5358                 + admin.info.getComponent().flattenToShortString();
5359         wipeDataNoLock(
5360                 admin.info.getComponent(), flags, reason, admin.getUserHandle().getIdentifier());
5361     }
5362
5363     private void wipeDataNoLock(ComponentName admin, int flags, String reason, int userId) {
5364         wtfIfInLock();
5365
5366         long ident = mInjector.binderClearCallingIdentity();
5367         try {
5368             // First check whether the admin is allowed to wipe the device/user/profile.
5369             final String restriction;
5370             if (userId == UserHandle.USER_SYSTEM) {
5371                 restriction = UserManager.DISALLOW_FACTORY_RESET;
5372             } else if (isManagedProfile(userId)) {
5373                 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
5374             } else {
5375                 restriction = UserManager.DISALLOW_REMOVE_USER;
5376             }
5377             if (isAdminAffectedByRestriction(admin, restriction, userId)) {
5378                 throw new SecurityException("Cannot wipe data. " + restriction
5379                         + " restriction is set for user " + userId);
5380             }
5381
5382             if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
5383                 if (!isDeviceOwner(admin, userId)) {
5384                     throw new SecurityException(
5385                             "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
5386                 }
5387                 PersistentDataBlockManager manager = (PersistentDataBlockManager)
5388                         mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
5389                 if (manager != null) {
5390                     manager.wipe();
5391                 }
5392             }
5393
5394             // TODO If split user is enabled and the device owner is set in the primary user
5395             // (rather than system), we should probably trigger factory reset. Current code just
5396             // removes that user (but still clears FRP...)
5397             if (userId == UserHandle.USER_SYSTEM) {
5398                 forceWipeDeviceNoLock(/*wipeExtRequested=*/ (flags & WIPE_EXTERNAL_STORAGE) != 0,
5399                         reason, /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0);
5400             } else {
5401                 forceWipeUser(userId);
5402             }
5403         } finally {
5404             mInjector.binderRestoreCallingIdentity(ident);
5405         }
5406     }
5407
5408     private void sendWipeProfileNotification() {
5409         String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
5410         Notification notification =
5411                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
5412                         .setSmallIcon(android.R.drawable.stat_sys_warning)
5413                         .setContentTitle(mContext.getString(R.string.work_profile_deleted))
5414                         .setContentText(contentText)
5415                         .setColor(mContext.getColor(R.color.system_notification_accent_color))
5416                         .setStyle(new Notification.BigTextStyle().bigText(contentText))
5417                         .build();
5418         mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification);
5419     }
5420
5421     private void clearWipeProfileNotification() {
5422         mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
5423     }
5424
5425     @Override
5426     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
5427         if (!mHasFeature) {
5428             return;
5429         }
5430         enforceFullCrossUsersPermission(userHandle);
5431         mContext.enforceCallingOrSelfPermission(
5432                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5433
5434         synchronized (this) {
5435             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
5436             if (admin == null) {
5437                 result.sendResult(null);
5438                 return;
5439             }
5440             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
5441             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
5442             intent.setComponent(admin.info.getComponent());
5443             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
5444                     null, new BroadcastReceiver() {
5445                 @Override
5446                 public void onReceive(Context context, Intent intent) {
5447                     result.sendResult(getResultExtras(false));
5448                 }
5449             }, null, Activity.RESULT_OK, null, null);
5450         }
5451     }
5452
5453     @Override
5454     public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
5455         if (!mHasFeature) {
5456             return;
5457         }
5458         enforceFullCrossUsersPermission(userHandle);
5459         mContext.enforceCallingOrSelfPermission(
5460                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5461
5462         // If the managed profile doesn't have a separate password, set the metrics to default
5463         if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
5464             metrics = new PasswordMetrics();
5465         }
5466
5467         validateQualityConstant(metrics.quality);
5468         DevicePolicyData policy = getUserData(userHandle);
5469         synchronized (this) {
5470             policy.mActivePasswordMetrics = metrics;
5471             policy.mPasswordStateHasBeenSetSinceBoot = true;
5472         }
5473     }
5474
5475     @Override
5476     public void reportPasswordChanged(@UserIdInt int userId) {
5477         if (!mHasFeature) {
5478             return;
5479         }
5480         enforceFullCrossUsersPermission(userId);
5481
5482         // Managed Profile password can only be changed when it has a separate challenge.
5483         if (!isSeparateProfileChallengeEnabled(userId)) {
5484             enforceNotManagedProfile(userId, "set the active password");
5485         }
5486
5487         mContext.enforceCallingOrSelfPermission(
5488                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5489
5490         DevicePolicyData policy = getUserData(userId);
5491
5492         long ident = mInjector.binderClearCallingIdentity();
5493         try {
5494             synchronized (this) {
5495                 policy.mFailedPasswordAttempts = 0;
5496                 updatePasswordValidityCheckpointLocked(userId);
5497                 saveSettingsLocked(userId);
5498                 updatePasswordExpirationsLocked(userId);
5499                 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
5500
5501                 // Send a broadcast to each profile using this password as its primary unlock.
5502                 sendAdminCommandForLockscreenPoliciesLocked(
5503                         DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
5504                         DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
5505             }
5506             removeCaApprovalsIfNeeded(userId);
5507         } finally {
5508             mInjector.binderRestoreCallingIdentity(ident);
5509         }
5510     }
5511
5512     /**
5513      * Called any time the device password is updated. Resets all password expiration clocks.
5514      */
5515     private void updatePasswordExpirationsLocked(int userHandle) {
5516         ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
5517         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5518                 userHandle, /* parent */ false);
5519         final int N = admins.size();
5520         for (int i = 0; i < N; i++) {
5521             ActiveAdmin admin = admins.get(i);
5522             if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
5523                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
5524                 long timeout = admin.passwordExpirationTimeout;
5525                 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
5526                 admin.passwordExpirationDate = expiration;
5527             }
5528         }
5529         for (int affectedUserId : affectedUserIds) {
5530             saveSettingsLocked(affectedUserId);
5531         }
5532     }
5533
5534     @Override
5535     public void reportFailedPasswordAttempt(int userHandle) {
5536         enforceFullCrossUsersPermission(userHandle);
5537         if (!isSeparateProfileChallengeEnabled(userHandle)) {
5538             enforceNotManagedProfile(userHandle,
5539                     "report failed password attempt if separate profile challenge is not in place");
5540         }
5541         mContext.enforceCallingOrSelfPermission(
5542                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5543
5544         boolean wipeData = false;
5545         ActiveAdmin strictestAdmin = null;
5546         final long ident = mInjector.binderClearCallingIdentity();
5547         try {
5548             synchronized (this) {
5549                 DevicePolicyData policy = getUserData(userHandle);
5550                 policy.mFailedPasswordAttempts++;
5551                 saveSettingsLocked(userHandle);
5552                 if (mHasFeature) {
5553                     strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
5554                             userHandle, /* parent */ false);
5555                     int max = strictestAdmin != null
5556                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
5557                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
5558                         wipeData = true;
5559                     }
5560
5561                     sendAdminCommandForLockscreenPoliciesLocked(
5562                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
5563                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5564                 }
5565             }
5566         } finally {
5567             mInjector.binderRestoreCallingIdentity(ident);
5568         }
5569
5570         if (wipeData && strictestAdmin != null) {
5571             final int userId = strictestAdmin.getUserHandle().getIdentifier();
5572             Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
5573                     + strictestAdmin.info.getComponent().flattenToShortString()
5574                     + ". Calling wipeData for user " + userId);
5575
5576             // Attempt to wipe the device/user/profile associated with the admin, as if the
5577             // admin had called wipeData(). That way we can check whether the admin is actually
5578             // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
5579             // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
5580             // able to do so).
5581             // IMPORTANT: Call without holding the lock to prevent deadlock.
5582             try {
5583                 wipeDataNoLock(strictestAdmin.info.getComponent(),
5584                         /*flags=*/ 0,
5585                         /*reason=*/ "reportFailedPasswordAttempt()",
5586                         userId);
5587             } catch (SecurityException e) {
5588                 Slog.w(LOG_TAG, "Failed to wipe user " + userId
5589                         + " after max failed password attempts reached.", e);
5590             }
5591         }
5592
5593         if (mInjector.securityLogIsLoggingEnabled()) {
5594             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5595                     /*method strength*/ 1);
5596         }
5597     }
5598
5599     @Override
5600     public void reportSuccessfulPasswordAttempt(int userHandle) {
5601         enforceFullCrossUsersPermission(userHandle);
5602         mContext.enforceCallingOrSelfPermission(
5603                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5604
5605         synchronized (this) {
5606             DevicePolicyData policy = getUserData(userHandle);
5607             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
5608                 long ident = mInjector.binderClearCallingIdentity();
5609                 try {
5610                     policy.mFailedPasswordAttempts = 0;
5611                     policy.mPasswordOwner = -1;
5612                     saveSettingsLocked(userHandle);
5613                     if (mHasFeature) {
5614                         sendAdminCommandForLockscreenPoliciesLocked(
5615                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
5616                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5617                     }
5618                 } finally {
5619                     mInjector.binderRestoreCallingIdentity(ident);
5620                 }
5621             }
5622         }
5623
5624         if (mInjector.securityLogIsLoggingEnabled()) {
5625             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5626                     /*method strength*/ 1);
5627         }
5628     }
5629
5630     @Override
5631     public void reportFailedFingerprintAttempt(int userHandle) {
5632         enforceFullCrossUsersPermission(userHandle);
5633         mContext.enforceCallingOrSelfPermission(
5634                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5635         if (mInjector.securityLogIsLoggingEnabled()) {
5636             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5637                     /*method strength*/ 0);
5638         }
5639     }
5640
5641     @Override
5642     public void reportSuccessfulFingerprintAttempt(int userHandle) {
5643         enforceFullCrossUsersPermission(userHandle);
5644         mContext.enforceCallingOrSelfPermission(
5645                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5646         if (mInjector.securityLogIsLoggingEnabled()) {
5647             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5648                     /*method strength*/ 0);
5649         }
5650     }
5651
5652     @Override
5653     public void reportKeyguardDismissed(int userHandle) {
5654         enforceFullCrossUsersPermission(userHandle);
5655         mContext.enforceCallingOrSelfPermission(
5656                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5657
5658         if (mInjector.securityLogIsLoggingEnabled()) {
5659             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5660         }
5661     }
5662
5663     @Override
5664     public void reportKeyguardSecured(int userHandle) {
5665         enforceFullCrossUsersPermission(userHandle);
5666         mContext.enforceCallingOrSelfPermission(
5667                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5668
5669         if (mInjector.securityLogIsLoggingEnabled()) {
5670             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5671         }
5672     }
5673
5674     @Override
5675     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5676             String exclusionList) {
5677         if (!mHasFeature) {
5678             return null;
5679         }
5680         synchronized(this) {
5681             Preconditions.checkNotNull(who, "ComponentName is null");
5682
5683             // Only check if system user has set global proxy. We don't allow other users to set it.
5684             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5685             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5686                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5687
5688             // Scan through active admins and find if anyone has already
5689             // set the global proxy.
5690             Set<ComponentName> compSet = policy.mAdminMap.keySet();
5691             for (ComponentName component : compSet) {
5692                 ActiveAdmin ap = policy.mAdminMap.get(component);
5693                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5694                     // Another admin already sets the global proxy
5695                     // Return it to the caller.
5696                     return component;
5697                 }
5698             }
5699
5700             // If the user is not system, don't set the global proxy. Fail silently.
5701             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5702                 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5703                         + UserHandle.getCallingUserId() + " is not permitted.");
5704                 return null;
5705             }
5706             if (proxySpec == null) {
5707                 admin.specifiesGlobalProxy = false;
5708                 admin.globalProxySpec = null;
5709                 admin.globalProxyExclusionList = null;
5710             } else {
5711
5712                 admin.specifiesGlobalProxy = true;
5713                 admin.globalProxySpec = proxySpec;
5714                 admin.globalProxyExclusionList = exclusionList;
5715             }
5716
5717             // Reset the global proxy accordingly
5718             // Do this using system permissions, as apps cannot write to secure settings
5719             long origId = mInjector.binderClearCallingIdentity();
5720             try {
5721                 resetGlobalProxyLocked(policy);
5722             } finally {
5723                 mInjector.binderRestoreCallingIdentity(origId);
5724             }
5725             return null;
5726         }
5727     }
5728
5729     @Override
5730     public ComponentName getGlobalProxyAdmin(int userHandle) {
5731         if (!mHasFeature) {
5732             return null;
5733         }
5734         enforceFullCrossUsersPermission(userHandle);
5735         synchronized(this) {
5736             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5737             // Scan through active admins and find if anyone has already
5738             // set the global proxy.
5739             final int N = policy.mAdminList.size();
5740             for (int i = 0; i < N; i++) {
5741                 ActiveAdmin ap = policy.mAdminList.get(i);
5742                 if (ap.specifiesGlobalProxy) {
5743                     // Device admin sets the global proxy
5744                     // Return it to the caller.
5745                     return ap.info.getComponent();
5746                 }
5747             }
5748         }
5749         // No device admin sets the global proxy.
5750         return null;
5751     }
5752
5753     @Override
5754     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5755         synchronized (this) {
5756             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5757         }
5758         long token = mInjector.binderClearCallingIdentity();
5759         try {
5760             ConnectivityManager connectivityManager = (ConnectivityManager)
5761                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5762             connectivityManager.setGlobalProxy(proxyInfo);
5763         } finally {
5764             mInjector.binderRestoreCallingIdentity(token);
5765         }
5766     }
5767
5768     private void resetGlobalProxyLocked(DevicePolicyData policy) {
5769         final int N = policy.mAdminList.size();
5770         for (int i = 0; i < N; i++) {
5771             ActiveAdmin ap = policy.mAdminList.get(i);
5772             if (ap.specifiesGlobalProxy) {
5773                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5774                 return;
5775             }
5776         }
5777         // No device admins defining global proxies - reset global proxy settings to none
5778         saveGlobalProxyLocked(null, null);
5779     }
5780
5781     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5782         if (exclusionList == null) {
5783             exclusionList = "";
5784         }
5785         if (proxySpec == null) {
5786             proxySpec = "";
5787         }
5788         // Remove white spaces
5789         proxySpec = proxySpec.trim();
5790         String data[] = proxySpec.split(":");
5791         int proxyPort = 8080;
5792         if (data.length > 1) {
5793             try {
5794                 proxyPort = Integer.parseInt(data[1]);
5795             } catch (NumberFormatException e) {}
5796         }
5797         exclusionList = exclusionList.trim();
5798
5799         ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5800         if (!proxyProperties.isValid()) {
5801             Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5802             return;
5803         }
5804         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5805         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5806         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5807                 exclusionList);
5808     }
5809
5810     /**
5811      * Set the storage encryption request for a single admin.  Returns the new total request
5812      * status (for all admins).
5813      */
5814     @Override
5815     public int setStorageEncryption(ComponentName who, boolean encrypt) {
5816         if (!mHasFeature) {
5817             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5818         }
5819         Preconditions.checkNotNull(who, "ComponentName is null");
5820         final int userHandle = UserHandle.getCallingUserId();
5821         synchronized (this) {
5822             // Check for permissions
5823             // Only system user can set storage encryption
5824             if (userHandle != UserHandle.USER_SYSTEM) {
5825                 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5826                         + UserHandle.getCallingUserId() + " is not permitted.");
5827                 return 0;
5828             }
5829
5830             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5831                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5832
5833             // Quick exit:  If the filesystem does not support encryption, we can exit early.
5834             if (!isEncryptionSupported()) {
5835                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5836             }
5837
5838             // (1) Record the value for the admin so it's sticky
5839             if (ap.encryptionRequested != encrypt) {
5840                 ap.encryptionRequested = encrypt;
5841                 saveSettingsLocked(userHandle);
5842             }
5843
5844             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5845             // (2) Compute "max" for all admins
5846             boolean newRequested = false;
5847             final int N = policy.mAdminList.size();
5848             for (int i = 0; i < N; i++) {
5849                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5850             }
5851
5852             // Notify OS of new request
5853             setEncryptionRequested(newRequested);
5854
5855             // Return the new global request status
5856             return newRequested
5857                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5858                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5859         }
5860     }
5861
5862     /**
5863      * Get the current storage encryption request status for a given admin, or aggregate of all
5864      * active admins.
5865      */
5866     @Override
5867     public boolean getStorageEncryption(ComponentName who, int userHandle) {
5868         if (!mHasFeature) {
5869             return false;
5870         }
5871         enforceFullCrossUsersPermission(userHandle);
5872         synchronized (this) {
5873             // Check for permissions if a particular caller is specified
5874             if (who != null) {
5875                 // When checking for a single caller, status is based on caller's request
5876                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5877                 return ap != null ? ap.encryptionRequested : false;
5878             }
5879
5880             // If no particular caller is specified, return the aggregate set of requests.
5881             // This is short circuited by returning true on the first hit.
5882             DevicePolicyData policy = getUserData(userHandle);
5883             final int N = policy.mAdminList.size();
5884             for (int i = 0; i < N; i++) {
5885                 if (policy.mAdminList.get(i).encryptionRequested) {
5886                     return true;
5887                 }
5888             }
5889             return false;
5890         }
5891     }
5892
5893     /**
5894      * Get the current encryption status of the device.
5895      */
5896     @Override
5897     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5898         if (!mHasFeature) {
5899             // Ok to return current status.
5900         }
5901         enforceFullCrossUsersPermission(userHandle);
5902
5903         // It's not critical here, but let's make sure the package name is correct, in case
5904         // we start using it for different purposes.
5905         ensureCallerPackage(callerPackage);
5906
5907         final ApplicationInfo ai;
5908         try {
5909             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5910         } catch (RemoteException e) {
5911             throw new SecurityException(e);
5912         }
5913
5914         boolean legacyApp = false;
5915         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5916             legacyApp = true;
5917         }
5918
5919         final int rawStatus = getEncryptionStatus();
5920         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5921             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5922         }
5923         return rawStatus;
5924     }
5925
5926     /**
5927      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
5928      */
5929     private boolean isEncryptionSupported() {
5930         // Note, this can be implemented as
5931         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5932         // But is provided as a separate internal method if there's a faster way to do a
5933         // simple check for supported-or-not.
5934         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5935     }
5936
5937     /**
5938      * Hook to low-levels:  Reporting the current status of encryption.
5939      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5940      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5941      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5942      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5943      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5944      */
5945     private int getEncryptionStatus() {
5946         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5947             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5948         } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5949             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5950         } else if (mInjector.storageManagerIsEncrypted()) {
5951             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5952         } else if (mInjector.storageManagerIsEncryptable()) {
5953             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5954         } else {
5955             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5956         }
5957     }
5958
5959     /**
5960      * Hook to low-levels:  If needed, record the new admin setting for encryption.
5961      */
5962     private void setEncryptionRequested(boolean encrypt) {
5963     }
5964
5965     /**
5966      * Set whether the screen capture is disabled for the user managed by the specified admin.
5967      */
5968     @Override
5969     public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5970         if (!mHasFeature) {
5971             return;
5972         }
5973         Preconditions.checkNotNull(who, "ComponentName is null");
5974         final int userHandle = UserHandle.getCallingUserId();
5975         synchronized (this) {
5976             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5977                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5978             if (ap.disableScreenCapture != disabled) {
5979                 ap.disableScreenCapture = disabled;
5980                 saveSettingsLocked(userHandle);
5981                 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5982             }
5983         }
5984     }
5985
5986     /**
5987      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5988      * active admin (if given admin is null).
5989      */
5990     @Override
5991     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5992         if (!mHasFeature) {
5993             return false;
5994         }
5995         synchronized (this) {
5996             if (who != null) {
5997                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5998                 return (admin != null) ? admin.disableScreenCapture : false;
5999             }
6000
6001             DevicePolicyData policy = getUserData(userHandle);
6002             final int N = policy.mAdminList.size();
6003             for (int i = 0; i < N; i++) {
6004                 ActiveAdmin admin = policy.mAdminList.get(i);
6005                 if (admin.disableScreenCapture) {
6006                     return true;
6007                 }
6008             }
6009             return false;
6010         }
6011     }
6012
6013     private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
6014             final boolean disabled) {
6015         mHandler.post(new Runnable() {
6016             @Override
6017             public void run() {
6018                 try {
6019                     mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
6020                 } catch (RemoteException e) {
6021                     Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
6022                 }
6023             }
6024         });
6025     }
6026
6027     /**
6028      * Set whether auto time is required by the specified admin (must be device or profile owner).
6029      */
6030     @Override
6031     public void setAutoTimeRequired(ComponentName who, boolean required) {
6032         if (!mHasFeature) {
6033             return;
6034         }
6035         Preconditions.checkNotNull(who, "ComponentName is null");
6036         final int userHandle = UserHandle.getCallingUserId();
6037         synchronized (this) {
6038             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6039                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6040             if (admin.requireAutoTime != required) {
6041                 admin.requireAutoTime = required;
6042                 saveSettingsLocked(userHandle);
6043             }
6044         }
6045
6046         // Turn AUTO_TIME on in settings if it is required
6047         if (required) {
6048             long ident = mInjector.binderClearCallingIdentity();
6049             try {
6050                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
6051             } finally {
6052                 mInjector.binderRestoreCallingIdentity(ident);
6053             }
6054         }
6055     }
6056
6057     /**
6058      * Returns whether or not auto time is required by the device owner or any profile owner.
6059      */
6060     @Override
6061     public boolean getAutoTimeRequired() {
6062         if (!mHasFeature) {
6063             return false;
6064         }
6065         synchronized (this) {
6066             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6067             if (deviceOwner != null && deviceOwner.requireAutoTime) {
6068                 // If the device owner enforces auto time, we don't need to check the PO's
6069                 return true;
6070             }
6071
6072             // Now check to see if any profile owner on any user enforces auto time
6073             for (Integer userId : mOwners.getProfileOwnerKeys()) {
6074                 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
6075                 if (profileOwner != null && profileOwner.requireAutoTime) {
6076                     return true;
6077                 }
6078             }
6079
6080             return false;
6081         }
6082     }
6083
6084     @Override
6085     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
6086         if (!mHasFeature) {
6087             return;
6088         }
6089         Preconditions.checkNotNull(who, "ComponentName is null");
6090         // Allow setting this policy to true only if there is a split system user.
6091         if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
6092             throw new UnsupportedOperationException(
6093                     "Cannot force ephemeral users on systems without split system user.");
6094         }
6095         boolean removeAllUsers = false;
6096         synchronized (this) {
6097             final ActiveAdmin deviceOwner =
6098                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6099             if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
6100                 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
6101                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
6102                 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
6103                 removeAllUsers = forceEphemeralUsers;
6104             }
6105         }
6106         if (removeAllUsers) {
6107             long identitity = mInjector.binderClearCallingIdentity();
6108             try {
6109                 mUserManagerInternal.removeAllUsers();
6110             } finally {
6111                 mInjector.binderRestoreCallingIdentity(identitity);
6112             }
6113         }
6114     }
6115
6116     @Override
6117     public boolean getForceEphemeralUsers(ComponentName who) {
6118         if (!mHasFeature) {
6119             return false;
6120         }
6121         Preconditions.checkNotNull(who, "ComponentName is null");
6122         synchronized (this) {
6123             final ActiveAdmin deviceOwner =
6124                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6125             return deviceOwner.forceEphemeralUsers;
6126         }
6127     }
6128
6129     private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException {
6130         synchronized (this) {
6131             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6132             if (!areAllUsersAffiliatedWithDeviceLocked()) {
6133                 throw new SecurityException("Not all users are affiliated.");
6134             }
6135         }
6136     }
6137
6138     @Override
6139     public boolean requestBugreport(ComponentName who) {
6140         if (!mHasFeature) {
6141             return false;
6142         }
6143         Preconditions.checkNotNull(who, "ComponentName is null");
6144
6145         // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
6146         // which could still contain data related to that user. Should we disallow that, e.g. until
6147         // next boot? Might not be needed given that this still requires user consent.
6148         ensureDeviceOwnerAndAllUsersAffiliated(who);
6149
6150         if (mRemoteBugreportServiceIsActive.get()
6151                 || (getDeviceOwnerRemoteBugreportUri() != null)) {
6152             Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
6153             return false;
6154         }
6155
6156         final long currentTime = System.currentTimeMillis();
6157         synchronized (this) {
6158             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6159             if (currentTime > policyData.mLastBugReportRequestTime) {
6160                 policyData.mLastBugReportRequestTime = currentTime;
6161                 saveSettingsLocked(UserHandle.USER_SYSTEM);
6162             }
6163         }
6164
6165         final long callingIdentity = mInjector.binderClearCallingIdentity();
6166         try {
6167             mInjector.getIActivityManager().requestBugReport(
6168                     ActivityManager.BUGREPORT_OPTION_REMOTE);
6169
6170             mRemoteBugreportServiceIsActive.set(true);
6171             mRemoteBugreportSharingAccepted.set(false);
6172             registerRemoteBugreportReceivers();
6173             mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
6174                     RemoteBugreportUtils.NOTIFICATION_ID,
6175                     RemoteBugreportUtils.buildNotification(mContext,
6176                             DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
6177             mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
6178                     RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
6179             return true;
6180         } catch (RemoteException re) {
6181             // should never happen
6182             Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
6183             return false;
6184         } finally {
6185             mInjector.binderRestoreCallingIdentity(callingIdentity);
6186         }
6187     }
6188
6189     synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
6190         Intent intent = new Intent(action);
6191         intent.setComponent(mOwners.getDeviceOwnerComponent());
6192         if (extras != null) {
6193             intent.putExtras(extras);
6194         }
6195         mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6196     }
6197
6198     private synchronized String getDeviceOwnerRemoteBugreportUri() {
6199         return mOwners.getDeviceOwnerRemoteBugreportUri();
6200     }
6201
6202     private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
6203             String bugreportHash) {
6204         mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
6205     }
6206
6207     private void registerRemoteBugreportReceivers() {
6208         try {
6209             IntentFilter filterFinished = new IntentFilter(
6210                     DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
6211                     RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6212             mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
6213         } catch (IntentFilter.MalformedMimeTypeException e) {
6214             // should never happen, as setting a constant
6215             Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
6216         }
6217         IntentFilter filterConsent = new IntentFilter();
6218         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
6219         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
6220         mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
6221     }
6222
6223     private void onBugreportFinished(Intent intent) {
6224         mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6225         mRemoteBugreportServiceIsActive.set(false);
6226         Uri bugreportUri = intent.getData();
6227         String bugreportUriString = null;
6228         if (bugreportUri != null) {
6229             bugreportUriString = bugreportUri.toString();
6230         }
6231         String bugreportHash = intent.getStringExtra(
6232                 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
6233         if (mRemoteBugreportSharingAccepted.get()) {
6234             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6235             mInjector.getNotificationManager().cancel(LOG_TAG,
6236                     RemoteBugreportUtils.NOTIFICATION_ID);
6237         } else {
6238             setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
6239             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6240                     RemoteBugreportUtils.buildNotification(mContext,
6241                             DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
6242                             UserHandle.ALL);
6243         }
6244         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6245     }
6246
6247     private void onBugreportFailed() {
6248         mRemoteBugreportServiceIsActive.set(false);
6249         mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6250                 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6251         mRemoteBugreportSharingAccepted.set(false);
6252         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6253         mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
6254         Bundle extras = new Bundle();
6255         extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6256                 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
6257         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6258         mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
6259         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6260     }
6261
6262     private void onBugreportSharingAccepted() {
6263         mRemoteBugreportSharingAccepted.set(true);
6264         String bugreportUriString = null;
6265         String bugreportHash = null;
6266         synchronized (this) {
6267             bugreportUriString = getDeviceOwnerRemoteBugreportUri();
6268             bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
6269         }
6270         if (bugreportUriString != null) {
6271             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6272         } else if (mRemoteBugreportServiceIsActive.get()) {
6273             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6274                     RemoteBugreportUtils.buildNotification(mContext,
6275                             DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
6276                             UserHandle.ALL);
6277         }
6278     }
6279
6280     private void onBugreportSharingDeclined() {
6281         if (mRemoteBugreportServiceIsActive.get()) {
6282             mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6283                     RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6284             mRemoteBugreportServiceIsActive.set(false);
6285             mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6286             mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6287         }
6288         mRemoteBugreportSharingAccepted.set(false);
6289         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6290         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
6291     }
6292
6293     private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
6294             String bugreportHash) {
6295         ParcelFileDescriptor pfd = null;
6296         try {
6297             if (bugreportUriString == null) {
6298                 throw new FileNotFoundException();
6299             }
6300             Uri bugreportUri = Uri.parse(bugreportUriString);
6301             pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
6302
6303             synchronized (this) {
6304                 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
6305                 intent.setComponent(mOwners.getDeviceOwnerComponent());
6306                 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6307                 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
6308                 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6309
6310                 LocalServices.getService(ActivityManagerInternal.class)
6311                         .grantUriPermissionFromIntent(Process.SHELL_UID,
6312                                 mOwners.getDeviceOwnerComponent().getPackageName(),
6313                                 intent, mOwners.getDeviceOwnerUserId());
6314                 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6315             }
6316         } catch (FileNotFoundException e) {
6317             Bundle extras = new Bundle();
6318             extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6319                     DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
6320             sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6321         } finally {
6322             try {
6323                 if (pfd != null) {
6324                     pfd.close();
6325                 }
6326             } catch (IOException ex) {
6327                 // Ignore
6328             }
6329             mRemoteBugreportSharingAccepted.set(false);
6330             setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6331         }
6332     }
6333
6334     /**
6335      * Disables all device cameras according to the specified admin.
6336      */
6337     @Override
6338     public void setCameraDisabled(ComponentName who, boolean disabled) {
6339         if (!mHasFeature) {
6340             return;
6341         }
6342         Preconditions.checkNotNull(who, "ComponentName is null");
6343         final int userHandle = mInjector.userHandleGetCallingUserId();
6344         synchronized (this) {
6345             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6346                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
6347             if (ap.disableCamera != disabled) {
6348                 ap.disableCamera = disabled;
6349                 saveSettingsLocked(userHandle);
6350             }
6351         }
6352         // Tell the user manager that the restrictions have changed.
6353         pushUserRestrictions(userHandle);
6354     }
6355
6356     /**
6357      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
6358      * active admins.
6359      */
6360     @Override
6361     public boolean getCameraDisabled(ComponentName who, int userHandle) {
6362         return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
6363     }
6364
6365     private boolean getCameraDisabled(ComponentName who, int userHandle,
6366             boolean mergeDeviceOwnerRestriction) {
6367         if (!mHasFeature) {
6368             return false;
6369         }
6370         synchronized (this) {
6371             if (who != null) {
6372                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6373                 return (admin != null) ? admin.disableCamera : false;
6374             }
6375             // First, see if DO has set it.  If so, it's device-wide.
6376             if (mergeDeviceOwnerRestriction) {
6377                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6378                 if (deviceOwner != null && deviceOwner.disableCamera) {
6379                     return true;
6380                 }
6381             }
6382
6383             // Then check each device admin on the user.
6384             DevicePolicyData policy = getUserData(userHandle);
6385             // Determine whether or not the device camera is disabled for any active admins.
6386             final int N = policy.mAdminList.size();
6387             for (int i = 0; i < N; i++) {
6388                 ActiveAdmin admin = policy.mAdminList.get(i);
6389                 if (admin.disableCamera) {
6390                     return true;
6391                 }
6392             }
6393             return false;
6394         }
6395     }
6396
6397     @Override
6398     public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
6399         if (!mHasFeature) {
6400             return;
6401         }
6402         Preconditions.checkNotNull(who, "ComponentName is null");
6403         final int userHandle = mInjector.userHandleGetCallingUserId();
6404         if (isManagedProfile(userHandle)) {
6405             if (parent) {
6406                 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
6407             } else {
6408                 which = which & PROFILE_KEYGUARD_FEATURES;
6409             }
6410         }
6411         synchronized (this) {
6412             ActiveAdmin ap = getActiveAdminForCallerLocked(
6413                     who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6414             if (ap.disabledKeyguardFeatures != which) {
6415                 ap.disabledKeyguardFeatures = which;
6416                 saveSettingsLocked(userHandle);
6417             }
6418         }
6419     }
6420
6421     /**
6422      * Gets the disabled state for features in keyguard for the given admin,
6423      * or the aggregate of all active admins if who is null.
6424      */
6425     @Override
6426     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
6427         if (!mHasFeature) {
6428             return 0;
6429         }
6430         enforceFullCrossUsersPermission(userHandle);
6431         final long ident = mInjector.binderClearCallingIdentity();
6432         try {
6433             synchronized (this) {
6434                 if (who != null) {
6435                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
6436                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
6437                 }
6438
6439                 final List<ActiveAdmin> admins;
6440                 if (!parent && isManagedProfile(userHandle)) {
6441                     // If we are being asked about a managed profile, just return keyguard features
6442                     // disabled by admins in the profile.
6443                     admins = getUserDataUnchecked(userHandle).mAdminList;
6444                 } else {
6445                     // Otherwise return those set by admins in the user and its profiles.
6446                     admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6447                 }
6448
6449                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
6450                 final int N = admins.size();
6451                 for (int i = 0; i < N; i++) {
6452                     ActiveAdmin admin = admins.get(i);
6453                     int userId = admin.getUserHandle().getIdentifier();
6454                     boolean isRequestedUser = !parent && (userId == userHandle);
6455                     if (isRequestedUser || !isManagedProfile(userId)) {
6456                         // If we are being asked explicitly about this user
6457                         // return all disabled features even if its a managed profile.
6458                         which |= admin.disabledKeyguardFeatures;
6459                     } else {
6460                         // Otherwise a managed profile is only allowed to disable
6461                         // some features on the parent user.
6462                         which |= (admin.disabledKeyguardFeatures
6463                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
6464                     }
6465                 }
6466                 return which;
6467             }
6468         } finally {
6469             mInjector.binderRestoreCallingIdentity(ident);
6470         }
6471     }
6472
6473     @Override
6474     public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
6475             List<String> packageList) {
6476         if (!mHasFeature) {
6477             return;
6478         }
6479         Preconditions.checkNotNull(packageList, "packageList is null");
6480         final int userHandle = UserHandle.getCallingUserId();
6481         synchronized (this) {
6482             // Ensure the caller is a DO or a keep uninstalled packages delegate.
6483             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6484                     DELEGATION_KEEP_UNINSTALLED_PACKAGES);
6485             // Get the device owner
6486             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6487             // Set list of packages to be kept even if uninstalled.
6488             deviceOwner.keepUninstalledPackages = packageList;
6489             // Save settings.
6490             saveSettingsLocked(userHandle);
6491             // Notify package manager.
6492             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
6493         }
6494     }
6495
6496     @Override
6497     public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
6498         if (!mHasFeature) {
6499             return null;
6500         }
6501         // TODO In split system user mode, allow apps on user 0 to query the list
6502         synchronized (this) {
6503             // Ensure the caller is a DO or a keep uninstalled packages delegate.
6504             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6505                     DELEGATION_KEEP_UNINSTALLED_PACKAGES);
6506             return getKeepUninstalledPackagesLocked();
6507         }
6508     }
6509
6510     private List<String> getKeepUninstalledPackagesLocked() {
6511         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6512         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
6513     }
6514
6515     @Override
6516     public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
6517         if (!mHasFeature) {
6518             return false;
6519         }
6520         if (admin == null
6521                 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
6522             throw new IllegalArgumentException("Invalid component " + admin
6523                     + " for device owner");
6524         }
6525         final boolean hasIncompatibleAccountsOrNonAdb =
6526                 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
6527         synchronized (this) {
6528             enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
6529             final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
6530             if (activeAdmin == null
6531                     || getUserData(userId).mRemovingAdmins.contains(admin)) {
6532                 throw new IllegalArgumentException("Not active admin: " + admin);
6533             }
6534
6535             // Shutting down backup manager service permanently.
6536             long ident = mInjector.binderClearCallingIdentity();
6537             try {
6538                 if (mInjector.getIBackupManager() != null) {
6539                     mInjector.getIBackupManager()
6540                             .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
6541                 }
6542             } catch (RemoteException e) {
6543                 throw new IllegalStateException("Failed deactivating backup service.", e);
6544             } finally {
6545                 mInjector.binderRestoreCallingIdentity(ident);
6546             }
6547
6548             if (isAdb()) {
6549                 // Log device owner provisioning was started using adb.
6550                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
6551             }
6552
6553             mOwners.setDeviceOwner(admin, ownerName, userId);
6554             mOwners.writeDeviceOwner();
6555             updateDeviceOwnerLocked();
6556             setDeviceOwnerSystemPropertyLocked();
6557
6558             final Set<String> restrictions =
6559                     UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
6560             if (!restrictions.isEmpty()) {
6561                 for (String restriction : restrictions) {
6562                     activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
6563                 }
6564                 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
6565                 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
6566
6567                 saveUserRestrictionsLocked(userId);
6568             }
6569
6570             ident = mInjector.binderClearCallingIdentity();
6571             try {
6572                 // TODO Send to system too?
6573                 mContext.sendBroadcastAsUser(
6574                         new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED)
6575                                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND),
6576                         UserHandle.of(userId));
6577             } finally {
6578                 mInjector.binderRestoreCallingIdentity(ident);
6579             }
6580             mDeviceAdminServiceController.startServiceForOwner(
6581                     admin.getPackageName(), userId, "set-device-owner");
6582
6583             Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
6584             return true;
6585         }
6586     }
6587
6588     @Override
6589     public boolean hasDeviceOwner() {
6590         enforceDeviceOwnerOrManageUsers();
6591         return mOwners.hasDeviceOwner();
6592     }
6593
6594     boolean isDeviceOwner(ActiveAdmin admin) {
6595         return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
6596     }
6597
6598     public boolean isDeviceOwner(ComponentName who, int userId) {
6599         synchronized (this) {
6600             return mOwners.hasDeviceOwner()
6601                     && mOwners.getDeviceOwnerUserId() == userId
6602                     && mOwners.getDeviceOwnerComponent().equals(who);
6603         }
6604     }
6605
6606     private boolean isDeviceOwnerPackage(String packageName, int userId) {
6607         synchronized (this) {
6608             return mOwners.hasDeviceOwner()
6609                     && mOwners.getDeviceOwnerUserId() == userId
6610                     && mOwners.getDeviceOwnerPackageName().equals(packageName);
6611         }
6612     }
6613
6614     private boolean isProfileOwnerPackage(String packageName, int userId) {
6615         synchronized (this) {
6616             return mOwners.hasProfileOwner(userId)
6617                     && mOwners.getProfileOwnerPackage(userId).equals(packageName);
6618         }
6619     }
6620
6621     public boolean isProfileOwner(ComponentName who, int userId) {
6622         final ComponentName profileOwner = getProfileOwner(userId);
6623         return who != null && who.equals(profileOwner);
6624     }
6625
6626     @Override
6627     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
6628         if (!mHasFeature) {
6629             return null;
6630         }
6631         if (!callingUserOnly) {
6632             enforceManageUsers();
6633         }
6634         synchronized (this) {
6635             if (!mOwners.hasDeviceOwner()) {
6636                 return null;
6637             }
6638             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
6639                     mOwners.getDeviceOwnerUserId()) {
6640                 return null;
6641             }
6642             return mOwners.getDeviceOwnerComponent();
6643         }
6644     }
6645
6646     @Override
6647     public int getDeviceOwnerUserId() {
6648         if (!mHasFeature) {
6649             return UserHandle.USER_NULL;
6650         }
6651         enforceManageUsers();
6652         synchronized (this) {
6653             return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
6654         }
6655     }
6656
6657     /**
6658      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
6659      * MANAGE_USERS.
6660      */
6661     @Override
6662     public String getDeviceOwnerName() {
6663         if (!mHasFeature) {
6664             return null;
6665         }
6666         enforceManageUsers();
6667         synchronized (this) {
6668             if (!mOwners.hasDeviceOwner()) {
6669                 return null;
6670             }
6671             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
6672             // Should setDeviceOwner/ProfileOwner still take a name?
6673             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
6674             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
6675         }
6676     }
6677
6678     /** Returns the active device owner or {@code null} if there is no device owner. */
6679     @VisibleForTesting
6680     ActiveAdmin getDeviceOwnerAdminLocked() {
6681         ComponentName component = mOwners.getDeviceOwnerComponent();
6682         if (component == null) {
6683             return null;
6684         }
6685
6686         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
6687         final int n = policy.mAdminList.size();
6688         for (int i = 0; i < n; i++) {
6689             ActiveAdmin admin = policy.mAdminList.get(i);
6690             if (component.equals(admin.info.getComponent())) {
6691                 return admin;
6692             }
6693         }
6694         Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6695         return null;
6696     }
6697
6698     @Override
6699     public void clearDeviceOwner(String packageName) {
6700         Preconditions.checkNotNull(packageName, "packageName is null");
6701         final int callingUid = mInjector.binderGetCallingUid();
6702         try {
6703             int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
6704                     UserHandle.getUserId(callingUid));
6705             if (uid != callingUid) {
6706                 throw new SecurityException("Invalid packageName");
6707             }
6708         } catch (NameNotFoundException e) {
6709             throw new SecurityException(e);
6710         }
6711         synchronized (this) {
6712             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6713             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6714             if (!mOwners.hasDeviceOwner()
6715                     || !deviceOwnerComponent.getPackageName().equals(packageName)
6716                     || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6717                 throw new SecurityException(
6718                         "clearDeviceOwner can only be called by the device owner");
6719             }
6720             enforceUserUnlocked(deviceOwnerUserId);
6721
6722             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6723             long ident = mInjector.binderClearCallingIdentity();
6724             try {
6725                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6726                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6727                 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
6728                 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
6729                 mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId));
6730             } finally {
6731                 mInjector.binderRestoreCallingIdentity(ident);
6732             }
6733             Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6734         }
6735     }
6736
6737     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6738         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
6739
6740         if (admin != null) {
6741             admin.disableCamera = false;
6742             admin.userRestrictions = null;
6743             admin.defaultEnabledRestrictionsAlreadySet.clear();
6744             admin.forceEphemeralUsers = false;
6745             admin.isNetworkLoggingEnabled = false;
6746             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6747         }
6748         final DevicePolicyData policyData = getUserData(userId);
6749         policyData.mCurrentInputMethodSet = false;
6750         saveSettingsLocked(userId);
6751         final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
6752         systemPolicyData.mLastSecurityLogRetrievalTime = -1;
6753         systemPolicyData.mLastBugReportRequestTime = -1;
6754         systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
6755         saveSettingsLocked(UserHandle.USER_SYSTEM);
6756         clearUserPoliciesLocked(userId);
6757
6758         mOwners.clearDeviceOwner();
6759         mOwners.writeDeviceOwner();
6760         updateDeviceOwnerLocked();
6761
6762         clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId));
6763         mInjector.securityLogSetLoggingEnabledProperty(false);
6764         mSecurityLogMonitor.stop();
6765         setNetworkLoggingActiveInternal(false);
6766
6767         try {
6768             if (mInjector.getIBackupManager() != null) {
6769                 // Reactivate backup service.
6770                 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6771             }
6772         } catch (RemoteException e) {
6773             throw new IllegalStateException("Failed reactivating backup service.", e);
6774         }
6775     }
6776
6777     @Override
6778     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6779         if (!mHasFeature) {
6780             return false;
6781         }
6782         if (who == null
6783                 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6784             throw new IllegalArgumentException("Component " + who
6785                     + " not installed for userId:" + userHandle);
6786         }
6787         final boolean hasIncompatibleAccountsOrNonAdb =
6788                 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
6789         synchronized (this) {
6790             enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
6791
6792             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6793             if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6794                 throw new IllegalArgumentException("Not active admin: " + who);
6795             }
6796
6797             if (isAdb()) {
6798                 // Log profile owner provisioning was started using adb.
6799                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
6800             }
6801
6802             mOwners.setProfileOwner(who, ownerName, userHandle);
6803             mOwners.writeProfileOwner(userHandle);
6804             Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6805
6806             final long id = mInjector.binderClearCallingIdentity();
6807             try {
6808                 if (mUserManager.isManagedProfile(userHandle)) {
6809                     maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin,
6810                             UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
6811                     ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
6812                             true /* newOwner */);
6813                 }
6814             } finally {
6815                 mInjector.binderRestoreCallingIdentity(id);
6816             }
6817             mDeviceAdminServiceController.startServiceForOwner(
6818                     who.getPackageName(), userHandle, "set-profile-owner");
6819             return true;
6820         }
6821     }
6822
6823     @Override
6824     public void clearProfileOwner(ComponentName who) {
6825         if (!mHasFeature) {
6826             return;
6827         }
6828         Preconditions.checkNotNull(who, "ComponentName is null");
6829
6830         final int userId = mInjector.userHandleGetCallingUserId();
6831         enforceNotManagedProfile(userId, "clear profile owner");
6832         enforceUserUnlocked(userId);
6833         synchronized (this) {
6834             // Check if this is the profile owner who is calling
6835             final ActiveAdmin admin =
6836                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6837
6838             final long ident = mInjector.binderClearCallingIdentity();
6839             try {
6840                 clearProfileOwnerLocked(admin, userId);
6841                 removeActiveAdminLocked(who, userId);
6842             } finally {
6843                 mInjector.binderRestoreCallingIdentity(ident);
6844             }
6845             Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6846         }
6847     }
6848
6849     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6850         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner");
6851
6852         if (admin != null) {
6853             admin.disableCamera = false;
6854             admin.userRestrictions = null;
6855             admin.defaultEnabledRestrictionsAlreadySet.clear();
6856         }
6857         final DevicePolicyData policyData = getUserData(userId);
6858         policyData.mCurrentInputMethodSet = false;
6859         policyData.mOwnerInstalledCaCerts.clear();
6860         saveSettingsLocked(userId);
6861         clearUserPoliciesLocked(userId);
6862         mOwners.removeProfileOwner(userId);
6863         mOwners.writeProfileOwner(userId);
6864     }
6865
6866     @Override
6867     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6868         Preconditions.checkNotNull(who, "ComponentName is null");
6869         if (!mHasFeature) {
6870             return;
6871         }
6872
6873         synchronized (this) {
6874             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6875             long token = mInjector.binderClearCallingIdentity();
6876             try {
6877                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6878             } finally {
6879                 mInjector.binderRestoreCallingIdentity(token);
6880             }
6881         }
6882     }
6883
6884     @Override
6885     public CharSequence getDeviceOwnerLockScreenInfo() {
6886         return mLockPatternUtils.getDeviceOwnerInfo();
6887     }
6888
6889     private void clearUserPoliciesLocked(int userId) {
6890         // Reset some of the user-specific policies.
6891         final DevicePolicyData policy = getUserData(userId);
6892         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6893         // Clear delegations.
6894         policy.mDelegationMap.clear();
6895         policy.mStatusBarDisabled = false;
6896         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6897         policy.mAffiliationIds.clear();
6898         policy.mLockTaskPackages.clear();
6899         saveSettingsLocked(userId);
6900
6901         try {
6902             mIPackageManager.updatePermissionFlagsForAllApps(
6903                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6904                     0  /* flagValues */, userId);
6905             pushUserRestrictions(userId);
6906         } catch (RemoteException re) {
6907             // Shouldn't happen.
6908         }
6909     }
6910
6911     @Override
6912     public boolean hasUserSetupCompleted() {
6913         return hasUserSetupCompleted(UserHandle.getCallingUserId());
6914     }
6915
6916     // This checks only if the Setup Wizard has run.  Since Wear devices pair before
6917     // completing Setup Wizard, and pairing involves transferring user data, calling
6918     // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6919     private boolean hasUserSetupCompleted(int userHandle) {
6920         if (!mHasFeature) {
6921             return true;
6922         }
6923         return getUserData(userHandle).mUserSetupComplete;
6924     }
6925
6926     private boolean hasPaired(int userHandle) {
6927         if (!mHasFeature) {
6928             return true;
6929         }
6930         return getUserData(userHandle).mPaired;
6931     }
6932
6933     @Override
6934     public int getUserProvisioningState() {
6935         if (!mHasFeature) {
6936             return DevicePolicyManager.STATE_USER_UNMANAGED;
6937         }
6938         int userHandle = mInjector.userHandleGetCallingUserId();
6939         return getUserProvisioningState(userHandle);
6940     }
6941
6942     private int getUserProvisioningState(int userHandle) {
6943         return getUserData(userHandle).mUserProvisioningState;
6944     }
6945
6946     @Override
6947     public void setUserProvisioningState(int newState, int userHandle) {
6948         if (!mHasFeature) {
6949             return;
6950         }
6951
6952         if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6953                 && getManagedUserId(userHandle) == -1) {
6954             // No managed device, user or profile, so setting provisioning state makes no sense.
6955             throw new IllegalStateException("Not allowed to change provisioning state unless a "
6956                       + "device or profile owner is set.");
6957         }
6958
6959         synchronized (this) {
6960             boolean transitionCheckNeeded = true;
6961
6962             // Calling identity/permission checks.
6963             if (isAdb()) {
6964                 // ADB shell can only move directly from un-managed to finalized as part of directly
6965                 // setting profile-owner or device-owner.
6966                 if (getUserProvisioningState(userHandle) !=
6967                         DevicePolicyManager.STATE_USER_UNMANAGED
6968                         || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6969                     throw new IllegalStateException("Not allowed to change provisioning state "
6970                             + "unless current provisioning state is unmanaged, and new state is "
6971                             + "finalized.");
6972                 }
6973                 transitionCheckNeeded = false;
6974             } else {
6975                 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6976                 enforceCanManageProfileAndDeviceOwners();
6977             }
6978
6979             final DevicePolicyData policyData = getUserData(userHandle);
6980             if (transitionCheckNeeded) {
6981                 // Optional state transition check for non-ADB case.
6982                 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6983             }
6984             policyData.mUserProvisioningState = newState;
6985             saveSettingsLocked(userHandle);
6986         }
6987     }
6988
6989     private void checkUserProvisioningStateTransition(int currentState, int newState) {
6990         // Valid transitions for normal use-cases.
6991         switch (currentState) {
6992             case DevicePolicyManager.STATE_USER_UNMANAGED:
6993                 // Can move to any state from unmanaged (except itself as an edge case)..
6994                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6995                     return;
6996                 }
6997                 break;
6998             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6999             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
7000                 // Can only move to finalized from these states.
7001                 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7002                     return;
7003                 }
7004                 break;
7005             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
7006                 // Current user has a managed-profile, but current user is not managed, so
7007                 // rather than moving to finalized state, go back to unmanaged once
7008                 // profile provisioning is complete.
7009                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
7010                     return;
7011                 }
7012                 break;
7013             case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
7014                 // Cannot transition out of finalized.
7015                 break;
7016         }
7017
7018         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
7019         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
7020                 + "from state [" + currentState + "]");
7021     }
7022
7023     @Override
7024     public void setProfileEnabled(ComponentName who) {
7025         if (!mHasFeature) {
7026             return;
7027         }
7028         Preconditions.checkNotNull(who, "ComponentName is null");
7029         synchronized (this) {
7030             // Check if this is the profile owner who is calling
7031             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7032             final int userId = UserHandle.getCallingUserId();
7033             enforceManagedProfile(userId, "enable the profile");
7034             // Check if the profile is already enabled.
7035             UserInfo managedProfile = getUserInfo(userId);
7036             if (managedProfile.isEnabled()) {
7037                 Slog.e(LOG_TAG,
7038                         "setProfileEnabled is called when the profile is already enabled");
7039                 return;
7040             }
7041             long id = mInjector.binderClearCallingIdentity();
7042             try {
7043                 mUserManager.setUserEnabled(userId);
7044                 UserInfo parent = mUserManager.getProfileParent(userId);
7045                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
7046                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
7047                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
7048                         Intent.FLAG_RECEIVER_FOREGROUND);
7049                 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
7050             } finally {
7051                 mInjector.binderRestoreCallingIdentity(id);
7052             }
7053         }
7054     }
7055
7056     @Override
7057     public void setProfileName(ComponentName who, String profileName) {
7058         Preconditions.checkNotNull(who, "ComponentName is null");
7059         int userId = UserHandle.getCallingUserId();
7060         // Check if this is the profile owner (includes device owner).
7061         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7062
7063         long id = mInjector.binderClearCallingIdentity();
7064         try {
7065             mUserManager.setUserName(userId, profileName);
7066         } finally {
7067             mInjector.binderRestoreCallingIdentity(id);
7068         }
7069     }
7070
7071     @Override
7072     public ComponentName getProfileOwner(int userHandle) {
7073         if (!mHasFeature) {
7074             return null;
7075         }
7076
7077         synchronized (this) {
7078             return mOwners.getProfileOwnerComponent(userHandle);
7079         }
7080     }
7081
7082     // Returns the active profile owner for this user or null if the current user has no
7083     // profile owner.
7084     @VisibleForTesting
7085     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
7086         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
7087         if (profileOwner == null) {
7088             return null;
7089         }
7090         DevicePolicyData policy = getUserData(userHandle);
7091         final int n = policy.mAdminList.size();
7092         for (int i = 0; i < n; i++) {
7093             ActiveAdmin admin = policy.mAdminList.get(i);
7094             if (profileOwner.equals(admin.info.getComponent())) {
7095                 return admin;
7096             }
7097         }
7098         return null;
7099     }
7100
7101     @Override
7102     public String getProfileOwnerName(int userHandle) {
7103         if (!mHasFeature) {
7104             return null;
7105         }
7106         enforceManageUsers();
7107         ComponentName profileOwner = getProfileOwner(userHandle);
7108         if (profileOwner == null) {
7109             return null;
7110         }
7111         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
7112     }
7113
7114     /**
7115      * Canonical name for a given package.
7116      */
7117     private String getApplicationLabel(String packageName, int userHandle) {
7118         long token = mInjector.binderClearCallingIdentity();
7119         try {
7120             final Context userContext;
7121             try {
7122                 UserHandle handle = new UserHandle(userHandle);
7123                 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
7124             } catch (PackageManager.NameNotFoundException nnfe) {
7125                 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
7126                 return null;
7127             }
7128             ApplicationInfo appInfo = userContext.getApplicationInfo();
7129             CharSequence result = null;
7130             if (appInfo != null) {
7131                 PackageManager pm = userContext.getPackageManager();
7132                 result = pm.getApplicationLabel(appInfo);
7133             }
7134             return result != null ? result.toString() : null;
7135         } finally {
7136             mInjector.binderRestoreCallingIdentity(token);
7137         }
7138     }
7139
7140     /**
7141      * Calls wtfStack() if called with the DPMS lock held.
7142      */
7143     private void wtfIfInLock() {
7144         if (Thread.holdsLock(this)) {
7145             Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
7146         }
7147     }
7148
7149     /**
7150      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7151      * permission.
7152      * The profile owner can only be set before the user setup phase has completed,
7153      * except for:
7154      * - SYSTEM_UID
7155      * - adb unless hasIncompatibleAccountsOrNonAdb is true.
7156      */
7157     private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
7158             boolean hasIncompatibleAccountsOrNonAdb) {
7159         UserInfo info = getUserInfo(userHandle);
7160         if (info == null) {
7161             // User doesn't exist.
7162             throw new IllegalArgumentException(
7163                     "Attempted to set profile owner for invalid userId: " + userHandle);
7164         }
7165         if (info.isGuest()) {
7166             throw new IllegalStateException("Cannot set a profile owner on a guest");
7167         }
7168         if (mOwners.hasProfileOwner(userHandle)) {
7169             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
7170                     + "is already set.");
7171         }
7172         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
7173             throw new IllegalStateException("Trying to set the profile owner, but the user "
7174                     + "already has a device owner.");
7175         }
7176         if (isAdb()) {
7177             if ((mIsWatch || hasUserSetupCompleted(userHandle))
7178                     && hasIncompatibleAccountsOrNonAdb) {
7179                 throw new IllegalStateException("Not allowed to set the profile owner because "
7180                         + "there are already some accounts on the profile");
7181             }
7182             return;
7183         }
7184         enforceCanManageProfileAndDeviceOwners();
7185         if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
7186             throw new IllegalStateException("Cannot set the profile owner on a user which is "
7187                     + "already set-up");
7188         }
7189     }
7190
7191     /**
7192      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7193      * permission.
7194      */
7195     private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
7196             boolean hasIncompatibleAccountsOrNonAdb) {
7197         if (!isAdb()) {
7198             enforceCanManageProfileAndDeviceOwners();
7199         }
7200
7201         final int code = checkDeviceOwnerProvisioningPreConditionLocked(
7202                 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb);
7203         switch (code) {
7204             case CODE_OK:
7205                 return;
7206             case CODE_HAS_DEVICE_OWNER:
7207                 throw new IllegalStateException(
7208                         "Trying to set the device owner, but device owner is already set.");
7209             case CODE_USER_HAS_PROFILE_OWNER:
7210                 throw new IllegalStateException("Trying to set the device owner, but the user "
7211                         + "already has a profile owner.");
7212             case CODE_USER_NOT_RUNNING:
7213                 throw new IllegalStateException("User not running: " + userId);
7214             case CODE_NOT_SYSTEM_USER:
7215                 throw new IllegalStateException("User is not system user");
7216             case CODE_USER_SETUP_COMPLETED:
7217                 throw new IllegalStateException(
7218                         "Cannot set the device owner if the device is already set-up");
7219             case CODE_NONSYSTEM_USER_EXISTS:
7220                 throw new IllegalStateException("Not allowed to set the device owner because there "
7221                         + "are already several users on the device");
7222             case CODE_ACCOUNTS_NOT_EMPTY:
7223                 throw new IllegalStateException("Not allowed to set the device owner because there "
7224                         + "are already some accounts on the device");
7225             case CODE_HAS_PAIRED:
7226                 throw new IllegalStateException("Not allowed to set the device owner because this "
7227                         + "device has already paired");
7228             default:
7229                 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code);
7230         }
7231     }
7232
7233     private void enforceUserUnlocked(int userId) {
7234         // Since we're doing this operation on behalf of an app, we only
7235         // want to use the actual "unlocked" state.
7236         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
7237                 "User must be running and unlocked");
7238     }
7239
7240     private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
7241         if (parent) {
7242             enforceUserUnlocked(getProfileParentId(userId));
7243         } else {
7244             enforceUserUnlocked(userId);
7245         }
7246     }
7247
7248     private void enforceManageUsers() {
7249         final int callingUid = mInjector.binderGetCallingUid();
7250         if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
7251             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7252         }
7253     }
7254
7255     private void enforceFullCrossUsersPermission(int userHandle) {
7256         enforceSystemUserOrPermissionIfCrossUser(userHandle,
7257                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7258     }
7259
7260     private void enforceCrossUsersPermission(int userHandle) {
7261         enforceSystemUserOrPermissionIfCrossUser(userHandle,
7262                 android.Manifest.permission.INTERACT_ACROSS_USERS);
7263     }
7264
7265     private void enforceSystemUserOrPermission(String permission) {
7266         if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) {
7267             mContext.enforceCallingOrSelfPermission(permission,
7268                     "Must be system or have " + permission + " permission");
7269         }
7270     }
7271
7272     private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) {
7273         if (userHandle < 0) {
7274             throw new IllegalArgumentException("Invalid userId " + userHandle);
7275         }
7276         if (userHandle == mInjector.userHandleGetCallingUserId()) {
7277             return;
7278         }
7279         enforceSystemUserOrPermission(permission);
7280     }
7281
7282     private void enforceManagedProfile(int userHandle, String message) {
7283         if(!isManagedProfile(userHandle)) {
7284             throw new SecurityException("You can not " + message + " outside a managed profile.");
7285         }
7286     }
7287
7288     private void enforceNotManagedProfile(int userHandle, String message) {
7289         if(isManagedProfile(userHandle)) {
7290             throw new SecurityException("You can not " + message + " for a managed profile.");
7291         }
7292     }
7293
7294     private void enforceDeviceOwnerOrManageUsers() {
7295         synchronized (this) {
7296             if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7297                     mInjector.binderGetCallingUid()) != null) {
7298                 return;
7299             }
7300         }
7301         enforceManageUsers();
7302     }
7303
7304     private void enforceProfileOwnerOrSystemUser() {
7305         synchronized (this) {
7306             if (getActiveAdminWithPolicyForUidLocked(null,
7307                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7308                             != null) {
7309                 return;
7310             }
7311         }
7312         Preconditions.checkState(isCallerWithSystemUid(),
7313                 "Only profile owner, device owner and system may call this method.");
7314     }
7315
7316     private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) {
7317         if (userId == mInjector.userHandleGetCallingUserId()) {
7318             synchronized (this) {
7319                 if (getActiveAdminWithPolicyForUidLocked(null,
7320                         DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7321                                 != null) {
7322                     // Device Owner/Profile Owner may access the user it runs on.
7323                     return;
7324                 }
7325             }
7326         }
7327         // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required.
7328         enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7329     }
7330
7331     private void ensureCallerPackage(@Nullable String packageName) {
7332         if (packageName == null) {
7333             Preconditions.checkState(isCallerWithSystemUid(),
7334                     "Only caller can omit package name");
7335         } else {
7336             final int callingUid = mInjector.binderGetCallingUid();
7337             final int userId = mInjector.userHandleGetCallingUserId();
7338             try {
7339                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
7340                         packageName, 0, userId);
7341                 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
7342             } catch (RemoteException e) {
7343                 // Shouldn't happen
7344             }
7345         }
7346     }
7347
7348     private boolean isCallerWithSystemUid() {
7349         return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
7350     }
7351
7352     protected int getProfileParentId(int userHandle) {
7353         final long ident = mInjector.binderClearCallingIdentity();
7354         try {
7355             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
7356             return parentUser != null ? parentUser.id : userHandle;
7357         } finally {
7358             mInjector.binderRestoreCallingIdentity(ident);
7359         }
7360     }
7361
7362     private int getCredentialOwner(int userHandle, boolean parent) {
7363         final long ident = mInjector.binderClearCallingIdentity();
7364         try {
7365             if (parent) {
7366                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
7367                 if (parentProfile != null) {
7368                     userHandle = parentProfile.id;
7369                 }
7370             }
7371             return mUserManager.getCredentialOwnerProfile(userHandle);
7372         } finally {
7373             mInjector.binderRestoreCallingIdentity(ident);
7374         }
7375     }
7376
7377     private boolean isManagedProfile(int userHandle) {
7378         final UserInfo user = getUserInfo(userHandle);
7379         return user != null && user.isManagedProfile();
7380     }
7381
7382     private void enableIfNecessary(String packageName, int userId) {
7383         try {
7384             final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
7385                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
7386             if (ai.enabledSetting
7387                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
7388                 mIPackageManager.setApplicationEnabledSetting(packageName,
7389                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
7390                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
7391             }
7392         } catch (RemoteException e) {
7393         }
7394     }
7395
7396     @Override
7397     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7398         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
7399
7400         synchronized (this) {
7401             pw.println("Current Device Policy Manager state:");
7402
7403             mOwners.dump("  ", pw);
7404             mDeviceAdminServiceController.dump("  ", pw);
7405             int userCount = mUserData.size();
7406             for (int u = 0; u < userCount; u++) {
7407                 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
7408                 pw.println();
7409                 pw.println("  Enabled Device Admins (User " + policy.mUserHandle
7410                         + ", provisioningState: " + policy.mUserProvisioningState + "):");
7411                 final int N = policy.mAdminList.size();
7412                 for (int i=0; i<N; i++) {
7413                     ActiveAdmin ap = policy.mAdminList.get(i);
7414                     if (ap != null) {
7415                         pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
7416                                 pw.println(":");
7417                         ap.dump("      ", pw);
7418                     }
7419                 }
7420                 if (!policy.mRemovingAdmins.isEmpty()) {
7421                     pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
7422                             + policy.mRemovingAdmins);
7423                 }
7424
7425                 pw.println(" ");
7426                 pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
7427             }
7428             pw.println();
7429             mConstants.dump("  ", pw);
7430             pw.println();
7431             pw.println("  Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
7432         }
7433     }
7434
7435     private String getEncryptionStatusName(int encryptionStatus) {
7436         switch (encryptionStatus) {
7437             case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
7438                 return "inactive";
7439             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
7440                 return "block default key";
7441             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
7442                 return "block";
7443             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
7444                 return "per-user";
7445             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
7446                 return "unsupported";
7447             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
7448                 return "activating";
7449             default:
7450                 return "unknown";
7451         }
7452     }
7453
7454     @Override
7455     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
7456             ComponentName activity) {
7457         Preconditions.checkNotNull(who, "ComponentName is null");
7458         final int userHandle = UserHandle.getCallingUserId();
7459         synchronized (this) {
7460             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7461
7462             long id = mInjector.binderClearCallingIdentity();
7463             try {
7464                 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
7465                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
7466             } catch (RemoteException re) {
7467                 // Shouldn't happen
7468             } finally {
7469                 mInjector.binderRestoreCallingIdentity(id);
7470             }
7471         }
7472     }
7473
7474     @Override
7475     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
7476         Preconditions.checkNotNull(who, "ComponentName is null");
7477         final int userHandle = UserHandle.getCallingUserId();
7478         synchronized (this) {
7479             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7480
7481             long id = mInjector.binderClearCallingIdentity();
7482             try {
7483                 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
7484                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
7485             } catch (RemoteException re) {
7486                 // Shouldn't happen
7487             } finally {
7488                 mInjector.binderRestoreCallingIdentity(id);
7489             }
7490         }
7491     }
7492
7493     @Override
7494     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
7495             String packageName) {
7496         try {
7497             setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
7498         } catch (IllegalArgumentException e) {
7499             return false;
7500         }
7501         return true;
7502     }
7503
7504     @Override
7505     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
7506         final List<String> delegatePackages = getDelegatePackages(admin,
7507                 DELEGATION_APP_RESTRICTIONS);
7508         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
7509     }
7510
7511     @Override
7512     public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
7513         return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS);
7514     }
7515
7516     @Override
7517     public void setApplicationRestrictions(ComponentName who, String callerPackage,
7518             String packageName, Bundle settings) {
7519         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
7520                 DELEGATION_APP_RESTRICTIONS);
7521
7522         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7523         final long id = mInjector.binderClearCallingIdentity();
7524         try {
7525             mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
7526         } finally {
7527             mInjector.binderRestoreCallingIdentity(id);
7528         }
7529     }
7530
7531     @Override
7532     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
7533             PersistableBundle args, boolean parent) {
7534         if (!mHasFeature) {
7535             return;
7536         }
7537         Preconditions.checkNotNull(admin, "admin is null");
7538         Preconditions.checkNotNull(agent, "agent is null");
7539         final int userHandle = UserHandle.getCallingUserId();
7540         synchronized (this) {
7541             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
7542                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
7543             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
7544             saveSettingsLocked(userHandle);
7545         }
7546     }
7547
7548     @Override
7549     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
7550             ComponentName agent, int userHandle, boolean parent) {
7551         if (!mHasFeature) {
7552             return null;
7553         }
7554         Preconditions.checkNotNull(agent, "agent null");
7555         enforceFullCrossUsersPermission(userHandle);
7556
7557         synchronized (this) {
7558             final String componentName = agent.flattenToString();
7559             if (admin != null) {
7560                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
7561                 if (ap == null) return null;
7562                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
7563                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
7564                 List<PersistableBundle> result = new ArrayList<>();
7565                 result.add(trustAgentInfo.options);
7566                 return result;
7567             }
7568
7569             // Return strictest policy for this user and profiles that are visible from this user.
7570             List<PersistableBundle> result = null;
7571             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
7572             // of the options. If any admin doesn't have options, discard options for the rest
7573             // and return null.
7574             List<ActiveAdmin> admins =
7575                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
7576             boolean allAdminsHaveOptions = true;
7577             final int N = admins.size();
7578             for (int i = 0; i < N; i++) {
7579                 final ActiveAdmin active = admins.get(i);
7580
7581                 final boolean disablesTrust = (active.disabledKeyguardFeatures
7582                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
7583                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
7584                 if (info != null && info.options != null && !info.options.isEmpty()) {
7585                     if (disablesTrust) {
7586                         if (result == null) {
7587                             result = new ArrayList<>();
7588                         }
7589                         result.add(info.options);
7590                     } else {
7591                         Log.w(LOG_TAG, "Ignoring admin " + active.info
7592                                 + " because it has trust options but doesn't declare "
7593                                 + "KEYGUARD_DISABLE_TRUST_AGENTS");
7594                     }
7595                 } else if (disablesTrust) {
7596                     allAdminsHaveOptions = false;
7597                     break;
7598                 }
7599             }
7600             return allAdminsHaveOptions ? result : null;
7601         }
7602     }
7603
7604     @Override
7605     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
7606         Preconditions.checkNotNull(who, "ComponentName is null");
7607         synchronized (this) {
7608             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7609
7610             int userHandle = UserHandle.getCallingUserId();
7611             DevicePolicyData userData = getUserData(userHandle);
7612             userData.mRestrictionsProvider = permissionProvider;
7613             saveSettingsLocked(userHandle);
7614         }
7615     }
7616
7617     @Override
7618     public ComponentName getRestrictionsProvider(int userHandle) {
7619         synchronized (this) {
7620             if (!isCallerWithSystemUid()) {
7621                 throw new SecurityException("Only the system can query the permission provider");
7622             }
7623             DevicePolicyData userData = getUserData(userHandle);
7624             return userData != null ? userData.mRestrictionsProvider : null;
7625         }
7626     }
7627
7628     @Override
7629     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
7630         Preconditions.checkNotNull(who, "ComponentName is null");
7631         int callingUserId = UserHandle.getCallingUserId();
7632         synchronized (this) {
7633             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7634
7635             long id = mInjector.binderClearCallingIdentity();
7636             try {
7637                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
7638                 if (parent == null) {
7639                     Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
7640                             + "parent");
7641                     return;
7642                 }
7643                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
7644                     mIPackageManager.addCrossProfileIntentFilter(
7645                             filter, who.getPackageName(), callingUserId, parent.id, 0);
7646                 }
7647                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
7648                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
7649                             parent.id, callingUserId, 0);
7650                 }
7651             } catch (RemoteException re) {
7652                 // Shouldn't happen
7653             } finally {
7654                 mInjector.binderRestoreCallingIdentity(id);
7655             }
7656         }
7657     }
7658
7659     @Override
7660     public void clearCrossProfileIntentFilters(ComponentName who) {
7661         Preconditions.checkNotNull(who, "ComponentName is null");
7662         int callingUserId = UserHandle.getCallingUserId();
7663         synchronized (this) {
7664             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7665             long id = mInjector.binderClearCallingIdentity();
7666             try {
7667                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
7668                 if (parent == null) {
7669                     Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
7670                             + "parent");
7671                     return;
7672                 }
7673                 // Removing those that go from the managed profile to the parent.
7674                 mIPackageManager.clearCrossProfileIntentFilters(
7675                         callingUserId, who.getPackageName());
7676                 // And those that go from the parent to the managed profile.
7677                 // If we want to support multiple managed profiles, we will have to only remove
7678                 // those that have callingUserId as their target.
7679                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
7680             } catch (RemoteException re) {
7681                 // Shouldn't happen
7682             } finally {
7683                 mInjector.binderRestoreCallingIdentity(id);
7684             }
7685         }
7686     }
7687
7688     /**
7689      * @return true if all packages in enabledPackages are either in the list
7690      * permittedList or are a system app.
7691      */
7692     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
7693             List<String> permittedList, int userIdToCheck) {
7694         long id = mInjector.binderClearCallingIdentity();
7695         try {
7696             // If we have an enabled packages list for a managed profile the packages
7697             // we should check are installed for the parent user.
7698             UserInfo user = getUserInfo(userIdToCheck);
7699             if (user.isManagedProfile()) {
7700                 userIdToCheck = user.profileGroupId;
7701             }
7702
7703             for (String enabledPackage : enabledPackages) {
7704                 boolean systemService = false;
7705                 try {
7706                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7707                             enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
7708                             userIdToCheck);
7709                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7710                 } catch (RemoteException e) {
7711                     Log.i(LOG_TAG, "Can't talk to package managed", e);
7712                 }
7713                 if (!systemService && !permittedList.contains(enabledPackage)) {
7714                     return false;
7715                 }
7716             }
7717         } finally {
7718             mInjector.binderRestoreCallingIdentity(id);
7719         }
7720         return true;
7721     }
7722
7723     private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7724         // Not using AccessibilityManager.getInstance because that guesses
7725         // at the user you require based on callingUid and caches for a given
7726         // process.
7727         IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7728         IAccessibilityManager service = iBinder == null
7729                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7730         return new AccessibilityManager(mContext, service, userId);
7731     }
7732
7733     @Override
7734     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7735         if (!mHasFeature) {
7736             return false;
7737         }
7738         Preconditions.checkNotNull(who, "ComponentName is null");
7739
7740         if (packageList != null) {
7741             int userId = UserHandle.getCallingUserId();
7742             List<AccessibilityServiceInfo> enabledServices = null;
7743             long id = mInjector.binderClearCallingIdentity();
7744             try {
7745                 UserInfo user = getUserInfo(userId);
7746                 if (user.isManagedProfile()) {
7747                     userId = user.profileGroupId;
7748                 }
7749                 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7750                 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7751                         AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7752             } finally {
7753                 mInjector.binderRestoreCallingIdentity(id);
7754             }
7755
7756             if (enabledServices != null) {
7757                 List<String> enabledPackages = new ArrayList<String>();
7758                 for (AccessibilityServiceInfo service : enabledServices) {
7759                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7760                 }
7761                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7762                         userId)) {
7763                     Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7764                             + "because it contains already enabled accesibility services.");
7765                     return false;
7766                 }
7767             }
7768         }
7769
7770         synchronized (this) {
7771             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7772                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7773             admin.permittedAccessiblityServices = packageList;
7774             saveSettingsLocked(UserHandle.getCallingUserId());
7775         }
7776         return true;
7777     }
7778
7779     @Override
7780     public List getPermittedAccessibilityServices(ComponentName who) {
7781         if (!mHasFeature) {
7782             return null;
7783         }
7784         Preconditions.checkNotNull(who, "ComponentName is null");
7785
7786         synchronized (this) {
7787             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7788                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7789             return admin.permittedAccessiblityServices;
7790         }
7791     }
7792
7793     @Override
7794     public List getPermittedAccessibilityServicesForUser(int userId) {
7795         if (!mHasFeature) {
7796             return null;
7797         }
7798         synchronized (this) {
7799             List<String> result = null;
7800             // If we have multiple profiles we return the intersection of the
7801             // permitted lists. This can happen in cases where we have a device
7802             // and profile owner.
7803             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7804             for (int profileId : profileIds) {
7805                 // Just loop though all admins, only device or profiles
7806                 // owners can have permitted lists set.
7807                 DevicePolicyData policy = getUserDataUnchecked(profileId);
7808                 final int N = policy.mAdminList.size();
7809                 for (int j = 0; j < N; j++) {
7810                     ActiveAdmin admin = policy.mAdminList.get(j);
7811                     List<String> fromAdmin = admin.permittedAccessiblityServices;
7812                     if (fromAdmin != null) {
7813                         if (result == null) {
7814                             result = new ArrayList<>(fromAdmin);
7815                         } else {
7816                             result.retainAll(fromAdmin);
7817                         }
7818                     }
7819                 }
7820             }
7821
7822             // If we have a permitted list add all system accessibility services.
7823             if (result != null) {
7824                 long id = mInjector.binderClearCallingIdentity();
7825                 try {
7826                     UserInfo user = getUserInfo(userId);
7827                     if (user.isManagedProfile()) {
7828                         userId = user.profileGroupId;
7829                     }
7830                     AccessibilityManager accessibilityManager =
7831                             getAccessibilityManagerForUser(userId);
7832                     List<AccessibilityServiceInfo> installedServices =
7833                             accessibilityManager.getInstalledAccessibilityServiceList();
7834
7835                     if (installedServices != null) {
7836                         for (AccessibilityServiceInfo service : installedServices) {
7837                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7838                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7839                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7840                                 result.add(serviceInfo.packageName);
7841                             }
7842                         }
7843                     }
7844                 } finally {
7845                     mInjector.binderRestoreCallingIdentity(id);
7846                 }
7847             }
7848
7849             return result;
7850         }
7851     }
7852
7853     @Override
7854     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7855             int userHandle) {
7856         if (!mHasFeature) {
7857             return true;
7858         }
7859         Preconditions.checkNotNull(who, "ComponentName is null");
7860         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7861         if (!isCallerWithSystemUid()){
7862             throw new SecurityException(
7863                     "Only the system can query if an accessibility service is disabled by admin");
7864         }
7865         synchronized (this) {
7866             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7867             if (admin == null) {
7868                 return false;
7869             }
7870             if (admin.permittedAccessiblityServices == null) {
7871                 return true;
7872             }
7873             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
7874                     admin.permittedAccessiblityServices, userHandle);
7875         }
7876     }
7877
7878     private boolean checkCallerIsCurrentUserOrProfile() {
7879         final int callingUserId = UserHandle.getCallingUserId();
7880         final long token = mInjector.binderClearCallingIdentity();
7881         try {
7882             UserInfo currentUser;
7883             UserInfo callingUser = getUserInfo(callingUserId);
7884             try {
7885                 currentUser = mInjector.getIActivityManager().getCurrentUser();
7886             } catch (RemoteException e) {
7887                 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7888                 return false;
7889             }
7890
7891             if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7892                 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7893                         + "of a user that isn't the foreground user.");
7894                 return false;
7895             }
7896             if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7897                 Slog.e(LOG_TAG, "Cannot set permitted input methods "
7898                         + "of a user that isn't the foreground user.");
7899                 return false;
7900             }
7901         } finally {
7902             mInjector.binderRestoreCallingIdentity(token);
7903         }
7904         return true;
7905     }
7906
7907     @Override
7908     public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7909         if (!mHasFeature) {
7910             return false;
7911         }
7912         Preconditions.checkNotNull(who, "ComponentName is null");
7913
7914         // TODO When InputMethodManager supports per user calls remove
7915         //      this restriction.
7916         if (!checkCallerIsCurrentUserOrProfile()) {
7917             return false;
7918         }
7919
7920         final int callingUserId = mInjector.userHandleGetCallingUserId();
7921         if (packageList != null) {
7922             // InputMethodManager fetches input methods for current user.
7923             // So this can only be set when calling user is the current user
7924             // or parent is current user in case of managed profiles.
7925             InputMethodManager inputMethodManager =
7926                     mContext.getSystemService(InputMethodManager.class);
7927             List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7928
7929             if (enabledImes != null) {
7930                 List<String> enabledPackages = new ArrayList<String>();
7931                 for (InputMethodInfo ime : enabledImes) {
7932                     enabledPackages.add(ime.getPackageName());
7933                 }
7934                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7935                         callingUserId)) {
7936                     Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7937                             + "because it contains already enabled input method.");
7938                     return false;
7939                 }
7940             }
7941         }
7942
7943         synchronized (this) {
7944             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7945                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7946             admin.permittedInputMethods = packageList;
7947             saveSettingsLocked(callingUserId);
7948         }
7949         return true;
7950     }
7951
7952     @Override
7953     public List getPermittedInputMethods(ComponentName who) {
7954         if (!mHasFeature) {
7955             return null;
7956         }
7957         Preconditions.checkNotNull(who, "ComponentName is null");
7958
7959         synchronized (this) {
7960             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7961                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7962             return admin.permittedInputMethods;
7963         }
7964     }
7965
7966     @Override
7967     public List getPermittedInputMethodsForCurrentUser() {
7968         UserInfo currentUser;
7969         try {
7970             currentUser = mInjector.getIActivityManager().getCurrentUser();
7971         } catch (RemoteException e) {
7972             Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7973             // Activity managed is dead, just allow all IMEs
7974             return null;
7975         }
7976
7977         int userId = currentUser.id;
7978         synchronized (this) {
7979             List<String> result = null;
7980             // If we have multiple profiles we return the intersection of the
7981             // permitted lists. This can happen in cases where we have a device
7982             // and profile owner.
7983             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7984             for (int profileId : profileIds) {
7985                 // Just loop though all admins, only device or profiles
7986                 // owners can have permitted lists set.
7987                 DevicePolicyData policy = getUserDataUnchecked(profileId);
7988                 final int N = policy.mAdminList.size();
7989                 for (int j = 0; j < N; j++) {
7990                     ActiveAdmin admin = policy.mAdminList.get(j);
7991                     List<String> fromAdmin = admin.permittedInputMethods;
7992                     if (fromAdmin != null) {
7993                         if (result == null) {
7994                             result = new ArrayList<String>(fromAdmin);
7995                         } else {
7996                             result.retainAll(fromAdmin);
7997                         }
7998                     }
7999                 }
8000             }
8001
8002             // If we have a permitted list add all system input methods.
8003             if (result != null) {
8004                 InputMethodManager inputMethodManager =
8005                         mContext.getSystemService(InputMethodManager.class);
8006                 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
8007                 long id = mInjector.binderClearCallingIdentity();
8008                 try {
8009                     if (imes != null) {
8010                         for (InputMethodInfo ime : imes) {
8011                             ServiceInfo serviceInfo = ime.getServiceInfo();
8012                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8013                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8014                                 result.add(serviceInfo.packageName);
8015                             }
8016                         }
8017                     }
8018                 } finally {
8019                     mInjector.binderRestoreCallingIdentity(id);
8020                 }
8021             }
8022             return result;
8023         }
8024     }
8025
8026     @Override
8027     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
8028             int userHandle) {
8029         if (!mHasFeature) {
8030             return true;
8031         }
8032         Preconditions.checkNotNull(who, "ComponentName is null");
8033         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8034         if (!isCallerWithSystemUid()) {
8035             throw new SecurityException(
8036                     "Only the system can query if an input method is disabled by admin");
8037         }
8038         synchronized (this) {
8039             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8040             if (admin == null) {
8041                 return false;
8042             }
8043             if (admin.permittedInputMethods == null) {
8044                 return true;
8045             }
8046             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8047                     admin.permittedInputMethods, userHandle);
8048         }
8049     }
8050
8051     @Override
8052     public boolean setPermittedCrossProfileNotificationListeners(
8053             ComponentName who, List<String> packageList) {
8054         if (!mHasFeature) {
8055             return false;
8056         }
8057         Preconditions.checkNotNull(who, "ComponentName is null");
8058
8059         final int callingUserId = mInjector.userHandleGetCallingUserId();
8060         if (!isManagedProfile(callingUserId)) {
8061             return false;
8062         }
8063
8064         synchronized (this) {
8065             ActiveAdmin admin = getActiveAdminForCallerLocked(
8066                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8067             admin.permittedNotificationListeners = packageList;
8068             saveSettingsLocked(callingUserId);
8069         }
8070         return true;
8071     }
8072
8073     @Override
8074     public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
8075         if (!mHasFeature) {
8076             return null;
8077         }
8078         Preconditions.checkNotNull(who, "ComponentName is null");
8079
8080         synchronized (this) {
8081             ActiveAdmin admin = getActiveAdminForCallerLocked(
8082                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8083             return admin.permittedNotificationListeners;
8084         }
8085     }
8086
8087     @Override
8088     public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
8089         if (!mHasFeature) {
8090             return true;
8091         }
8092
8093         Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
8094         if (!isCallerWithSystemUid()) {
8095             throw new SecurityException(
8096                     "Only the system can query if a notification listener service is permitted");
8097         }
8098         synchronized (this) {
8099             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8100             if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
8101                 return true;
8102             }
8103             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8104                     profileOwner.permittedNotificationListeners, userId);
8105
8106         }
8107     }
8108
8109
8110     private void sendAdminEnabledBroadcastLocked(int userHandle) {
8111         DevicePolicyData policyData = getUserData(userHandle);
8112         if (policyData.mAdminBroadcastPending) {
8113             // Send the initialization data to profile owner and delete the data
8114             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
8115             if (admin != null) {
8116                 PersistableBundle initBundle = policyData.mInitBundle;
8117                 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
8118                         initBundle == null ? null : new Bundle(initBundle), null);
8119             }
8120             policyData.mInitBundle = null;
8121             policyData.mAdminBroadcastPending = false;
8122             saveSettingsLocked(userHandle);
8123         }
8124     }
8125
8126     @Override
8127     public UserHandle createAndManageUser(ComponentName admin, String name,
8128             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
8129         Preconditions.checkNotNull(admin, "admin is null");
8130         Preconditions.checkNotNull(profileOwner, "profileOwner is null");
8131         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
8132             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
8133                     + admin + " are not in the same package");
8134         }
8135         // Only allow the system user to use this method
8136         if (!mInjector.binderGetCallingUserHandle().isSystem()) {
8137             throw new SecurityException("createAndManageUser was called from non-system user");
8138         }
8139         final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
8140         final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
8141                 && UserManager.isDeviceInDemoMode(mContext);
8142         if (ephemeral && !mInjector.userManagerIsSplitSystemUser() && !demo) {
8143             throw new IllegalArgumentException(
8144                     "Ephemeral users are only supported on systems with a split system user.");
8145         }
8146         // Create user.
8147         UserHandle user = null;
8148         synchronized (this) {
8149             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8150
8151             final long id = mInjector.binderClearCallingIdentity();
8152             try {
8153                 int userInfoFlags = 0;
8154                 if (ephemeral) {
8155                     userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
8156                 }
8157                 if (demo) {
8158                     userInfoFlags |= UserInfo.FLAG_DEMO;
8159                 }
8160                 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
8161                         userInfoFlags);
8162                 if (userInfo != null) {
8163                     user = userInfo.getUserHandle();
8164                 }
8165             } finally {
8166                 mInjector.binderRestoreCallingIdentity(id);
8167             }
8168         }
8169         if (user == null) {
8170             return null;
8171         }
8172         // Set admin.
8173         final long id = mInjector.binderClearCallingIdentity();
8174         try {
8175             final String adminPkg = admin.getPackageName();
8176
8177             final int userHandle = user.getIdentifier();
8178             try {
8179                 // Install the profile owner if not present.
8180                 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
8181                     mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle,
8182                             0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8183                 }
8184             } catch (RemoteException e) {
8185                 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
8186                         + "removing created user", e);
8187                 mUserManager.removeUser(user.getIdentifier());
8188                 return null;
8189             }
8190
8191             setActiveAdmin(profileOwner, true, userHandle);
8192             // User is not started yet, the broadcast by setActiveAdmin will not be received.
8193             // So we store adminExtras for broadcasting when the user starts for first time.
8194             synchronized(this) {
8195                 DevicePolicyData policyData = getUserData(userHandle);
8196                 policyData.mInitBundle = adminExtras;
8197                 policyData.mAdminBroadcastPending = true;
8198                 saveSettingsLocked(userHandle);
8199             }
8200             final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
8201             setProfileOwner(profileOwner, ownerName, userHandle);
8202
8203             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
8204                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
8205                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
8206             }
8207
8208             return user;
8209         } finally {
8210             mInjector.binderRestoreCallingIdentity(id);
8211         }
8212     }
8213
8214     @Override
8215     public boolean removeUser(ComponentName who, UserHandle userHandle) {
8216         Preconditions.checkNotNull(who, "ComponentName is null");
8217         synchronized (this) {
8218             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8219         }
8220
8221         final int callingUserId = mInjector.userHandleGetCallingUserId();
8222         final long id = mInjector.binderClearCallingIdentity();
8223         try {
8224             String restriction = isManagedProfile(userHandle.getIdentifier())
8225                     ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
8226                     : UserManager.DISALLOW_REMOVE_USER;
8227             if (isAdminAffectedByRestriction(who, restriction, callingUserId)) {
8228                 Log.w(LOG_TAG, "The device owner cannot remove a user because "
8229                         + restriction + " is enabled, and was not set by the device owner");
8230                 return false;
8231             }
8232             return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
8233         } finally {
8234             mInjector.binderRestoreCallingIdentity(id);
8235         }
8236     }
8237
8238     private boolean isAdminAffectedByRestriction(
8239             ComponentName admin, String userRestriction, int userId) {
8240         switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
8241             case UserManager.RESTRICTION_NOT_SET:
8242                 return false;
8243             case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
8244                 return !isDeviceOwner(admin, userId);
8245             case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
8246                 return !isProfileOwner(admin, userId);
8247             default:
8248                 return true;
8249         }
8250     }
8251
8252     @Override
8253     public boolean switchUser(ComponentName who, UserHandle userHandle) {
8254         Preconditions.checkNotNull(who, "ComponentName is null");
8255         synchronized (this) {
8256             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8257
8258             long id = mInjector.binderClearCallingIdentity();
8259             try {
8260                 int userId = UserHandle.USER_SYSTEM;
8261                 if (userHandle != null) {
8262                     userId = userHandle.getIdentifier();
8263                 }
8264                 return mInjector.getIActivityManager().switchUser(userId);
8265             } catch (RemoteException e) {
8266                 Log.e(LOG_TAG, "Couldn't switch user", e);
8267                 return false;
8268             } finally {
8269                 mInjector.binderRestoreCallingIdentity(id);
8270             }
8271         }
8272     }
8273
8274     @Override
8275     public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
8276             String packageName) {
8277         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8278                 DELEGATION_APP_RESTRICTIONS);
8279
8280         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
8281         final long id = mInjector.binderClearCallingIdentity();
8282         try {
8283            Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
8284            // if no restrictions were saved, mUserManager.getApplicationRestrictions
8285            // returns null, but DPM method should return an empty Bundle as per JavaDoc
8286            return bundle != null ? bundle : Bundle.EMPTY;
8287         } finally {
8288             mInjector.binderRestoreCallingIdentity(id);
8289         }
8290     }
8291
8292     @Override
8293     public String[] setPackagesSuspended(ComponentName who, String callerPackage,
8294             String[] packageNames, boolean suspended) {
8295         int callingUserId = UserHandle.getCallingUserId();
8296         synchronized (this) {
8297             // Ensure the caller is a DO/PO or a package access delegate.
8298             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8299                     DELEGATION_PACKAGE_ACCESS);
8300
8301             long id = mInjector.binderClearCallingIdentity();
8302             try {
8303                 return mIPackageManager.setPackagesSuspendedAsUser(
8304                         packageNames, suspended, callingUserId);
8305             } catch (RemoteException re) {
8306                 // Shouldn't happen.
8307                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
8308             } finally {
8309                 mInjector.binderRestoreCallingIdentity(id);
8310             }
8311             return packageNames;
8312         }
8313     }
8314
8315     @Override
8316     public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
8317         int callingUserId = UserHandle.getCallingUserId();
8318         synchronized (this) {
8319             // Ensure the caller is a DO/PO or a package access delegate.
8320             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8321                     DELEGATION_PACKAGE_ACCESS);
8322
8323             long id = mInjector.binderClearCallingIdentity();
8324             try {
8325                 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
8326             } catch (RemoteException re) {
8327                 // Shouldn't happen.
8328                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
8329             } finally {
8330                 mInjector.binderRestoreCallingIdentity(id);
8331             }
8332             return false;
8333         }
8334     }
8335
8336     @Override
8337     public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
8338         Preconditions.checkNotNull(who, "ComponentName is null");
8339         if (!UserRestrictionsUtils.isValidRestriction(key)) {
8340             return;
8341         }
8342
8343         final int userHandle = mInjector.userHandleGetCallingUserId();
8344         synchronized (this) {
8345             final ActiveAdmin activeAdmin =
8346                     getActiveAdminForCallerLocked(who,
8347                             DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8348             final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
8349             if (isDeviceOwner) {
8350                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
8351                     throw new SecurityException("Device owner cannot set user restriction " + key);
8352                 }
8353             } else { // profile owner
8354                 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
8355                     throw new SecurityException("Profile owner cannot set user restriction " + key);
8356                 }
8357             }
8358
8359             // Save the restriction to ActiveAdmin.
8360             final Bundle restrictions = activeAdmin.ensureUserRestrictions();
8361             if (enabledFromThisOwner) {
8362                 restrictions.putBoolean(key, true);
8363             } else {
8364                 restrictions.remove(key);
8365             }
8366             saveUserRestrictionsLocked(userHandle);
8367         }
8368     }
8369
8370     private void saveUserRestrictionsLocked(int userId) {
8371         saveSettingsLocked(userId);
8372         pushUserRestrictions(userId);
8373         sendChangedNotification(userId);
8374     }
8375
8376     private void pushUserRestrictions(int userId) {
8377         synchronized (this) {
8378             final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
8379             final Bundle userRestrictions;
8380             // Whether device owner enforces camera restriction.
8381             boolean disallowCameraGlobally = false;
8382
8383             if (isDeviceOwner) {
8384                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
8385                 if (deviceOwner == null) {
8386                     return; // Shouldn't happen.
8387                 }
8388                 userRestrictions = deviceOwner.userRestrictions;
8389                 // DO can disable camera globally.
8390                 disallowCameraGlobally = deviceOwner.disableCamera;
8391             } else {
8392                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8393                 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null;
8394             }
8395
8396             // Whether any admin enforces camera restriction.
8397             final int cameraRestrictionScope =
8398                     getCameraRestrictionScopeLocked(userId, disallowCameraGlobally);
8399
8400             mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
8401                     isDeviceOwner, cameraRestrictionScope);
8402         }
8403     }
8404
8405     /**
8406      * Get the scope of camera restriction for a given user if any.
8407      */
8408     private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) {
8409         if (disallowCameraGlobally) {
8410             return UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
8411         } else if (getCameraDisabled(
8412                 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) {
8413             return UserManagerInternal.CAMERA_DISABLED_LOCALLY;
8414         }
8415         return UserManagerInternal.CAMERA_NOT_DISABLED;
8416     }
8417
8418     @Override
8419     public Bundle getUserRestrictions(ComponentName who) {
8420         if (!mHasFeature) {
8421             return null;
8422         }
8423         Preconditions.checkNotNull(who, "ComponentName is null");
8424         synchronized (this) {
8425             final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
8426                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8427             return activeAdmin.userRestrictions;
8428         }
8429     }
8430
8431     @Override
8432     public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
8433             boolean hidden) {
8434         int callingUserId = UserHandle.getCallingUserId();
8435         synchronized (this) {
8436             // Ensure the caller is a DO/PO or a package access delegate.
8437             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8438                     DELEGATION_PACKAGE_ACCESS);
8439
8440             long id = mInjector.binderClearCallingIdentity();
8441             try {
8442                 return mIPackageManager.setApplicationHiddenSettingAsUser(
8443                         packageName, hidden, callingUserId);
8444             } catch (RemoteException re) {
8445                 // shouldn't happen
8446                 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
8447             } finally {
8448                 mInjector.binderRestoreCallingIdentity(id);
8449             }
8450             return false;
8451         }
8452     }
8453
8454     @Override
8455     public boolean isApplicationHidden(ComponentName who, String callerPackage,
8456             String packageName) {
8457         int callingUserId = UserHandle.getCallingUserId();
8458         synchronized (this) {
8459             // Ensure the caller is a DO/PO or a package access delegate.
8460             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8461                     DELEGATION_PACKAGE_ACCESS);
8462
8463             long id = mInjector.binderClearCallingIdentity();
8464             try {
8465                 return mIPackageManager.getApplicationHiddenSettingAsUser(
8466                         packageName, callingUserId);
8467             } catch (RemoteException re) {
8468                 // shouldn't happen
8469                 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
8470             } finally {
8471                 mInjector.binderRestoreCallingIdentity(id);
8472             }
8473             return false;
8474         }
8475     }
8476
8477     @Override
8478     public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
8479         synchronized (this) {
8480             // Ensure the caller is a DO/PO or an enable system app delegate.
8481             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8482                     DELEGATION_ENABLE_SYSTEM_APP);
8483
8484             final boolean isDemo = isCurrentUserDemo();
8485
8486             int userId = UserHandle.getCallingUserId();
8487             long id = mInjector.binderClearCallingIdentity();
8488
8489             try {
8490                 if (VERBOSE_LOG) {
8491                     Slog.v(LOG_TAG, "installing " + packageName + " for "
8492                             + userId);
8493                 }
8494
8495                 int parentUserId = getProfileParentId(userId);
8496                 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) {
8497                     throw new IllegalArgumentException("Only system apps can be enabled this way.");
8498                 }
8499
8500                 // Install the app.
8501                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
8502                         0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8503                 if (isDemo) {
8504                     // Ensure the app is also ENABLED for demo users.
8505                     mIPackageManager.setApplicationEnabledSetting(packageName,
8506                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
8507                             PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
8508                 }
8509             } catch (RemoteException re) {
8510                 // shouldn't happen
8511                 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
8512             } finally {
8513                 mInjector.binderRestoreCallingIdentity(id);
8514             }
8515         }
8516     }
8517
8518     @Override
8519     public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
8520         synchronized (this) {
8521             // Ensure the caller is a DO/PO or an enable system app delegate.
8522             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8523                     DELEGATION_ENABLE_SYSTEM_APP);
8524
8525             int userId = UserHandle.getCallingUserId();
8526             long id = mInjector.binderClearCallingIdentity();
8527
8528             try {
8529                 int parentUserId = getProfileParentId(userId);
8530                 List<ResolveInfo> activitiesToEnable = mIPackageManager
8531                         .queryIntentActivities(intent,
8532                                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
8533                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
8534                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
8535                                 parentUserId)
8536                         .getList();
8537
8538                 if (VERBOSE_LOG) {
8539                     Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
8540                 }
8541                 int numberOfAppsInstalled = 0;
8542                 if (activitiesToEnable != null) {
8543                     for (ResolveInfo info : activitiesToEnable) {
8544                         if (info.activityInfo != null) {
8545                             String packageName = info.activityInfo.packageName;
8546                             if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
8547                                 numberOfAppsInstalled++;
8548                                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
8549                                         0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8550                             } else {
8551                                 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
8552                                         + " system app");
8553                             }
8554                         }
8555                     }
8556                 }
8557                 return numberOfAppsInstalled;
8558             } catch (RemoteException e) {
8559                 // shouldn't happen
8560                 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
8561                 return 0;
8562             } finally {
8563                 mInjector.binderRestoreCallingIdentity(id);
8564             }
8565         }
8566     }
8567
8568     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
8569             throws RemoteException {
8570         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
8571                 userId);
8572         if (appInfo == null) {
8573             throw new IllegalArgumentException("The application " + packageName +
8574                     " is not present on this device");
8575         }
8576         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8577     }
8578
8579     @Override
8580     public void setAccountManagementDisabled(ComponentName who, String accountType,
8581             boolean disabled) {
8582         if (!mHasFeature) {
8583             return;
8584         }
8585         Preconditions.checkNotNull(who, "ComponentName is null");
8586         synchronized (this) {
8587             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
8588                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8589             if (disabled) {
8590                 ap.accountTypesWithManagementDisabled.add(accountType);
8591             } else {
8592                 ap.accountTypesWithManagementDisabled.remove(accountType);
8593             }
8594             saveSettingsLocked(UserHandle.getCallingUserId());
8595         }
8596     }
8597
8598     @Override
8599     public String[] getAccountTypesWithManagementDisabled() {
8600         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
8601     }
8602
8603     @Override
8604     public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
8605         enforceFullCrossUsersPermission(userId);
8606         if (!mHasFeature) {
8607             return null;
8608         }
8609         synchronized (this) {
8610             DevicePolicyData policy = getUserData(userId);
8611             final int N = policy.mAdminList.size();
8612             ArraySet<String> resultSet = new ArraySet<>();
8613             for (int i = 0; i < N; i++) {
8614                 ActiveAdmin admin = policy.mAdminList.get(i);
8615                 resultSet.addAll(admin.accountTypesWithManagementDisabled);
8616             }
8617             return resultSet.toArray(new String[resultSet.size()]);
8618         }
8619     }
8620
8621     @Override
8622     public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
8623             boolean uninstallBlocked) {
8624         final int userId = UserHandle.getCallingUserId();
8625         synchronized (this) {
8626             // Ensure the caller is a DO/PO or a block uninstall delegate
8627             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8628                     DELEGATION_BLOCK_UNINSTALL);
8629
8630             long id = mInjector.binderClearCallingIdentity();
8631             try {
8632                 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
8633             } catch (RemoteException re) {
8634                 // Shouldn't happen.
8635                 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
8636             } finally {
8637                 mInjector.binderRestoreCallingIdentity(id);
8638             }
8639         }
8640     }
8641
8642     @Override
8643     public boolean isUninstallBlocked(ComponentName who, String packageName) {
8644         // This function should return true if and only if the package is blocked by
8645         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
8646         // when the package is a system app, or when it is an active device admin.
8647         final int userId = UserHandle.getCallingUserId();
8648
8649         synchronized (this) {
8650             if (who != null) {
8651                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8652             }
8653
8654             long id = mInjector.binderClearCallingIdentity();
8655             try {
8656                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
8657             } catch (RemoteException re) {
8658                 // Shouldn't happen.
8659                 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
8660             } finally {
8661                 mInjector.binderRestoreCallingIdentity(id);
8662             }
8663         }
8664         return false;
8665     }
8666
8667     @Override
8668     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
8669         if (!mHasFeature) {
8670             return;
8671         }
8672         Preconditions.checkNotNull(who, "ComponentName is null");
8673         synchronized (this) {
8674             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8675                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8676             if (admin.disableCallerId != disabled) {
8677                 admin.disableCallerId = disabled;
8678                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
8679             }
8680         }
8681     }
8682
8683     @Override
8684     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
8685         if (!mHasFeature) {
8686             return false;
8687         }
8688         Preconditions.checkNotNull(who, "ComponentName is null");
8689         synchronized (this) {
8690             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8691                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8692             return admin.disableCallerId;
8693         }
8694     }
8695
8696     @Override
8697     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
8698         enforceCrossUsersPermission(userId);
8699         synchronized (this) {
8700             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8701             return (admin != null) ? admin.disableCallerId : false;
8702         }
8703     }
8704
8705     @Override
8706     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
8707         if (!mHasFeature) {
8708             return;
8709         }
8710         Preconditions.checkNotNull(who, "ComponentName is null");
8711         synchronized (this) {
8712             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8713                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8714             if (admin.disableContactsSearch != disabled) {
8715                 admin.disableContactsSearch = disabled;
8716                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
8717             }
8718         }
8719     }
8720
8721     @Override
8722     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
8723         if (!mHasFeature) {
8724             return false;
8725         }
8726         Preconditions.checkNotNull(who, "ComponentName is null");
8727         synchronized (this) {
8728             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8729                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8730             return admin.disableContactsSearch;
8731         }
8732     }
8733
8734     @Override
8735     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
8736         enforceCrossUsersPermission(userId);
8737         synchronized (this) {
8738             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8739             return (admin != null) ? admin.disableContactsSearch : false;
8740         }
8741     }
8742
8743     @Override
8744     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
8745             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
8746         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
8747                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
8748         final int callingUserId = UserHandle.getCallingUserId();
8749
8750         final long ident = mInjector.binderClearCallingIdentity();
8751         try {
8752             synchronized (this) {
8753                 final int managedUserId = getManagedUserId(callingUserId);
8754                 if (managedUserId < 0) {
8755                     return;
8756                 }
8757                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
8758                     if (VERBOSE_LOG) {
8759                         Log.v(LOG_TAG,
8760                                 "Cross-profile contacts access disabled for user " + managedUserId);
8761                     }
8762                     return;
8763                 }
8764                 ContactsInternal.startQuickContactWithErrorToastForUser(
8765                         mContext, intent, new UserHandle(managedUserId));
8766             }
8767         } finally {
8768             mInjector.binderRestoreCallingIdentity(ident);
8769         }
8770     }
8771
8772     /**
8773      * @return true if cross-profile QuickContact is disabled
8774      */
8775     private boolean isCrossProfileQuickContactDisabled(int userId) {
8776         return getCrossProfileCallerIdDisabledForUser(userId)
8777                 && getCrossProfileContactsSearchDisabledForUser(userId);
8778     }
8779
8780     /**
8781      * @return the user ID of the managed user that is linked to the current user, if any.
8782      * Otherwise -1.
8783      */
8784     public int getManagedUserId(int callingUserId) {
8785         if (VERBOSE_LOG) {
8786             Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
8787         }
8788
8789         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
8790             if (ui.id == callingUserId || !ui.isManagedProfile()) {
8791                 continue; // Caller user self, or not a managed profile.  Skip.
8792             }
8793             if (VERBOSE_LOG) {
8794                 Log.v(LOG_TAG, "Managed user=" + ui.id);
8795             }
8796             return ui.id;
8797         }
8798         if (VERBOSE_LOG) {
8799             Log.v(LOG_TAG, "Managed user not found.");
8800         }
8801         return -1;
8802     }
8803
8804     @Override
8805     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
8806         if (!mHasFeature) {
8807             return;
8808         }
8809         Preconditions.checkNotNull(who, "ComponentName is null");
8810         synchronized (this) {
8811             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8812                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8813             if (admin.disableBluetoothContactSharing != disabled) {
8814                 admin.disableBluetoothContactSharing = disabled;
8815                 saveSettingsLocked(UserHandle.getCallingUserId());
8816             }
8817         }
8818     }
8819
8820     @Override
8821     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
8822         if (!mHasFeature) {
8823             return false;
8824         }
8825         Preconditions.checkNotNull(who, "ComponentName is null");
8826         synchronized (this) {
8827             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8828                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8829             return admin.disableBluetoothContactSharing;
8830         }
8831     }
8832
8833     @Override
8834     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
8835         // TODO: Should there be a check to make sure this relationship is
8836         // within a profile group?
8837         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
8838         synchronized (this) {
8839             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8840             return (admin != null) ? admin.disableBluetoothContactSharing : false;
8841         }
8842     }
8843
8844     @Override
8845     public void setLockTaskPackages(ComponentName who, String[] packages)
8846             throws SecurityException {
8847         Preconditions.checkNotNull(who, "ComponentName is null");
8848         Preconditions.checkNotNull(packages, "packages is null");
8849
8850         synchronized (this) {
8851             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8852             final int userHandle = mInjector.userHandleGetCallingUserId();
8853             if (isUserAffiliatedWithDeviceLocked(userHandle)) {
8854                 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
8855             } else {
8856                 throw new SecurityException("Admin " + who +
8857                     " is neither the device owner or affiliated user's profile owner.");
8858             }
8859         }
8860     }
8861
8862     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
8863         DevicePolicyData policy = getUserData(userHandle);
8864         policy.mLockTaskPackages = packages;
8865
8866         // Store the settings persistently.
8867         saveSettingsLocked(userHandle);
8868         updateLockTaskPackagesLocked(packages, userHandle);
8869     }
8870
8871     private void maybeClearLockTaskPackagesLocked() {
8872         final long ident = mInjector.binderClearCallingIdentity();
8873         try {
8874             final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
8875             for (int i = 0; i < userInfos.size(); i++) {
8876                 int userId = userInfos.get(i).id;
8877                 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
8878                 if (!lockTaskPackages.isEmpty() &&
8879                         !isUserAffiliatedWithDeviceLocked(userId)) {
8880                     Slog.d(LOG_TAG,
8881                             "User id " + userId + " not affiliated. Clearing lock task packages");
8882                     setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
8883                 }
8884             }
8885         } finally {
8886             mInjector.binderRestoreCallingIdentity(ident);
8887         }
8888     }
8889
8890     @Override
8891     public String[] getLockTaskPackages(ComponentName who) {
8892         Preconditions.checkNotNull(who, "ComponentName is null");
8893
8894         final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8895         synchronized (this) {
8896             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8897             if (!isUserAffiliatedWithDeviceLocked(userHandle)) {
8898                 throw new SecurityException("Admin " + who +
8899                     " is neither the device owner or affiliated user's profile owner.");
8900             }
8901
8902             final List<String> packages = getUserData(userHandle).mLockTaskPackages;
8903             return packages.toArray(new String[packages.size()]);
8904         }
8905     }
8906
8907     @Override
8908     public boolean isLockTaskPermitted(String pkg) {
8909         final int userHandle = mInjector.userHandleGetCallingUserId();
8910         synchronized (this) {
8911             return getUserData(userHandle).mLockTaskPackages.contains(pkg);
8912         }
8913     }
8914
8915     @Override
8916     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8917         if (!isCallerWithSystemUid()) {
8918             throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8919         }
8920         synchronized (this) {
8921             final DevicePolicyData policy = getUserData(userHandle);
8922             Bundle adminExtras = new Bundle();
8923             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8924             for (ActiveAdmin admin : policy.mAdminList) {
8925                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8926                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8927                 if (ownsDevice || ownsProfile) {
8928                     if (isEnabled) {
8929                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8930                                 adminExtras, null);
8931                     } else {
8932                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8933                     }
8934                 }
8935             }
8936         }
8937     }
8938
8939     @Override
8940     public void setGlobalSetting(ComponentName who, String setting, String value) {
8941         Preconditions.checkNotNull(who, "ComponentName is null");
8942
8943         synchronized (this) {
8944             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8945
8946             // Some settings are no supported any more. However we do not want to throw a
8947             // SecurityException to avoid breaking apps.
8948             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8949                 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8950                 return;
8951             }
8952
8953             if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)
8954                     && !UserManager.isDeviceInDemoMode(mContext)) {
8955                 throw new SecurityException(String.format(
8956                         "Permission denial: device owners cannot update %1$s", setting));
8957             }
8958
8959             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8960                 // ignore if it contradicts an existing policy
8961                 long timeMs = getMaximumTimeToLock(
8962                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8963                 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8964                     return;
8965                 }
8966             }
8967
8968             long id = mInjector.binderClearCallingIdentity();
8969             try {
8970                 mInjector.settingsGlobalPutString(setting, value);
8971             } finally {
8972                 mInjector.binderRestoreCallingIdentity(id);
8973             }
8974         }
8975     }
8976
8977     @Override
8978     public void setSecureSetting(ComponentName who, String setting, String value) {
8979         Preconditions.checkNotNull(who, "ComponentName is null");
8980         int callingUserId = mInjector.userHandleGetCallingUserId();
8981
8982         synchronized (this) {
8983             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8984
8985             if (isDeviceOwner(who, callingUserId)) {
8986                 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)
8987                         && !isCurrentUserDemo()) {
8988                     throw new SecurityException(String.format(
8989                             "Permission denial: Device owners cannot update %1$s", setting));
8990                 }
8991             } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) {
8992                 throw new SecurityException(String.format(
8993                         "Permission denial: Profile owners cannot update %1$s", setting));
8994             }
8995             if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
8996                 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
8997                     throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
8998                             + " is deprecated. Please use the user restriction "
8999                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead.");
9000                 }
9001                 if (!mUserManager.isManagedProfile(callingUserId)) {
9002                     Slog.e(LOG_TAG, "Ignoring setSecureSetting request for "
9003                             + setting + ". User restriction "
9004                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
9005                             + " should be used instead.");
9006                 } else {
9007                     try {
9008                         setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
9009                                 (Integer.parseInt(value) == 0) ? true : false);
9010                     } catch (NumberFormatException exc) {
9011                         Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
9012                     }
9013                 }
9014                 return;
9015             }
9016             long id = mInjector.binderClearCallingIdentity();
9017             try {
9018                 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
9019                     final String currentValue = mInjector.settingsSecureGetStringForUser(
9020                             Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
9021                     if (!TextUtils.equals(currentValue, value)) {
9022                         // Tell the content observer that the next change will be due to the owner
9023                         // changing the value. There is a small race condition here that we cannot
9024                         // avoid: Change notifications are sent asynchronously, so it is possible
9025                         // that there are prior notifications queued up before the one we are about
9026                         // to trigger. This is a corner case that will have no impact in practice.
9027                         mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
9028                     }
9029                     getUserData(callingUserId).mCurrentInputMethodSet = true;
9030                     saveSettingsLocked(callingUserId);
9031                 }
9032                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
9033             } finally {
9034                 mInjector.binderRestoreCallingIdentity(id);
9035             }
9036         }
9037     }
9038
9039     @Override
9040     public void setMasterVolumeMuted(ComponentName who, boolean on) {
9041         Preconditions.checkNotNull(who, "ComponentName is null");
9042         synchronized (this) {
9043             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9044             setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
9045         }
9046     }
9047
9048     @Override
9049     public boolean isMasterVolumeMuted(ComponentName who) {
9050         Preconditions.checkNotNull(who, "ComponentName is null");
9051         synchronized (this) {
9052             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9053
9054             AudioManager audioManager =
9055                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
9056             return audioManager.isMasterMute();
9057         }
9058     }
9059
9060     @Override
9061     public void setUserIcon(ComponentName who, Bitmap icon) {
9062         synchronized (this) {
9063             Preconditions.checkNotNull(who, "ComponentName is null");
9064             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9065
9066             int userId = UserHandle.getCallingUserId();
9067             long id = mInjector.binderClearCallingIdentity();
9068             try {
9069                 mUserManagerInternal.setUserIcon(userId, icon);
9070             } finally {
9071                 mInjector.binderRestoreCallingIdentity(id);
9072             }
9073         }
9074     }
9075
9076     @Override
9077     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
9078         Preconditions.checkNotNull(who, "ComponentName is null");
9079         synchronized (this) {
9080             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9081         }
9082         final int userId = UserHandle.getCallingUserId();
9083
9084         long ident = mInjector.binderClearCallingIdentity();
9085         try {
9086             // disallow disabling the keyguard if a password is currently set
9087             if (disabled && mLockPatternUtils.isSecure(userId)) {
9088                 return false;
9089             }
9090             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
9091         } finally {
9092             mInjector.binderRestoreCallingIdentity(ident);
9093         }
9094         return true;
9095     }
9096
9097     @Override
9098     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
9099         int userId = UserHandle.getCallingUserId();
9100         synchronized (this) {
9101             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9102             DevicePolicyData policy = getUserData(userId);
9103             if (policy.mStatusBarDisabled != disabled) {
9104                 if (!setStatusBarDisabledInternal(disabled, userId)) {
9105                     return false;
9106                 }
9107                 policy.mStatusBarDisabled = disabled;
9108                 saveSettingsLocked(userId);
9109             }
9110         }
9111         return true;
9112     }
9113
9114     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
9115         long ident = mInjector.binderClearCallingIdentity();
9116         try {
9117             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
9118                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
9119             if (statusBarService != null) {
9120                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
9121                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
9122                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
9123                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
9124                 return true;
9125             }
9126         } catch (RemoteException e) {
9127             Slog.e(LOG_TAG, "Failed to disable the status bar", e);
9128         } finally {
9129             mInjector.binderRestoreCallingIdentity(ident);
9130         }
9131         return false;
9132     }
9133
9134     /**
9135      * We need to update the internal state of whether a user has completed setup or a
9136      * device has paired once. After that, we ignore any changes that reset the
9137      * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
9138      * as we don't trust any apps that might try to reset them.
9139      * <p>
9140      * Unfortunately, we don't know which user's setup state was changed, so we write all of
9141      * them.
9142      */
9143     void updateUserSetupCompleteAndPaired() {
9144         List<UserInfo> users = mUserManager.getUsers(true);
9145         final int N = users.size();
9146         for (int i = 0; i < N; i++) {
9147             int userHandle = users.get(i).id;
9148             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
9149                     userHandle) != 0) {
9150                 DevicePolicyData policy = getUserData(userHandle);
9151                 if (!policy.mUserSetupComplete) {
9152                     policy.mUserSetupComplete = true;
9153                     synchronized (this) {
9154                         saveSettingsLocked(userHandle);
9155                     }
9156                 }
9157             }
9158             if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
9159                     userHandle) != 0) {
9160                 DevicePolicyData policy = getUserData(userHandle);
9161                 if (!policy.mPaired) {
9162                     policy.mPaired = true;
9163                     synchronized (this) {
9164                         saveSettingsLocked(userHandle);
9165                     }
9166                 }
9167             }
9168         }
9169     }
9170
9171     private class SetupContentObserver extends ContentObserver {
9172         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
9173                 Settings.Secure.USER_SETUP_COMPLETE);
9174         private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
9175                 Settings.Global.DEVICE_PROVISIONED);
9176         private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
9177         private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
9178                 Settings.Secure.DEFAULT_INPUT_METHOD);
9179
9180         @GuardedBy("DevicePolicyManagerService.this")
9181         private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
9182
9183         public SetupContentObserver(Handler handler) {
9184             super(handler);
9185         }
9186
9187         void register() {
9188             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
9189             mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
9190             if (mIsWatch) {
9191                 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
9192             }
9193             mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
9194         }
9195
9196         private void addPendingChangeByOwnerLocked(int userId) {
9197             mUserIdsWithPendingChangesByOwner.add(userId);
9198         }
9199
9200         @Override
9201         public void onChange(boolean selfChange, Uri uri, int userId) {
9202             if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
9203                 updateUserSetupCompleteAndPaired();
9204             } else if (mDeviceProvisioned.equals(uri)) {
9205                 synchronized (DevicePolicyManagerService.this) {
9206                     // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
9207                     // is delayed until device is marked as provisioned.
9208                     setDeviceOwnerSystemPropertyLocked();
9209                 }
9210             } else if (mDefaultImeChanged.equals(uri)) {
9211                 synchronized (DevicePolicyManagerService.this) {
9212                     if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
9213                         // This change notification was triggered by the owner changing the current
9214                         // IME. Ignore it.
9215                         mUserIdsWithPendingChangesByOwner.remove(userId);
9216                     } else {
9217                         // This change notification was triggered by the user manually changing the
9218                         // current IME.
9219                         getUserData(userId).mCurrentInputMethodSet = false;
9220                         saveSettingsLocked(userId);
9221                     }
9222                 }
9223             }
9224         }
9225     }
9226
9227     @VisibleForTesting
9228     final class LocalService extends DevicePolicyManagerInternal {
9229         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
9230
9231         @Override
9232         public List<String> getCrossProfileWidgetProviders(int profileId) {
9233             synchronized (DevicePolicyManagerService.this) {
9234                 if (mOwners == null) {
9235                     return Collections.emptyList();
9236                 }
9237                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
9238                 if (ownerComponent == null) {
9239                     return Collections.emptyList();
9240                 }
9241
9242                 DevicePolicyData policy = getUserDataUnchecked(profileId);
9243                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
9244
9245                 if (admin == null || admin.crossProfileWidgetProviders == null
9246                         || admin.crossProfileWidgetProviders.isEmpty()) {
9247                     return Collections.emptyList();
9248                 }
9249
9250                 return admin.crossProfileWidgetProviders;
9251             }
9252         }
9253
9254         @Override
9255         public void addOnCrossProfileWidgetProvidersChangeListener(
9256                 OnCrossProfileWidgetProvidersChangeListener listener) {
9257             synchronized (DevicePolicyManagerService.this) {
9258                 if (mWidgetProviderListeners == null) {
9259                     mWidgetProviderListeners = new ArrayList<>();
9260                 }
9261                 if (!mWidgetProviderListeners.contains(listener)) {
9262                     mWidgetProviderListeners.add(listener);
9263                 }
9264             }
9265         }
9266
9267         @Override
9268         public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
9269             synchronized(DevicePolicyManagerService.this) {
9270                 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
9271             }
9272         }
9273
9274         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
9275             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
9276             synchronized (DevicePolicyManagerService.this) {
9277                 listeners = new ArrayList<>(mWidgetProviderListeners);
9278             }
9279             final int listenerCount = listeners.size();
9280             for (int i = 0; i < listenerCount; i++) {
9281                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
9282                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
9283             }
9284         }
9285
9286         @Override
9287         public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
9288             // This method is called from AM with its lock held, so don't take the DPMS lock.
9289             // b/29242568
9290
9291             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9292             if (profileOwner != null) {
9293                 return DevicePolicyManagerService.this
9294                         .createShowAdminSupportIntent(profileOwner, userId);
9295             }
9296
9297             final Pair<Integer, ComponentName> deviceOwner =
9298                     mOwners.getDeviceOwnerUserIdAndComponent();
9299             if (deviceOwner != null && deviceOwner.first == userId) {
9300                 return DevicePolicyManagerService.this
9301                         .createShowAdminSupportIntent(deviceOwner.second, userId);
9302             }
9303
9304             // We're not specifying the device admin because there isn't one.
9305             if (useDefaultIfNoAdmin) {
9306                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9307             }
9308             return null;
9309         }
9310
9311         @Override
9312         public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
9313             int source;
9314             long ident = mInjector.binderClearCallingIdentity();
9315             try {
9316                 source = mUserManager.getUserRestrictionSource(userRestriction,
9317                         UserHandle.of(userId));
9318             } finally {
9319                 mInjector.binderRestoreCallingIdentity(ident);
9320             }
9321             if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
9322                 /*
9323                  * In this case, the user restriction is enforced by the system.
9324                  * So we won't show an admin support intent, even if it is also
9325                  * enforced by a profile/device owner.
9326                  */
9327                 return null;
9328             }
9329             boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
9330             boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
9331             if (enforcedByDo && enforcedByPo) {
9332                 // In this case, we'll show an admin support dialog that does not
9333                 // specify the admin.
9334                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9335             } else if (enforcedByPo) {
9336                 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9337                 if (profileOwner != null) {
9338                     return DevicePolicyManagerService.this
9339                             .createShowAdminSupportIntent(profileOwner, userId);
9340                 }
9341                 // This could happen if another thread has changed the profile owner since we called
9342                 // getUserRestrictionSource
9343                 return null;
9344             } else if (enforcedByDo) {
9345                 final Pair<Integer, ComponentName> deviceOwner
9346                         = mOwners.getDeviceOwnerUserIdAndComponent();
9347                 if (deviceOwner != null) {
9348                     return DevicePolicyManagerService.this
9349                             .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
9350                 }
9351                 // This could happen if another thread has changed the device owner since we called
9352                 // getUserRestrictionSource
9353                 return null;
9354             }
9355             return null;
9356         }
9357     }
9358
9359     private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
9360         // This method is called with AMS lock held, so don't take DPMS lock
9361         final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
9362         intent.putExtra(Intent.EXTRA_USER_ID, userId);
9363         intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
9364         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9365         return intent;
9366     }
9367
9368     @Override
9369     public Intent createAdminSupportIntent(String restriction) {
9370         Preconditions.checkNotNull(restriction);
9371         final int uid = mInjector.binderGetCallingUid();
9372         final int userId = UserHandle.getUserId(uid);
9373         Intent intent = null;
9374         if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
9375                 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
9376             synchronized(this) {
9377                 final DevicePolicyData policy = getUserData(userId);
9378                 final int N = policy.mAdminList.size();
9379                 for (int i = 0; i < N; i++) {
9380                     final ActiveAdmin admin = policy.mAdminList.get(i);
9381                     if ((admin.disableCamera &&
9382                                 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
9383                         (admin.disableScreenCapture && DevicePolicyManager
9384                                 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) {
9385                         intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
9386                         break;
9387                     }
9388                 }
9389                 // For the camera, a device owner on a different user can disable it globally,
9390                 // so we need an additional check.
9391                 if (intent == null
9392                         && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
9393                     final ActiveAdmin admin = getDeviceOwnerAdminLocked();
9394                     if (admin != null && admin.disableCamera) {
9395                         intent = createShowAdminSupportIntent(admin.info.getComponent(),
9396                                 mOwners.getDeviceOwnerUserId());
9397                     }
9398                 }
9399             }
9400         } else {
9401             // if valid, |restriction| can only be a user restriction
9402             intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
9403         }
9404         if (intent != null) {
9405             intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
9406         }
9407         return intent;
9408     }
9409
9410     /**
9411      * Returns true if specified admin is allowed to limit passwords and has a
9412      * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
9413      */
9414     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
9415         if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
9416             return false;
9417         }
9418         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
9419     }
9420
9421     @Override
9422     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
9423         if (policy != null && !policy.isValid()) {
9424             throw new IllegalArgumentException("Invalid system update policy.");
9425         }
9426         synchronized (this) {
9427             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9428             if (policy == null) {
9429                 mOwners.clearSystemUpdatePolicy();
9430             } else {
9431                 mOwners.setSystemUpdatePolicy(policy);
9432             }
9433             mOwners.writeDeviceOwner();
9434         }
9435         mContext.sendBroadcastAsUser(
9436                 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
9437                 UserHandle.SYSTEM);
9438     }
9439
9440     @Override
9441     public SystemUpdatePolicy getSystemUpdatePolicy() {
9442         synchronized (this) {
9443             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
9444             if (policy != null && !policy.isValid()) {
9445                 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
9446                 return null;
9447             }
9448             return policy;
9449         }
9450     }
9451
9452     /**
9453      * Checks if the caller of the method is the device owner app.
9454      *
9455      * @param callerUid UID of the caller.
9456      * @return true if the caller is the device owner app
9457      */
9458     @VisibleForTesting
9459     boolean isCallerDeviceOwner(int callerUid) {
9460         synchronized (this) {
9461             if (!mOwners.hasDeviceOwner()) {
9462                 return false;
9463             }
9464             if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
9465                 return false;
9466             }
9467             final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
9468                     .getPackageName();
9469                 try {
9470                     String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid);
9471                     for (String pkg : pkgs) {
9472                         if (deviceOwnerPackageName.equals(pkg)) {
9473                             return true;
9474                         }
9475                     }
9476                 } catch (RemoteException e) {
9477                     return false;
9478                 }
9479         }
9480
9481         return false;
9482     }
9483
9484     @Override
9485     public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
9486         mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
9487                 "Only the system update service can broadcast update information");
9488
9489         if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
9490             Slog.w(LOG_TAG, "Only the system update service in the system user " +
9491                     "can broadcast update information.");
9492             return;
9493         }
9494
9495         if (!mOwners.saveSystemUpdateInfo(info)) {
9496             // Pending system update hasn't changed, don't send duplicate notification.
9497             return;
9498         }
9499
9500         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
9501                 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
9502                         info == null ? -1 : info.getReceivedTime());
9503
9504         final long ident = mInjector.binderClearCallingIdentity();
9505         try {
9506             synchronized (this) {
9507                 // Broadcast to device owner first if there is one.
9508                 if (mOwners.hasDeviceOwner()) {
9509                     final UserHandle deviceOwnerUser =
9510                             UserHandle.of(mOwners.getDeviceOwnerUserId());
9511                     intent.setComponent(mOwners.getDeviceOwnerComponent());
9512                     mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
9513                 }
9514             }
9515             // Get running users.
9516             final int runningUserIds[];
9517             try {
9518                 runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
9519             } catch (RemoteException e) {
9520                 // Shouldn't happen.
9521                 Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
9522                 return;
9523             }
9524             // Send broadcasts to corresponding profile owners if any.
9525             for (final int userId : runningUserIds) {
9526                 synchronized (this) {
9527                     final ComponentName profileOwnerPackage =
9528                             mOwners.getProfileOwnerComponent(userId);
9529                     if (profileOwnerPackage != null) {
9530                         intent.setComponent(profileOwnerPackage);
9531                         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9532                     }
9533                 }
9534             }
9535         } finally {
9536             mInjector.binderRestoreCallingIdentity(ident);
9537         }
9538     }
9539
9540     @Override
9541     public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
9542         Preconditions.checkNotNull(admin, "ComponentName is null");
9543         enforceProfileOrDeviceOwner(admin);
9544
9545         return mOwners.getSystemUpdateInfo();
9546     }
9547
9548     @Override
9549     public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
9550             throws RemoteException {
9551         int userId = UserHandle.getCallingUserId();
9552         synchronized (this) {
9553             // Ensure the caller is a DO/PO or a permission grant state delegate.
9554             enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9555                     DELEGATION_PERMISSION_GRANT);
9556             DevicePolicyData userPolicy = getUserData(userId);
9557             if (userPolicy.mPermissionPolicy != policy) {
9558                 userPolicy.mPermissionPolicy = policy;
9559                 saveSettingsLocked(userId);
9560             }
9561         }
9562     }
9563
9564     @Override
9565     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
9566         int userId = UserHandle.getCallingUserId();
9567         synchronized (this) {
9568             DevicePolicyData userPolicy = getUserData(userId);
9569             return userPolicy.mPermissionPolicy;
9570         }
9571     }
9572
9573     @Override
9574     public boolean setPermissionGrantState(ComponentName admin, String callerPackage,
9575             String packageName, String permission, int grantState) throws RemoteException {
9576         UserHandle user = mInjector.binderGetCallingUserHandle();
9577         synchronized (this) {
9578             // Ensure the caller is a DO/PO or a permission grant state delegate.
9579             enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9580                     DELEGATION_PERMISSION_GRANT);
9581             long ident = mInjector.binderClearCallingIdentity();
9582             try {
9583                 if (getTargetSdk(packageName, user.getIdentifier())
9584                         < android.os.Build.VERSION_CODES.M) {
9585                     return false;
9586                 }
9587                 if (!isRuntimePermission(permission)) {
9588                     EventLog.writeEvent(0x534e4554, "62623498", user.getIdentifier(), "");
9589                     return false;
9590                 }
9591                 final PackageManager packageManager = mInjector.getPackageManager();
9592                 switch (grantState) {
9593                     case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
9594                         mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
9595                                 permission, user.getIdentifier(), true /* override policy */);
9596                         packageManager.updatePermissionFlags(permission, packageName,
9597                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9598                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9599                     } break;
9600
9601                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
9602                         mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
9603                                 permission, user.getIdentifier(), true /* override policy */);
9604                         packageManager.updatePermissionFlags(permission, packageName,
9605                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9606                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9607                     } break;
9608
9609                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
9610                         packageManager.updatePermissionFlags(permission, packageName,
9611                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
9612                     } break;
9613                 }
9614                 return true;
9615             } catch (SecurityException se) {
9616                 return false;
9617             } catch (NameNotFoundException e) {
9618                 return false;
9619             } finally {
9620                 mInjector.binderRestoreCallingIdentity(ident);
9621             }
9622         }
9623     }
9624
9625     @Override
9626     public int getPermissionGrantState(ComponentName admin, String callerPackage,
9627             String packageName, String permission) throws RemoteException {
9628         PackageManager packageManager = mInjector.getPackageManager();
9629
9630         UserHandle user = mInjector.binderGetCallingUserHandle();
9631         if (!isCallerWithSystemUid()) {
9632             // Ensure the caller is a DO/PO or a permission grant state delegate.
9633             enforceCanManageScope(admin, callerPackage,
9634                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT);
9635         }
9636         synchronized (this) {
9637             long ident = mInjector.binderClearCallingIdentity();
9638             try {
9639                 int granted = mIPackageManager.checkPermission(permission,
9640                         packageName, user.getIdentifier());
9641                 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
9642                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
9643                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
9644                     // Not controlled by policy
9645                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
9646                 } else {
9647                     // Policy controlled so return result based on permission grant state
9648                     return granted == PackageManager.PERMISSION_GRANTED
9649                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
9650                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
9651                 }
9652             } finally {
9653                 mInjector.binderRestoreCallingIdentity(ident);
9654             }
9655         }
9656     }
9657
9658     boolean isPackageInstalledForUser(String packageName, int userHandle) {
9659         try {
9660             PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
9661                     userHandle);
9662             return (pi != null) && (pi.applicationInfo.flags != 0);
9663         } catch (RemoteException re) {
9664             throw new RuntimeException("Package manager has died", re);
9665         }
9666     }
9667
9668     public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
9669         final PackageManager packageManager = mInjector.getPackageManager();
9670         PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
9671         return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
9672                 == PermissionInfo.PROTECTION_DANGEROUS;
9673     }
9674
9675     @Override
9676     public boolean isProvisioningAllowed(String action, String packageName) {
9677         Preconditions.checkNotNull(packageName);
9678
9679         final int callingUid = mInjector.binderGetCallingUid();
9680         final long ident = mInjector.binderClearCallingIdentity();
9681         try {
9682             final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
9683                     packageName, UserHandle.getUserId(callingUid));
9684             Preconditions.checkArgument(callingUid == uidForPackage,
9685                     "Caller uid doesn't match the one for the provided package.");
9686         } catch (NameNotFoundException e) {
9687             throw new IllegalArgumentException("Invalid package provided " + packageName, e);
9688         } finally {
9689             mInjector.binderRestoreCallingIdentity(ident);
9690         }
9691
9692         return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
9693     }
9694
9695     @Override
9696     public int checkProvisioningPreCondition(String action, String packageName) {
9697         Preconditions.checkNotNull(packageName);
9698         enforceCanManageProfileAndDeviceOwners();
9699         return checkProvisioningPreConditionSkipPermission(action, packageName);
9700     }
9701
9702     private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
9703         if (!mHasFeature) {
9704             return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
9705         }
9706
9707         final int callingUserId = mInjector.userHandleGetCallingUserId();
9708         if (action != null) {
9709             switch (action) {
9710                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
9711                     return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
9712                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
9713                     return checkDeviceOwnerProvisioningPreCondition(callingUserId);
9714                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
9715                     return checkManagedUserProvisioningPreCondition(callingUserId);
9716                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
9717                     return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
9718             }
9719         }
9720         throw new IllegalArgumentException("Unknown provisioning action " + action);
9721     }
9722
9723     /**
9724      * The device owner can only be set before the setup phase of the primary user has completed,
9725      * except for adb command if no accounts or additional users are present on the device.
9726      */
9727     private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
9728             int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
9729         if (mOwners.hasDeviceOwner()) {
9730             return CODE_HAS_DEVICE_OWNER;
9731         }
9732         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
9733             return CODE_USER_HAS_PROFILE_OWNER;
9734         }
9735         if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
9736             return CODE_USER_NOT_RUNNING;
9737         }
9738         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
9739             return CODE_HAS_PAIRED;
9740         }
9741         if (isAdb) {
9742             // if shell command runs after user setup completed check device status. Otherwise, OK.
9743             if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
9744                 if (!mInjector.userManagerIsSplitSystemUser()) {
9745                     if (mUserManager.getUserCount() > 1) {
9746                         return CODE_NONSYSTEM_USER_EXISTS;
9747                     }
9748                     if (hasIncompatibleAccountsOrNonAdb) {
9749                         return CODE_ACCOUNTS_NOT_EMPTY;
9750                     }
9751                 } else {
9752                     // STOPSHIP Do proper check in split user mode
9753                 }
9754             }
9755             return CODE_OK;
9756         } else {
9757             if (!mInjector.userManagerIsSplitSystemUser()) {
9758                 // In non-split user mode, DO has to be user 0
9759                 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
9760                     return CODE_NOT_SYSTEM_USER;
9761                 }
9762                 // In non-split user mode, only provision DO before setup wizard completes
9763                 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
9764                     return CODE_USER_SETUP_COMPLETED;
9765                 }
9766             } else {
9767                 // STOPSHIP Do proper check in split user mode
9768             }
9769             return CODE_OK;
9770         }
9771     }
9772
9773     private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
9774         synchronized (this) {
9775             // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
9776             return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
9777                     deviceOwnerUserId, /* isAdb= */ false,
9778                     /* hasIncompatibleAccountsOrNonAdb=*/ true);
9779         }
9780     }
9781
9782     private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
9783         if (!hasFeatureManagedUsers()) {
9784             return CODE_MANAGED_USERS_NOT_SUPPORTED;
9785         }
9786         if (callingUserId == UserHandle.USER_SYSTEM
9787                 && mInjector.userManagerIsSplitSystemUser()) {
9788             // Managed-profiles cannot be setup on the system user.
9789             return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
9790         }
9791         if (getProfileOwner(callingUserId) != null) {
9792             // Managed user cannot have a managed profile.
9793             return CODE_USER_HAS_PROFILE_OWNER;
9794         }
9795
9796         final long ident = mInjector.binderClearCallingIdentity();
9797         try {
9798             final UserHandle callingUserHandle = UserHandle.of(callingUserId);
9799             final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
9800             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
9801                     callingUserHandle)) {
9802                 // An admin can initiate provisioning if it has set the restriction.
9803                 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
9804                         UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
9805                     return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
9806                 }
9807             }
9808             boolean canRemoveProfile = true;
9809             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
9810                     callingUserHandle)) {
9811                 // We can remove a profile if the admin itself has set the restriction.
9812                 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
9813                         UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
9814                         callingUserId)) {
9815                     canRemoveProfile = false;
9816                 }
9817             }
9818             if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
9819                 return CODE_CANNOT_ADD_MANAGED_PROFILE;
9820             }
9821         } finally {
9822             mInjector.binderRestoreCallingIdentity(ident);
9823         }
9824         return CODE_OK;
9825     }
9826
9827     private ComponentName getOwnerComponent(String packageName, int userId) {
9828         if (isDeviceOwnerPackage(packageName, userId)) {
9829             return mOwners.getDeviceOwnerComponent();
9830         }
9831         if (isProfileOwnerPackage(packageName, userId)) {
9832             return mOwners.getProfileOwnerComponent(userId);
9833         }
9834         return null;
9835     }
9836
9837     /**
9838      * Return device owner or profile owner set on a given user.
9839      */
9840     private @Nullable ComponentName getOwnerComponent(int userId) {
9841         synchronized (this) {
9842             if (mOwners.getDeviceOwnerUserId() == userId) {
9843                 return mOwners.getDeviceOwnerComponent();
9844             }
9845             if (mOwners.hasProfileOwner(userId)) {
9846                 return mOwners.getProfileOwnerComponent(userId);
9847             }
9848         }
9849         return null;
9850     }
9851
9852     private int checkManagedUserProvisioningPreCondition(int callingUserId) {
9853         if (!hasFeatureManagedUsers()) {
9854             return CODE_MANAGED_USERS_NOT_SUPPORTED;
9855         }
9856         if (!mInjector.userManagerIsSplitSystemUser()) {
9857             // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
9858             return CODE_NOT_SYSTEM_USER_SPLIT;
9859         }
9860         if (callingUserId == UserHandle.USER_SYSTEM) {
9861             // System user cannot be a managed user.
9862             return CODE_SYSTEM_USER;
9863         }
9864         if (hasUserSetupCompleted(callingUserId)) {
9865             return CODE_USER_SETUP_COMPLETED;
9866         }
9867         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
9868             return CODE_HAS_PAIRED;
9869         }
9870         return CODE_OK;
9871     }
9872
9873     private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
9874         if (!mInjector.userManagerIsSplitSystemUser()) {
9875             // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
9876             return CODE_NOT_SYSTEM_USER_SPLIT;
9877         }
9878         return checkDeviceOwnerProvisioningPreCondition(callingUserId);
9879     }
9880
9881     private boolean hasFeatureManagedUsers() {
9882         try {
9883             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
9884         } catch (RemoteException e) {
9885             return false;
9886         }
9887     }
9888
9889     @Override
9890     public String getWifiMacAddress(ComponentName admin) {
9891         // Make sure caller has DO.
9892         synchronized (this) {
9893             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9894         }
9895
9896         final long ident = mInjector.binderClearCallingIdentity();
9897         try {
9898             final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
9899             if (wifiInfo == null) {
9900                 return null;
9901             }
9902             return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
9903         } finally {
9904             mInjector.binderRestoreCallingIdentity(ident);
9905         }
9906     }
9907
9908     /**
9909      * Returns the target sdk version number that the given packageName was built for
9910      * in the given user.
9911      */
9912     private int getTargetSdk(String packageName, int userId) {
9913         final ApplicationInfo ai;
9914         try {
9915             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
9916             final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
9917             return targetSdkVersion;
9918         } catch (RemoteException e) {
9919             // Shouldn't happen
9920             return 0;
9921         }
9922     }
9923
9924     @Override
9925     public boolean isManagedProfile(ComponentName admin) {
9926         enforceProfileOrDeviceOwner(admin);
9927         return isManagedProfile(mInjector.userHandleGetCallingUserId());
9928     }
9929
9930     @Override
9931     public boolean isSystemOnlyUser(ComponentName admin) {
9932         synchronized (this) {
9933             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9934         }
9935         final int callingUserId = mInjector.userHandleGetCallingUserId();
9936         return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
9937     }
9938
9939     @Override
9940     public void reboot(ComponentName admin) {
9941         Preconditions.checkNotNull(admin);
9942         // Make sure caller has DO.
9943         synchronized (this) {
9944             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9945         }
9946         long ident = mInjector.binderClearCallingIdentity();
9947         try {
9948             // Make sure there are no ongoing calls on the device.
9949             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
9950                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
9951             }
9952             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
9953         } finally {
9954             mInjector.binderRestoreCallingIdentity(ident);
9955         }
9956     }
9957
9958     @Override
9959     public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
9960         if (!mHasFeature) {
9961             return;
9962         }
9963         Preconditions.checkNotNull(who, "ComponentName is null");
9964         final int userHandle = mInjector.userHandleGetCallingUserId();
9965         synchronized (this) {
9966             ActiveAdmin admin = getActiveAdminForUidLocked(who,
9967                     mInjector.binderGetCallingUid());
9968             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
9969                 admin.shortSupportMessage = message;
9970                 saveSettingsLocked(userHandle);
9971             }
9972         }
9973     }
9974
9975     @Override
9976     public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
9977         if (!mHasFeature) {
9978             return null;
9979         }
9980         Preconditions.checkNotNull(who, "ComponentName is null");
9981         synchronized (this) {
9982             ActiveAdmin admin = getActiveAdminForUidLocked(who,
9983                     mInjector.binderGetCallingUid());
9984             return admin.shortSupportMessage;
9985         }
9986     }
9987
9988     @Override
9989     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
9990         if (!mHasFeature) {
9991             return;
9992         }
9993         Preconditions.checkNotNull(who, "ComponentName is null");
9994         final int userHandle = mInjector.userHandleGetCallingUserId();
9995         synchronized (this) {
9996             ActiveAdmin admin = getActiveAdminForUidLocked(who,
9997                     mInjector.binderGetCallingUid());
9998             if (!TextUtils.equals(admin.longSupportMessage, message)) {
9999                 admin.longSupportMessage = message;
10000                 saveSettingsLocked(userHandle);
10001             }
10002         }
10003     }
10004
10005     @Override
10006     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
10007         if (!mHasFeature) {
10008             return null;
10009         }
10010         Preconditions.checkNotNull(who, "ComponentName is null");
10011         synchronized (this) {
10012             ActiveAdmin admin = getActiveAdminForUidLocked(who,
10013                     mInjector.binderGetCallingUid());
10014             return admin.longSupportMessage;
10015         }
10016     }
10017
10018     @Override
10019     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
10020         if (!mHasFeature) {
10021             return null;
10022         }
10023         Preconditions.checkNotNull(who, "ComponentName is null");
10024         if (!isCallerWithSystemUid()) {
10025             throw new SecurityException("Only the system can query support message for user");
10026         }
10027         synchronized (this) {
10028             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10029             if (admin != null) {
10030                 return admin.shortSupportMessage;
10031             }
10032         }
10033         return null;
10034     }
10035
10036     @Override
10037     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
10038         if (!mHasFeature) {
10039             return null;
10040         }
10041         Preconditions.checkNotNull(who, "ComponentName is null");
10042         if (!isCallerWithSystemUid()) {
10043             throw new SecurityException("Only the system can query support message for user");
10044         }
10045         synchronized (this) {
10046             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10047             if (admin != null) {
10048                 return admin.longSupportMessage;
10049             }
10050         }
10051         return null;
10052     }
10053
10054     @Override
10055     public void setOrganizationColor(@NonNull ComponentName who, int color) {
10056         if (!mHasFeature) {
10057             return;
10058         }
10059         Preconditions.checkNotNull(who, "ComponentName is null");
10060         final int userHandle = mInjector.userHandleGetCallingUserId();
10061         enforceManagedProfile(userHandle, "set organization color");
10062         synchronized (this) {
10063             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10064                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10065             admin.organizationColor = color;
10066             saveSettingsLocked(userHandle);
10067         }
10068     }
10069
10070     @Override
10071     public void setOrganizationColorForUser(int color, int userId) {
10072         if (!mHasFeature) {
10073             return;
10074         }
10075         enforceFullCrossUsersPermission(userId);
10076         enforceManageUsers();
10077         enforceManagedProfile(userId, "set organization color");
10078         synchronized (this) {
10079             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
10080             admin.organizationColor = color;
10081             saveSettingsLocked(userId);
10082         }
10083     }
10084
10085     @Override
10086     public int getOrganizationColor(@NonNull ComponentName who) {
10087         if (!mHasFeature) {
10088             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
10089         }
10090         Preconditions.checkNotNull(who, "ComponentName is null");
10091         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
10092         synchronized (this) {
10093             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10094                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10095             return admin.organizationColor;
10096         }
10097     }
10098
10099     @Override
10100     public int getOrganizationColorForUser(int userHandle) {
10101         if (!mHasFeature) {
10102             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
10103         }
10104         enforceFullCrossUsersPermission(userHandle);
10105         enforceManagedProfile(userHandle, "get organization color");
10106         synchronized (this) {
10107             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
10108             return (profileOwner != null)
10109                     ? profileOwner.organizationColor
10110                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
10111         }
10112     }
10113
10114     @Override
10115     public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
10116         if (!mHasFeature) {
10117             return;
10118         }
10119         Preconditions.checkNotNull(who, "ComponentName is null");
10120         final int userHandle = mInjector.userHandleGetCallingUserId();
10121
10122         synchronized (this) {
10123             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10124                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10125             if (!TextUtils.equals(admin.organizationName, text)) {
10126                 admin.organizationName = (text == null || text.length() == 0)
10127                         ? null : text.toString();
10128                 saveSettingsLocked(userHandle);
10129             }
10130         }
10131     }
10132
10133     @Override
10134     public CharSequence getOrganizationName(@NonNull ComponentName who) {
10135         if (!mHasFeature) {
10136             return null;
10137         }
10138         Preconditions.checkNotNull(who, "ComponentName is null");
10139         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
10140         synchronized(this) {
10141             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10142                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10143             return admin.organizationName;
10144         }
10145     }
10146
10147     @Override
10148     public CharSequence getDeviceOwnerOrganizationName() {
10149         if (!mHasFeature) {
10150             return null;
10151         }
10152         enforceDeviceOwnerOrManageUsers();
10153         synchronized(this) {
10154             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
10155             return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
10156         }
10157     }
10158
10159     @Override
10160     public CharSequence getOrganizationNameForUser(int userHandle) {
10161         if (!mHasFeature) {
10162             return null;
10163         }
10164         enforceFullCrossUsersPermission(userHandle);
10165         enforceManagedProfile(userHandle, "get organization name");
10166         synchronized (this) {
10167             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
10168             return (profileOwner != null)
10169                     ? profileOwner.organizationName
10170                     : null;
10171         }
10172     }
10173
10174     @Override
10175     public void setAffiliationIds(ComponentName admin, List<String> ids) {
10176         if (!mHasFeature) {
10177             return;
10178         }
10179         if (ids == null) {
10180             throw new IllegalArgumentException("ids must not be null");
10181         }
10182         for (String id : ids) {
10183             if (TextUtils.isEmpty(id)) {
10184                 throw new IllegalArgumentException("ids must not contain empty string");
10185             }
10186         }
10187
10188         final Set<String> affiliationIds = new ArraySet<>(ids);
10189         final int callingUserId = mInjector.userHandleGetCallingUserId();
10190         synchronized (this) {
10191             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10192             getUserData(callingUserId).mAffiliationIds = affiliationIds;
10193             saveSettingsLocked(callingUserId);
10194             if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
10195                 // Affiliation ids specified by the device owner are additionally stored in
10196                 // UserHandle.USER_SYSTEM's DevicePolicyData.
10197                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
10198                 saveSettingsLocked(UserHandle.USER_SYSTEM);
10199             }
10200
10201             // Affiliation status for any user, not just the calling user, might have changed.
10202             // The device owner user will still be affiliated after changing its affiliation ids,
10203             // but as a result of that other users might become affiliated or un-affiliated.
10204             maybePauseDeviceWideLoggingLocked();
10205             maybeResumeDeviceWideLoggingLocked();
10206             maybeClearLockTaskPackagesLocked();
10207         }
10208     }
10209
10210     @Override
10211     public List<String> getAffiliationIds(ComponentName admin) {
10212         if (!mHasFeature) {
10213             return Collections.emptyList();
10214         }
10215
10216         Preconditions.checkNotNull(admin);
10217         synchronized (this) {
10218             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10219             return new ArrayList<String>(
10220                     getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
10221         }
10222     }
10223
10224     @Override
10225     public boolean isAffiliatedUser() {
10226         if (!mHasFeature) {
10227             return false;
10228         }
10229
10230         synchronized (this) {
10231             return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
10232         }
10233     }
10234
10235     private boolean isUserAffiliatedWithDeviceLocked(int userId) {
10236         if (!mOwners.hasDeviceOwner()) {
10237             return false;
10238         }
10239         if (userId == mOwners.getDeviceOwnerUserId()) {
10240             // The user that the DO is installed on is always affiliated with the device.
10241             return true;
10242         }
10243         if (userId == UserHandle.USER_SYSTEM) {
10244             // The system user is always affiliated in a DO device, even if the DO is set on a
10245             // different user. This could be the case if the DO is set in the primary user
10246             // of a split user device.
10247             return true;
10248         }
10249         final ComponentName profileOwner = getProfileOwner(userId);
10250         if (profileOwner == null) {
10251             return false;
10252         }
10253         final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
10254         final Set<String> deviceAffiliationIds =
10255                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
10256         for (String id : userAffiliationIds) {
10257             if (deviceAffiliationIds.contains(id)) {
10258                 return true;
10259             }
10260         }
10261         return false;
10262     }
10263
10264     private boolean areAllUsersAffiliatedWithDeviceLocked() {
10265         final long ident = mInjector.binderClearCallingIdentity();
10266         try {
10267             final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
10268             for (int i = 0; i < userInfos.size(); i++) {
10269                 int userId = userInfos.get(i).id;
10270                 if (!isUserAffiliatedWithDeviceLocked(userId)) {
10271                     Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
10272                     return false;
10273                 }
10274             }
10275         } finally {
10276             mInjector.binderRestoreCallingIdentity(ident);
10277         }
10278
10279         return true;
10280     }
10281
10282     @Override
10283     public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
10284         if (!mHasFeature) {
10285             return;
10286         }
10287         Preconditions.checkNotNull(admin);
10288
10289         synchronized (this) {
10290             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10291             if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
10292                 return;
10293             }
10294             mInjector.securityLogSetLoggingEnabledProperty(enabled);
10295             if (enabled) {
10296                 mSecurityLogMonitor.start();
10297                 maybePauseDeviceWideLoggingLocked();
10298             } else {
10299                 mSecurityLogMonitor.stop();
10300             }
10301         }
10302     }
10303
10304     @Override
10305     public boolean isSecurityLoggingEnabled(ComponentName admin) {
10306         if (!mHasFeature) {
10307             return false;
10308         }
10309
10310         synchronized (this) {
10311             if (!isCallerWithSystemUid()) {
10312                 Preconditions.checkNotNull(admin);
10313                 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10314             }
10315             return mInjector.securityLogGetLoggingEnabledProperty();
10316         }
10317     }
10318
10319     private synchronized void recordSecurityLogRetrievalTime() {
10320         final long currentTime = System.currentTimeMillis();
10321         DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
10322         if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
10323             policyData.mLastSecurityLogRetrievalTime = currentTime;
10324             saveSettingsLocked(UserHandle.USER_SYSTEM);
10325         }
10326     }
10327
10328     @Override
10329     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
10330         if (!mHasFeature) {
10331             return null;
10332         }
10333
10334         Preconditions.checkNotNull(admin);
10335         ensureDeviceOwnerAndAllUsersAffiliated(admin);
10336
10337         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
10338                 || !mInjector.securityLogGetLoggingEnabledProperty()) {
10339             return null;
10340         }
10341
10342         recordSecurityLogRetrievalTime();
10343
10344         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
10345         try {
10346             SecurityLog.readPreviousEvents(output);
10347             return new ParceledListSlice<SecurityEvent>(output);
10348         } catch (IOException e) {
10349             Slog.w(LOG_TAG, "Fail to read previous events" , e);
10350             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
10351         }
10352     }
10353
10354     @Override
10355     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
10356         if (!mHasFeature) {
10357             return null;
10358         }
10359
10360         Preconditions.checkNotNull(admin);
10361         ensureDeviceOwnerAndAllUsersAffiliated(admin);
10362
10363         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
10364             return null;
10365         }
10366
10367         recordSecurityLogRetrievalTime();
10368
10369         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
10370         return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
10371     }
10372
10373     private void enforceCanManageDeviceAdmin() {
10374         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
10375                 null);
10376     }
10377
10378     private void enforceCanManageProfileAndDeviceOwners() {
10379         mContext.enforceCallingOrSelfPermission(
10380                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
10381     }
10382
10383     private void enforceCallerSystemUserHandle() {
10384         final int callingUid = mInjector.binderGetCallingUid();
10385         final int userId = UserHandle.getUserId(callingUid);
10386         if (userId != UserHandle.USER_SYSTEM) {
10387             throw new SecurityException("Caller has to be in user 0");
10388         }
10389     }
10390
10391     @Override
10392     public boolean isUninstallInQueue(final String packageName) {
10393         enforceCanManageDeviceAdmin();
10394         final int userId = mInjector.userHandleGetCallingUserId();
10395         Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10396         synchronized (this) {
10397             return mPackagesToRemove.contains(packageUserPair);
10398         }
10399     }
10400
10401     @Override
10402     public void uninstallPackageWithActiveAdmins(final String packageName) {
10403         enforceCanManageDeviceAdmin();
10404         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
10405
10406         final int userId = mInjector.userHandleGetCallingUserId();
10407
10408         enforceUserUnlocked(userId);
10409
10410         final ComponentName profileOwner = getProfileOwner(userId);
10411         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
10412             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
10413         }
10414
10415         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
10416         if (getDeviceOwnerUserId() == userId && deviceOwner != null
10417                 && packageName.equals(deviceOwner.getPackageName())) {
10418             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
10419         }
10420
10421         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10422         synchronized (this) {
10423             mPackagesToRemove.add(packageUserPair);
10424         }
10425
10426         // All active admins on the user.
10427         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
10428
10429         // Active admins in the target package.
10430         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
10431         if (allActiveAdmins != null) {
10432             for (ComponentName activeAdmin : allActiveAdmins) {
10433                 if (packageName.equals(activeAdmin.getPackageName())) {
10434                     packageActiveAdmins.add(activeAdmin);
10435                     removeActiveAdmin(activeAdmin, userId);
10436                 }
10437             }
10438         }
10439         if (packageActiveAdmins.size() == 0) {
10440             startUninstallIntent(packageName, userId);
10441         } else {
10442             mHandler.postDelayed(new Runnable() {
10443                 @Override
10444                 public void run() {
10445                     for (ComponentName activeAdmin : packageActiveAdmins) {
10446                         removeAdminArtifacts(activeAdmin, userId);
10447                     }
10448                     startUninstallIntent(packageName, userId);
10449                 }
10450             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
10451         }
10452     }
10453
10454     @Override
10455     public boolean isDeviceProvisioned() {
10456         synchronized (this) {
10457             return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
10458         }
10459     }
10460
10461     private boolean isCurrentUserDemo() {
10462         if (UserManager.isDeviceInDemoMode(mContext)) {
10463             final int userId = mInjector.userHandleGetCallingUserId();
10464             final long callingIdentity = mInjector.binderClearCallingIdentity();
10465             try {
10466                 return mUserManager.getUserInfo(userId).isDemo();
10467             } finally {
10468                 mInjector.binderRestoreCallingIdentity(callingIdentity);
10469             }
10470         }
10471         return false;
10472     }
10473
10474     private void removePackageIfRequired(final String packageName, final int userId) {
10475         if (!packageHasActiveAdmins(packageName, userId)) {
10476             // Will not do anything if uninstall was not requested or was already started.
10477             startUninstallIntent(packageName, userId);
10478         }
10479     }
10480
10481     private void startUninstallIntent(final String packageName, final int userId) {
10482         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10483         synchronized (this) {
10484             if (!mPackagesToRemove.contains(packageUserPair)) {
10485                 // Do nothing if uninstall was not requested or was already started.
10486                 return;
10487             }
10488             mPackagesToRemove.remove(packageUserPair);
10489         }
10490         try {
10491             if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
10492                 // Package does not exist. Nothing to do.
10493                 return;
10494             }
10495         } catch (RemoteException re) {
10496             Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
10497         }
10498
10499         try { // force stop the package before uninstalling
10500             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
10501         } catch (RemoteException re) {
10502             Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
10503         }
10504         final Uri packageURI = Uri.parse("package:" + packageName);
10505         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
10506         uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10507         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
10508     }
10509
10510     /**
10511      * Removes the admin from the policy. Ideally called after the admin's
10512      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
10513      *
10514      * @param adminReceiver The admin to remove
10515      * @param userHandle The user for which this admin has to be removed.
10516      */
10517     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
10518         synchronized (this) {
10519             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
10520             if (admin == null) {
10521                 return;
10522             }
10523             final DevicePolicyData policy = getUserData(userHandle);
10524             final boolean doProxyCleanup = admin.info.usesPolicy(
10525                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
10526             policy.mAdminList.remove(admin);
10527             policy.mAdminMap.remove(adminReceiver);
10528             validatePasswordOwnerLocked(policy);
10529             if (doProxyCleanup) {
10530                 resetGlobalProxyLocked(policy);
10531             }
10532             saveSettingsLocked(userHandle);
10533             updateMaximumTimeToLockLocked(userHandle);
10534             policy.mRemovingAdmins.remove(adminReceiver);
10535
10536             Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
10537         }
10538         // The removed admin might have disabled camera, so update user
10539         // restrictions.
10540         pushUserRestrictions(userHandle);
10541     }
10542
10543     @Override
10544     public void setDeviceProvisioningConfigApplied() {
10545         enforceManageUsers();
10546         synchronized (this) {
10547             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10548             policy.mDeviceProvisioningConfigApplied = true;
10549             saveSettingsLocked(UserHandle.USER_SYSTEM);
10550         }
10551     }
10552
10553     @Override
10554     public boolean isDeviceProvisioningConfigApplied() {
10555         enforceManageUsers();
10556         synchronized (this) {
10557             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10558             return policy.mDeviceProvisioningConfigApplied;
10559         }
10560     }
10561
10562     /**
10563      * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
10564      *
10565      * It's added for testing only. Please use this API carefully if it's used by other system app
10566      * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
10567      * apps.
10568      */
10569     @Override
10570     public void forceUpdateUserSetupComplete() {
10571         enforceCanManageProfileAndDeviceOwners();
10572         enforceCallerSystemUserHandle();
10573         // no effect if it's called from user build
10574         if (!mInjector.isBuildDebuggable()) {
10575             return;
10576         }
10577         final int userId = UserHandle.USER_SYSTEM;
10578         boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
10579                 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
10580         DevicePolicyData policy = getUserData(userId);
10581         policy.mUserSetupComplete = isUserCompleted;
10582         synchronized (this) {
10583             saveSettingsLocked(userId);
10584         }
10585     }
10586
10587     // TODO(b/22388012): When backup is available for secondary users and profiles, consider
10588     // whether there are any privacy/security implications of enabling the backup service here
10589     // if there are other users or profiles unmanaged or managed by a different entity (i.e. not
10590     // affiliated).
10591     @Override
10592     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
10593         if (!mHasFeature) {
10594             return;
10595         }
10596         Preconditions.checkNotNull(admin);
10597         synchronized (this) {
10598             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10599         }
10600
10601         final long ident = mInjector.binderClearCallingIdentity();
10602         try {
10603             IBackupManager ibm = mInjector.getIBackupManager();
10604             if (ibm != null) {
10605                 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
10606             }
10607         } catch (RemoteException e) {
10608             throw new IllegalStateException(
10609                 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
10610         } finally {
10611             mInjector.binderRestoreCallingIdentity(ident);
10612         }
10613     }
10614
10615     @Override
10616     public boolean isBackupServiceEnabled(ComponentName admin) {
10617         Preconditions.checkNotNull(admin);
10618         if (!mHasFeature) {
10619             return true;
10620         }
10621         synchronized (this) {
10622             try {
10623                 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10624                 IBackupManager ibm = mInjector.getIBackupManager();
10625                 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
10626             } catch (RemoteException e) {
10627                 throw new IllegalStateException("Failed requesting backup service state.", e);
10628             }
10629         }
10630     }
10631
10632     @Override
10633     public boolean bindDeviceAdminServiceAsUser(
10634             @NonNull ComponentName admin, @NonNull IApplicationThread caller,
10635             @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
10636             @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
10637         if (!mHasFeature) {
10638             return false;
10639         }
10640         Preconditions.checkNotNull(admin);
10641         Preconditions.checkNotNull(caller);
10642         Preconditions.checkNotNull(serviceIntent);
10643         Preconditions.checkArgument(
10644                 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
10645                 "Service intent must be explicit (with a package name or component): "
10646                         + serviceIntent);
10647         Preconditions.checkNotNull(connection);
10648         Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
10649                 "target user id must be different from the calling user id");
10650
10651         if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
10652             throw new SecurityException("Not allowed to bind to target user id");
10653         }
10654
10655         final String targetPackage;
10656         synchronized (this) {
10657             targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
10658         }
10659
10660         final long callingIdentity = mInjector.binderClearCallingIdentity();
10661         try {
10662             // Validate and sanitize the incoming service intent.
10663             final Intent sanitizedIntent =
10664                     createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
10665             if (sanitizedIntent == null) {
10666                 // Fail, cannot lookup the target service.
10667                 return false;
10668             }
10669             // Ask ActivityManager to bind it. Notice that we are binding the service with the
10670             // caller app instead of DevicePolicyManagerService.
10671             return mInjector.getIActivityManager().bindService(
10672                     caller, activtiyToken, serviceIntent,
10673                     serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
10674                     connection, flags, mContext.getOpPackageName(),
10675                     targetUserId) != 0;
10676         } catch (RemoteException ex) {
10677             // Same process, should not happen.
10678         } finally {
10679             mInjector.binderRestoreCallingIdentity(callingIdentity);
10680         }
10681
10682         // Failed to bind.
10683         return false;
10684     }
10685
10686     @Override
10687     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
10688         if (!mHasFeature) {
10689             return Collections.emptyList();
10690         }
10691         Preconditions.checkNotNull(admin);
10692
10693         synchronized (this) {
10694             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10695
10696             final int callingUserId = mInjector.userHandleGetCallingUserId();
10697             final long callingIdentity = mInjector.binderClearCallingIdentity();
10698             try {
10699                 ArrayList<UserHandle> targetUsers = new ArrayList<>();
10700                 if (!isDeviceOwner(admin, callingUserId)) {
10701                     // Profile owners can only bind to the device owner.
10702                     if (canUserBindToDeviceOwnerLocked(callingUserId)) {
10703                         targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
10704                     }
10705                 } else {
10706                     // Caller is the device owner: Look for profile owners that it can bind to.
10707                     final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
10708                     for (int i = 0; i < userInfos.size(); i++) {
10709                         final int userId = userInfos.get(i).id;
10710                         if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
10711                             targetUsers.add(UserHandle.of(userId));
10712                         }
10713                     }
10714                 }
10715
10716                 return targetUsers;
10717             } finally {
10718                 mInjector.binderRestoreCallingIdentity(callingIdentity);
10719             }
10720         }
10721     }
10722
10723     private boolean canUserBindToDeviceOwnerLocked(int userId) {
10724         // There has to be a device owner, under another user id.
10725         if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
10726             return false;
10727         }
10728
10729         // The user must have a profile owner that belongs to the same package as the device owner.
10730         if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
10731                 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
10732             return false;
10733         }
10734
10735         // The user must be affiliated.
10736         return isUserAffiliatedWithDeviceLocked(userId);
10737     }
10738
10739     /**
10740      * Return true if a given user has any accounts that'll prevent installing a device or profile
10741      * owner {@code owner}.
10742      * - If the user has no accounts, then return false.
10743      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
10744      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
10745      *   ..._DISALLOWED, return true.
10746      * - Otherwise return false.
10747      *
10748      * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
10749      * when the caller is not ADB.
10750      *
10751      * DO NOT CALL IT WITH THE DPMS LOCK HELD.
10752      */
10753     private boolean hasIncompatibleAccountsOrNonAdbNoLock(
10754             int userId, @Nullable ComponentName owner) {
10755         if (!isAdb()) {
10756             return true;
10757         }
10758         wtfIfInLock();
10759
10760         final long token = mInjector.binderClearCallingIdentity();
10761         try {
10762             final AccountManager am = AccountManager.get(mContext);
10763             final Account accounts[] = am.getAccountsAsUser(userId);
10764             if (accounts.length == 0) {
10765                 return false;
10766             }
10767             synchronized (this) {
10768                 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
10769                     Log.w(LOG_TAG,
10770                             "Non test-only owner can't be installed with existing accounts.");
10771                     return true;
10772                 }
10773             }
10774
10775             final String[] feature_allow =
10776                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
10777             final String[] feature_disallow =
10778                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
10779
10780             boolean compatible = true;
10781             for (Account account : accounts) {
10782                 if (hasAccountFeatures(am, account, feature_disallow)) {
10783                     Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
10784                     compatible = false;
10785                     break;
10786                 }
10787                 if (!hasAccountFeatures(am, account, feature_allow)) {
10788                     Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
10789                     compatible = false;
10790                     break;
10791                 }
10792             }
10793             if (compatible) {
10794                 Log.w(LOG_TAG, "All accounts are compatible");
10795             } else {
10796                 Log.e(LOG_TAG, "Found incompatible accounts");
10797             }
10798             return !compatible;
10799         } finally {
10800             mInjector.binderRestoreCallingIdentity(token);
10801         }
10802     }
10803
10804     private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
10805         try {
10806             return am.hasFeatures(account, features, null, null).getResult();
10807         } catch (Exception e) {
10808             Log.w(LOG_TAG, "Failed to get account feature", e);
10809             return false;
10810         }
10811     }
10812
10813     private boolean isAdb() {
10814         final int callingUid = mInjector.binderGetCallingUid();
10815         return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
10816     }
10817
10818     @Override
10819     public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
10820         if (!mHasFeature) {
10821             return;
10822         }
10823         Preconditions.checkNotNull(admin);
10824         getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10825
10826         if (enabled == isNetworkLoggingEnabledInternalLocked()) {
10827             // already in the requested state
10828             return;
10829         }
10830         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10831         deviceOwner.isNetworkLoggingEnabled = enabled;
10832         if (!enabled) {
10833             deviceOwner.numNetworkLoggingNotifications = 0;
10834             deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
10835         }
10836         saveSettingsLocked(mInjector.userHandleGetCallingUserId());
10837
10838         setNetworkLoggingActiveInternal(enabled);
10839     }
10840
10841     private synchronized void setNetworkLoggingActiveInternal(boolean active) {
10842         final long callingIdentity = mInjector.binderClearCallingIdentity();
10843         try {
10844             if (active) {
10845                 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
10846                 if (!mNetworkLogger.startNetworkLogging()) {
10847                     mNetworkLogger = null;
10848                     Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
10849                             + " service not being available yet.");
10850                 }
10851                 maybePauseDeviceWideLoggingLocked();
10852                 sendNetworkLoggingNotificationLocked();
10853             } else {
10854                 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
10855                     Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
10856                             + " service not being available yet.");
10857                 }
10858                 mNetworkLogger = null;
10859                 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING);
10860             }
10861         } finally {
10862             mInjector.binderRestoreCallingIdentity(callingIdentity);
10863         }
10864     }
10865
10866     /** Pauses security and network logging if there are unaffiliated users on the device */
10867     private void maybePauseDeviceWideLoggingLocked() {
10868         if (!areAllUsersAffiliatedWithDeviceLocked()) {
10869             Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
10870                     + "paused if enabled.");
10871             mSecurityLogMonitor.pause();
10872             if (mNetworkLogger != null) {
10873                 mNetworkLogger.pause();
10874             }
10875         }
10876     }
10877
10878     /** Resumes security and network logging (if they are enabled) if all users are affiliated */
10879     private void maybeResumeDeviceWideLoggingLocked() {
10880         if (areAllUsersAffiliatedWithDeviceLocked()) {
10881             final long ident = mInjector.binderClearCallingIdentity();
10882             try {
10883                 mSecurityLogMonitor.resume();
10884                 if (mNetworkLogger != null) {
10885                     mNetworkLogger.resume();
10886                 }
10887             } finally {
10888                 mInjector.binderRestoreCallingIdentity(ident);
10889             }
10890         }
10891     }
10892
10893     /** Deletes any security and network logs that might have been collected so far */
10894     private void discardDeviceWideLogsLocked() {
10895         mSecurityLogMonitor.discardLogs();
10896         if (mNetworkLogger != null) {
10897             mNetworkLogger.discardLogs();
10898         }
10899         // TODO: We should discard pre-boot security logs here too, as otherwise those
10900         // logs (which might contain data from the user just removed) will be
10901         // available after next boot.
10902     }
10903
10904     @Override
10905     public boolean isNetworkLoggingEnabled(ComponentName admin) {
10906         if (!mHasFeature) {
10907             return false;
10908         }
10909         synchronized (this) {
10910             enforceDeviceOwnerOrManageUsers();
10911             return isNetworkLoggingEnabledInternalLocked();
10912         }
10913     }
10914
10915     private boolean isNetworkLoggingEnabledInternalLocked() {
10916         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10917         return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
10918     }
10919
10920     /*
10921      * A maximum of 1200 events are returned, and the total marshalled size is in the order of
10922      * 100kB, so returning a List instead of ParceledListSlice is acceptable.
10923      * Ideally this would be done with ParceledList, however it only supports homogeneous types.
10924      *
10925      * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
10926      */
10927     @Override
10928     public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) {
10929         if (!mHasFeature) {
10930             return null;
10931         }
10932         Preconditions.checkNotNull(admin);
10933         ensureDeviceOwnerAndAllUsersAffiliated(admin);
10934
10935         synchronized (this) {
10936             if (mNetworkLogger == null
10937                     || !isNetworkLoggingEnabledInternalLocked()) {
10938                 return null;
10939             }
10940
10941             final long currentTime = System.currentTimeMillis();
10942             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
10943             if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
10944                 policyData.mLastNetworkLogsRetrievalTime = currentTime;
10945                 saveSettingsLocked(UserHandle.USER_SYSTEM);
10946             }
10947             return mNetworkLogger.retrieveLogs(batchToken);
10948         }
10949     }
10950
10951     private void sendNetworkLoggingNotificationLocked() {
10952         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
10953         if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
10954             return;
10955         }
10956         if (deviceOwner.numNetworkLoggingNotifications >=
10957                 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
10958             return;
10959         }
10960         final long now = System.currentTimeMillis();
10961         if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
10962             return;
10963         }
10964         deviceOwner.numNetworkLoggingNotifications++;
10965         if (deviceOwner.numNetworkLoggingNotifications
10966                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
10967             deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
10968         } else {
10969             deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
10970         }
10971         final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
10972         intent.setPackage("com.android.systemui");
10973         final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
10974                 UserHandle.CURRENT);
10975         Notification notification =
10976                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
10977                 .setSmallIcon(R.drawable.ic_info_outline)
10978                 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
10979                 .setContentText(mContext.getString(R.string.network_logging_notification_text))
10980                 .setTicker(mContext.getString(R.string.network_logging_notification_title))
10981                 .setShowWhen(true)
10982                 .setContentIntent(pendingIntent)
10983                 .setStyle(new Notification.BigTextStyle()
10984                         .bigText(mContext.getString(R.string.network_logging_notification_text)))
10985                 .build();
10986         mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification);
10987         saveSettingsLocked(mOwners.getDeviceOwnerUserId());
10988     }
10989
10990     /**
10991      * Return the package name of owner in a given user.
10992      */
10993     private String getOwnerPackageNameForUserLocked(int userId) {
10994         return mOwners.getDeviceOwnerUserId() == userId
10995                 ? mOwners.getDeviceOwnerPackageName()
10996                 : mOwners.getProfileOwnerPackage(userId);
10997     }
10998
10999     /**
11000      * @param rawIntent Original service intent specified by caller. It must be explicit.
11001      * @param expectedPackageName The expected package name of the resolved service.
11002      * @return Intent that have component explicitly set. {@code null} if no service is resolved
11003      *     with the given intent.
11004      * @throws SecurityException if the intent is resolved to an invalid service.
11005      */
11006     private Intent createCrossUserServiceIntent(
11007             @NonNull Intent rawIntent, @NonNull String expectedPackageName,
11008             @UserIdInt int targetUserId) throws RemoteException, SecurityException {
11009         ResolveInfo info = mIPackageManager.resolveService(
11010                 rawIntent,
11011                 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
11012                 0,  // flags
11013                 targetUserId);
11014         if (info == null || info.serviceInfo == null) {
11015             Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
11016                     + " or user " + targetUserId + " is not running");
11017             return null;
11018         }
11019         if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
11020             throw new SecurityException("Only allow to bind service in " + expectedPackageName);
11021         }
11022         // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
11023         if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
11024             throw new SecurityException(
11025                     "Service must be protected by BIND_DEVICE_ADMIN permission");
11026         }
11027         // It is the system server to bind the service, it would be extremely dangerous if it
11028         // can be exploited to bind any service. Set the component explicitly to make sure we
11029         // do not bind anything accidentally.
11030         rawIntent.setComponent(info.serviceInfo.getComponentName());
11031         return rawIntent;
11032     }
11033
11034     @Override
11035     public long getLastSecurityLogRetrievalTime() {
11036         enforceDeviceOwnerOrManageUsers();
11037         return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
11038      }
11039
11040     @Override
11041     public long getLastBugReportRequestTime() {
11042         enforceDeviceOwnerOrManageUsers();
11043         return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
11044      }
11045
11046     @Override
11047     public long getLastNetworkLogRetrievalTime() {
11048         enforceDeviceOwnerOrManageUsers();
11049         return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
11050     }
11051
11052     @Override
11053     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
11054         if (!mHasFeature) {
11055             return false;
11056         }
11057         if (token == null || token.length < 32) {
11058             throw new IllegalArgumentException("token must be at least 32-byte long");
11059         }
11060         synchronized (this) {
11061             final int userHandle = mInjector.userHandleGetCallingUserId();
11062             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11063
11064             DevicePolicyData policy = getUserData(userHandle);
11065             long ident = mInjector.binderClearCallingIdentity();
11066             try {
11067                 if (policy.mPasswordTokenHandle != 0) {
11068                     mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
11069                 }
11070
11071                 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle);
11072                 saveSettingsLocked(userHandle);
11073                 return policy.mPasswordTokenHandle != 0;
11074             } finally {
11075                 mInjector.binderRestoreCallingIdentity(ident);
11076             }
11077         }
11078     }
11079
11080     @Override
11081     public boolean clearResetPasswordToken(ComponentName admin) {
11082         if (!mHasFeature) {
11083             return false;
11084         }
11085         synchronized (this) {
11086             final int userHandle = mInjector.userHandleGetCallingUserId();
11087             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11088
11089             DevicePolicyData policy = getUserData(userHandle);
11090             if (policy.mPasswordTokenHandle != 0) {
11091                 long ident = mInjector.binderClearCallingIdentity();
11092                 try {
11093                     boolean result = mLockPatternUtils.removeEscrowToken(
11094                             policy.mPasswordTokenHandle, userHandle);
11095                     policy.mPasswordTokenHandle = 0;
11096                     saveSettingsLocked(userHandle);
11097                     return result;
11098                 } finally {
11099                     mInjector.binderRestoreCallingIdentity(ident);
11100                 }
11101             }
11102         }
11103         return false;
11104     }
11105
11106     @Override
11107     public boolean isResetPasswordTokenActive(ComponentName admin) {
11108         synchronized (this) {
11109             final int userHandle = mInjector.userHandleGetCallingUserId();
11110             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11111
11112             DevicePolicyData policy = getUserData(userHandle);
11113             if (policy.mPasswordTokenHandle != 0) {
11114                 long ident = mInjector.binderClearCallingIdentity();
11115                 try {
11116                     return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle,
11117                             userHandle);
11118                 } finally {
11119                     mInjector.binderRestoreCallingIdentity(ident);
11120                 }
11121             }
11122         }
11123         return false;
11124     }
11125
11126     @Override
11127     public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
11128             int flags) {
11129         Preconditions.checkNotNull(token);
11130         synchronized (this) {
11131             final int userHandle = mInjector.userHandleGetCallingUserId();
11132             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11133
11134             DevicePolicyData policy = getUserData(userHandle);
11135             if (policy.mPasswordTokenHandle != 0) {
11136                 final String password = passwordOrNull != null ? passwordOrNull : "";
11137                 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token,
11138                         flags, mInjector.binderGetCallingUid(), userHandle);
11139             } else {
11140                 Slog.w(LOG_TAG, "No saved token handle");
11141             }
11142         }
11143         return false;
11144     }
11145
11146     @Override
11147     public boolean isCurrentInputMethodSetByOwner() {
11148         enforceProfileOwnerOrSystemUser();
11149         return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet;
11150     }
11151
11152     @Override
11153     public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
11154         final int userId = user.getIdentifier();
11155         enforceProfileOwnerOrFullCrossUsersPermission(userId);
11156         synchronized (this) {
11157             return new StringParceledListSlice(
11158                     new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
11159         }
11160     }
11161 }