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