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