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