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