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