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