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