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