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