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