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