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