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