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