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