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