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