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