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