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