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