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