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