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