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