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