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