DevicePolicyManagerService.java revision 044588599c97ceff70d74a133c9eb01a028db00c
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    static {
319        SECURE_SETTINGS_WHITELIST = new ArraySet<>();
320        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
321        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
322        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
323
324        SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
325        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
326        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
327
328        GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
329        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
330        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
331        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
332        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
333        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
334        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
335        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
336        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
337
338        GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
339        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
340        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
341        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
342        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
343        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
344    }
345
346    /**
347     * Keyguard features that when set on a profile affect the profile content or challenge only.
348     * These cannot be set on the managed profile's parent DPM instance
349     */
350    private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
351            DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
352
353    /** Keyguard features that are allowed to be set on a managed profile */
354    private static final int PROFILE_KEYGUARD_FEATURES =
355            PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
356
357    private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
358
359    /**
360     * Minimum timeout in milliseconds after which unlocking with weak auth times out,
361     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
362     */
363    private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
364
365    /**
366     * Strings logged with {@link
367     * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}.
368     */
369    private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
370    private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
371
372    final Context mContext;
373    final Injector mInjector;
374    final IPackageManager mIPackageManager;
375    final UserManager mUserManager;
376    final UserManagerInternal mUserManagerInternal;
377    final TelephonyManager mTelephonyManager;
378    private final LockPatternUtils mLockPatternUtils;
379    private final DevicePolicyConstants mConstants;
380    private final DeviceAdminServiceController mDeviceAdminServiceController;
381
382    /**
383     * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
384     * is requested for user u.
385     */
386    private final Set<Pair<String, Integer>> mPackagesToRemove =
387            new ArraySet<Pair<String, Integer>>();
388
389    final LocalService mLocalService;
390
391    // Stores and loads state on device and profile owners.
392    @VisibleForTesting
393    final Owners mOwners;
394
395    private final Binder mToken = new Binder();
396
397    /**
398     * Whether or not device admin feature is supported. If it isn't return defaults for all
399     * public methods.
400     */
401    boolean mHasFeature;
402
403    /**
404     * Whether or not this device is a watch.
405     */
406    boolean mIsWatch;
407
408    private final CertificateMonitor mCertificateMonitor;
409    private final SecurityLogMonitor mSecurityLogMonitor;
410    private NetworkLogger mNetworkLogger;
411
412    private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
413    private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
414
415    private SetupContentObserver mSetupContentObserver;
416
417    private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
418        @Override
419        public void run() {
420            if(mRemoteBugreportServiceIsActive.get()) {
421                onBugreportFailed();
422            }
423        }
424    };
425
426    /** Listens only if mHasFeature == true. */
427    private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
428
429        @Override
430        public void onReceive(Context context, Intent intent) {
431            if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
432                    && mRemoteBugreportServiceIsActive.get()) {
433                onBugreportFinished(intent);
434            }
435        }
436    };
437
438    /** Listens only if mHasFeature == true. */
439    private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
440
441        @Override
442        public void onReceive(Context context, Intent intent) {
443            String action = intent.getAction();
444            mInjector.getNotificationManager().cancel(LOG_TAG,
445                    RemoteBugreportUtils.NOTIFICATION_ID);
446            if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
447                onBugreportSharingAccepted();
448            } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
449                onBugreportSharingDeclined();
450            }
451            mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
452        }
453    };
454
455    public static final class Lifecycle extends SystemService {
456        private BaseIDevicePolicyManager mService;
457
458        public Lifecycle(Context context) {
459            super(context);
460            String dpmsClassName = context.getResources()
461                    .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
462            if (TextUtils.isEmpty(dpmsClassName)) {
463                dpmsClassName = DevicePolicyManagerService.class.getName();
464            }
465            try {
466                Class serviceClass = Class.forName(dpmsClassName);
467                Constructor constructor = serviceClass.getConstructor(Context.class);
468                mService = (BaseIDevicePolicyManager) constructor.newInstance(context);
469            } catch (Exception e) {
470                throw new IllegalStateException(
471                    "Failed to instantiate DevicePolicyManagerService with class name: "
472                    + dpmsClassName, e);
473            }
474        }
475
476        @Override
477        public void onStart() {
478            publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
479        }
480
481        @Override
482        public void onBootPhase(int phase) {
483            mService.systemReady(phase);
484        }
485
486        @Override
487        public void onStartUser(int userHandle) {
488            mService.handleStartUser(userHandle);
489        }
490
491        @Override
492        public void onUnlockUser(int userHandle) {
493            mService.handleUnlockUser(userHandle);
494        }
495
496        @Override
497        public void onStopUser(int userHandle) {
498            mService.handleStopUser(userHandle);
499        }
500    }
501
502    public static class DevicePolicyData {
503        @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics();
504        int mFailedPasswordAttempts = 0;
505        boolean mPasswordStateHasBeenSetSinceBoot = false;
506        boolean mPasswordValidAtLastCheckpoint = false;
507
508        int mUserHandle;
509        int mPasswordOwner = -1;
510        long mLastMaximumTimeToLock = -1;
511        boolean mUserSetupComplete = false;
512        boolean mPaired = false;
513        int mUserProvisioningState;
514        int mPermissionPolicy;
515
516        boolean mDeviceProvisioningConfigApplied = false;
517
518        final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
519        final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
520        final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
521
522        // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
523        final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
524
525        // This is the list of component allowed to start lock task mode.
526        List<String> mLockTaskPackages = new ArrayList<>();
527
528        // Bitfield of feature flags to be enabled during LockTask mode.
529        int mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
530
531        boolean mStatusBarDisabled = false;
532
533        ComponentName mRestrictionsProvider;
534
535        // Map of delegate package to delegation scopes
536        final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>();
537
538        boolean doNotAskCredentialsOnBoot = false;
539
540        Set<String> mAffiliationIds = new ArraySet<>();
541
542        long mLastSecurityLogRetrievalTime = -1;
543
544        long mLastBugReportRequestTime = -1;
545
546        long mLastNetworkLogsRetrievalTime = -1;
547
548        boolean mCurrentInputMethodSet = false;
549
550        // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
551        Set<String> mOwnerInstalledCaCerts = new ArraySet<>();
552
553        // Used for initialization of users created by createAndManageUser.
554        boolean mAdminBroadcastPending = false;
555        PersistableBundle mInitBundle = null;
556
557        long mPasswordTokenHandle = 0;
558
559        public DevicePolicyData(int userHandle) {
560            mUserHandle = userHandle;
561        }
562    }
563
564    final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
565
566    final Handler mHandler;
567    final Handler mBackgroundHandler;
568
569    /** Listens only if mHasFeature == true. */
570    final BroadcastReceiver mReceiver = new BroadcastReceiver() {
571        @Override
572        public void onReceive(Context context, Intent intent) {
573            final String action = intent.getAction();
574            final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
575                    getSendingUserId());
576
577            /*
578             * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
579             * however it's too early in the boot process to register with IIpConnectivityMetrics
580             * to listen for events.
581             */
582            if (Intent.ACTION_USER_STARTED.equals(action)
583                    && userHandle == mOwners.getDeviceOwnerUserId()) {
584                synchronized (DevicePolicyManagerService.this) {
585                    if (isNetworkLoggingEnabledInternalLocked()) {
586                        setNetworkLoggingActiveInternal(true);
587                    }
588                }
589            }
590            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
591                    && userHandle == mOwners.getDeviceOwnerUserId()
592                    && getDeviceOwnerRemoteBugreportUri() != null) {
593                IntentFilter filterConsent = new IntentFilter();
594                filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
595                filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
596                mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
597                mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
598                        RemoteBugreportUtils.NOTIFICATION_ID,
599                        RemoteBugreportUtils.buildNotification(mContext,
600                                DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
601                                UserHandle.ALL);
602            }
603            if (Intent.ACTION_BOOT_COMPLETED.equals(action)
604                    || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
605                if (VERBOSE_LOG) {
606                    Slog.v(LOG_TAG, "Sending password expiration notifications for action "
607                            + action + " for user " + userHandle);
608                }
609                mHandler.post(new Runnable() {
610                    @Override
611                    public void run() {
612                        handlePasswordExpirationNotification(userHandle);
613                    }
614                });
615            }
616
617            if (Intent.ACTION_USER_ADDED.equals(action)) {
618                sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
619                synchronized (DevicePolicyManagerService.this) {
620                    // It might take a while for the user to become affiliated. Make security
621                    // and network logging unavailable in the meantime.
622                    maybePauseDeviceWideLoggingLocked();
623                }
624            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
625                sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
626                synchronized (DevicePolicyManagerService.this) {
627                    // Check whether the user is affiliated, *before* removing its data.
628                    boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
629                    removeUserData(userHandle);
630                    if (!isRemovedUserAffiliated) {
631                        // We discard the logs when unaffiliated users are deleted (so that the
632                        // device owner cannot retrieve data about that user after it's gone).
633                        discardDeviceWideLogsLocked();
634                        // Resume logging if all remaining users are affiliated.
635                        maybeResumeDeviceWideLoggingLocked();
636                    }
637                }
638            } else if (Intent.ACTION_USER_STARTED.equals(action)) {
639                synchronized (DevicePolicyManagerService.this) {
640                    maybeSendAdminEnabledBroadcastLocked(userHandle);
641                    // Reset the policy data
642                    mUserData.remove(userHandle);
643                }
644                handlePackagesChanged(null /* check all admins */, userHandle);
645            } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
646                synchronized (DevicePolicyManagerService.this) {
647                    maybeSendAdminEnabledBroadcastLocked(userHandle);
648                }
649            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
650                handlePackagesChanged(null /* check all admins */, userHandle);
651            } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
652                    || (Intent.ACTION_PACKAGE_ADDED.equals(action)
653                            && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
654                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
655            } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
656                    && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
657                handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
658            } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
659                clearWipeProfileNotification();
660            }
661        }
662
663        private void sendUserAddedOrRemovedCommand(String action, int userHandle) {
664            synchronized (DevicePolicyManagerService.this) {
665                ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
666                if (deviceOwner != null) {
667                    Bundle extras = new Bundle();
668                    extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
669                    sendAdminCommandLocked(deviceOwner, action, extras, null);
670                }
671            }
672        }
673    };
674
675    static class ActiveAdmin {
676        private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
677        private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
678        private static final String TAG_DISABLE_CAMERA = "disable-camera";
679        private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
680        private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
681        private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
682                = "disable-bt-contacts-sharing";
683        private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
684        private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
685        private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
686        private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
687        private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
688        private static final String TAG_ACCOUNT_TYPE = "account-type";
689        private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
690                = "permitted-accessiblity-services";
691        private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
692        private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
693        private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
694        private static final String TAG_TRUST_AGENT_COMPONENT = "component";
695        private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
696        private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
697        private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
698        private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
699        private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
700        private static final String TAG_PERMITTED_IMES = "permitted-imes";
701        private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS =
702                "permitted-notification-listeners";
703        private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
704        private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
705        private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
706        private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
707        private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
708        private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
709        private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
710        private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
711        private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
712        private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
713        private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
714        private static final String ATTR_VALUE = "value";
715        private static final String TAG_PASSWORD_QUALITY = "password-quality";
716        private static final String TAG_POLICIES = "policies";
717        private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
718                "cross-profile-widget-providers";
719        private static final String TAG_PROVIDER = "provider";
720        private static final String TAG_PACKAGE_LIST_ITEM  = "item";
721        private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
722        private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
723        private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS =
724                "default-enabled-user-restrictions";
725        private static final String TAG_RESTRICTION = "restriction";
726        private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
727        private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
728        private static final String TAG_PARENT_ADMIN = "parent-admin";
729        private static final String TAG_ORGANIZATION_COLOR = "organization-color";
730        private static final String TAG_ORGANIZATION_NAME = "organization-name";
731        private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
732        private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
733        private static final String TAG_IS_LOGOUT_BUTTON_ENABLED = "is_logout_button_enabled";
734
735        final DeviceAdminInfo info;
736
737
738        static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
739        int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
740
741        static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
742        static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
743        static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
744        static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
745        static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
746        static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
747        static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
748        @NonNull
749        PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
750                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
751                DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
752                DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
753                DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
754
755        static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
756        long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
757
758        long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
759
760        static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
761        int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
762
763        static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
764        long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
765
766        static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
767        long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
768
769        static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
770
771        int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
772
773        boolean encryptionRequested = false;
774        boolean testOnlyAdmin = false;
775        boolean disableCamera = false;
776        boolean disableCallerId = false;
777        boolean disableContactsSearch = false;
778        boolean disableBluetoothContactSharing = true;
779        boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
780        boolean requireAutoTime = false; // Can only be set by a device owner.
781        boolean forceEphemeralUsers = false; // Can only be set by a device owner.
782        boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
783        boolean isLogoutButtonEnabled = false; // Can only be set by a device owner.
784
785        // one notification after enabling + one more after reboots
786        static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2;
787        int numNetworkLoggingNotifications = 0;
788        long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
789
790        ActiveAdmin parentAdmin;
791        final boolean isParent;
792
793        static class TrustAgentInfo {
794            public PersistableBundle options;
795            TrustAgentInfo(PersistableBundle bundle) {
796                options = bundle;
797            }
798        }
799
800        final Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
801
802        // The list of permitted accessibility services package namesas set by a profile
803        // or device owner. Null means all accessibility services are allowed, empty means
804        // none except system services are allowed.
805        List<String> permittedAccessiblityServices;
806
807        // The list of permitted input methods package names as set by a profile or device owner.
808        // Null means all input methods are allowed, empty means none except system imes are
809        // allowed.
810        List<String> permittedInputMethods;
811
812        // The list of packages allowed to use a NotificationListenerService to receive events for
813        // notifications from this user. Null means that all packages are allowed. Empty list means
814        // that only packages from the system are allowed.
815        List<String> permittedNotificationListeners;
816
817        // List of package names to keep cached.
818        List<String> keepUninstalledPackages;
819
820        // TODO: review implementation decisions with frameworks team
821        boolean specifiesGlobalProxy = false;
822        String globalProxySpec = null;
823        String globalProxyExclusionList = null;
824
825        ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
826
827        List<String> crossProfileWidgetProviders;
828
829        Bundle userRestrictions;
830
831        // User restrictions that have already been enabled by default for this admin (either when
832        // setting the device or profile owner, or during a system update if one of those "enabled
833        // by default" restrictions is newly added).
834        final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>();
835
836        // Support text provided by the admin to display to the user.
837        CharSequence shortSupportMessage = null;
838        CharSequence longSupportMessage = null;
839
840        // Background color of confirm credentials screen. Default: teal.
841        static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
842        int organizationColor = DEF_ORGANIZATION_COLOR;
843
844        // Default title of confirm credentials screen
845        String organizationName = null;
846
847        ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
848            info = _info;
849            isParent = parent;
850        }
851
852        ActiveAdmin getParentActiveAdmin() {
853            Preconditions.checkState(!isParent);
854
855            if (parentAdmin == null) {
856                parentAdmin = new ActiveAdmin(info, /* parent */ true);
857            }
858            return parentAdmin;
859        }
860
861        boolean hasParentActiveAdmin() {
862            return parentAdmin != null;
863        }
864
865        int getUid() { return info.getActivityInfo().applicationInfo.uid; }
866
867        public UserHandle getUserHandle() {
868            return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
869        }
870
871        void writeToXml(XmlSerializer out)
872                throws IllegalArgumentException, IllegalStateException, IOException {
873            out.startTag(null, TAG_POLICIES);
874            info.writePoliciesToXml(out);
875            out.endTag(null, TAG_POLICIES);
876            if (minimumPasswordMetrics.quality
877                    != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
878                out.startTag(null, TAG_PASSWORD_QUALITY);
879                out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
880                out.endTag(null, TAG_PASSWORD_QUALITY);
881                if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
882                    out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
883                    out.attribute(
884                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
885                    out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
886                }
887                if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
888                    out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
889                    out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
890                    out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
891                }
892                if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
893                    out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
894                    out.attribute(
895                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
896                    out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
897                }
898                if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
899                    out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
900                    out.attribute(
901                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
902                    out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
903                }
904                if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
905                    out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
906                    out.attribute(
907                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
908                    out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
909                }
910                if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
911                    out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
912                    out.attribute(
913                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
914                    out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
915                }
916                if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
917                    out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
918                    out.attribute(
919                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
920                    out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
921                }
922                if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
923                    out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
924                    out.attribute(
925                            null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
926                    out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
927                }
928            }
929            if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
930                out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
931                out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
932                out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
933            }
934            if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
935                out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
936                out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
937                out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
938            }
939            if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
940                out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
941                out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
942                out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
943            }
944            if (specifiesGlobalProxy) {
945                out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
946                out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
947                out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
948                if (globalProxySpec != null) {
949                    out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
950                    out.attribute(null, ATTR_VALUE, globalProxySpec);
951                    out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
952                }
953                if (globalProxyExclusionList != null) {
954                    out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
955                    out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
956                    out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
957                }
958            }
959            if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
960                out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
961                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
962                out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
963            }
964            if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
965                out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
966                out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
967                out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
968            }
969            if (encryptionRequested) {
970                out.startTag(null, TAG_ENCRYPTION_REQUESTED);
971                out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
972                out.endTag(null, TAG_ENCRYPTION_REQUESTED);
973            }
974            if (testOnlyAdmin) {
975                out.startTag(null, TAG_TEST_ONLY_ADMIN);
976                out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
977                out.endTag(null, TAG_TEST_ONLY_ADMIN);
978            }
979            if (disableCamera) {
980                out.startTag(null, TAG_DISABLE_CAMERA);
981                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
982                out.endTag(null, TAG_DISABLE_CAMERA);
983            }
984            if (disableCallerId) {
985                out.startTag(null, TAG_DISABLE_CALLER_ID);
986                out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
987                out.endTag(null, TAG_DISABLE_CALLER_ID);
988            }
989            if (disableContactsSearch) {
990                out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
991                out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
992                out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
993            }
994            if (!disableBluetoothContactSharing) {
995                out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
996                out.attribute(null, ATTR_VALUE,
997                        Boolean.toString(disableBluetoothContactSharing));
998                out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
999            }
1000            if (disableScreenCapture) {
1001                out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1002                out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
1003                out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1004            }
1005            if (requireAutoTime) {
1006                out.startTag(null, TAG_REQUIRE_AUTO_TIME);
1007                out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
1008                out.endTag(null, TAG_REQUIRE_AUTO_TIME);
1009            }
1010            if (forceEphemeralUsers) {
1011                out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
1012                out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
1013                out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
1014            }
1015            if (isNetworkLoggingEnabled) {
1016                out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1017                out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
1018                out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
1019                        Integer.toString(numNetworkLoggingNotifications));
1020                out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
1021                        Long.toString(lastNetworkLoggingNotificationTimeMs));
1022                out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1023            }
1024            if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
1025                out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1026                out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
1027                out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1028            }
1029            if (!accountTypesWithManagementDisabled.isEmpty()) {
1030                out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
1031                writeAttributeValuesToXml(
1032                        out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1033                out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
1034            }
1035            if (!trustAgentInfos.isEmpty()) {
1036                Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
1037                out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1038                for (Entry<String, TrustAgentInfo> entry : set) {
1039                    TrustAgentInfo trustAgentInfo = entry.getValue();
1040                    out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
1041                    out.attribute(null, ATTR_VALUE, entry.getKey());
1042                    if (trustAgentInfo.options != null) {
1043                        out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1044                        try {
1045                            trustAgentInfo.options.saveToXml(out);
1046                        } catch (XmlPullParserException e) {
1047                            Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
1048                        }
1049                        out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1050                    }
1051                    out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
1052                }
1053                out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1054            }
1055            if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
1056                out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1057                writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders);
1058                out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1059            }
1060            writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
1061                    permittedAccessiblityServices);
1062            writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
1063            writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS,
1064                    permittedNotificationListeners);
1065            writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
1066            if (hasUserRestrictions()) {
1067                UserRestrictionsUtils.writeRestrictions(
1068                        out, userRestrictions, TAG_USER_RESTRICTIONS);
1069            }
1070            if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) {
1071                out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1072                writeAttributeValuesToXml(
1073                        out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1074                out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1075            }
1076            if (!TextUtils.isEmpty(shortSupportMessage)) {
1077                out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1078                out.text(shortSupportMessage.toString());
1079                out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1080            }
1081            if (!TextUtils.isEmpty(longSupportMessage)) {
1082                out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
1083                out.text(longSupportMessage.toString());
1084                out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
1085            }
1086            if (parentAdmin != null) {
1087                out.startTag(null, TAG_PARENT_ADMIN);
1088                parentAdmin.writeToXml(out);
1089                out.endTag(null, TAG_PARENT_ADMIN);
1090            }
1091            if (organizationColor != DEF_ORGANIZATION_COLOR) {
1092                out.startTag(null, TAG_ORGANIZATION_COLOR);
1093                out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
1094                out.endTag(null, TAG_ORGANIZATION_COLOR);
1095            }
1096            if (organizationName != null) {
1097                out.startTag(null, TAG_ORGANIZATION_NAME);
1098                out.text(organizationName);
1099                out.endTag(null, TAG_ORGANIZATION_NAME);
1100            }
1101            if (isLogoutButtonEnabled) {
1102                out.startTag(null, TAG_IS_LOGOUT_BUTTON_ENABLED);
1103                out.attribute(null, ATTR_VALUE, Boolean.toString(isLogoutButtonEnabled));
1104                out.endTag(null, TAG_IS_LOGOUT_BUTTON_ENABLED);
1105            }
1106        }
1107
1108        void writePackageListToXml(XmlSerializer out, String outerTag,
1109                List<String> packageList)
1110                throws IllegalArgumentException, IllegalStateException, IOException {
1111            if (packageList == null) {
1112                return;
1113            }
1114
1115            out.startTag(null, outerTag);
1116            writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList);
1117            out.endTag(null, outerTag);
1118        }
1119
1120        void writeAttributeValuesToXml(XmlSerializer out, String tag,
1121                @NonNull Collection<String> values) throws IOException {
1122            for (String value : values) {
1123                out.startTag(null, tag);
1124                out.attribute(null, ATTR_VALUE, value);
1125                out.endTag(null, tag);
1126            }
1127        }
1128
1129        void readFromXml(XmlPullParser parser)
1130                throws XmlPullParserException, IOException {
1131            int outerDepth = parser.getDepth();
1132            int type;
1133            while ((type=parser.next()) != END_DOCUMENT
1134                   && (type != END_TAG || parser.getDepth() > outerDepth)) {
1135                if (type == END_TAG || type == TEXT) {
1136                    continue;
1137                }
1138                String tag = parser.getName();
1139                if (TAG_POLICIES.equals(tag)) {
1140                    info.readPoliciesFromXml(parser);
1141                } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1142                    minimumPasswordMetrics.quality = Integer.parseInt(
1143                            parser.getAttributeValue(null, ATTR_VALUE));
1144                } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1145                    minimumPasswordMetrics.length = Integer.parseInt(
1146                            parser.getAttributeValue(null, ATTR_VALUE));
1147                } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1148                    passwordHistoryLength = Integer.parseInt(
1149                            parser.getAttributeValue(null, ATTR_VALUE));
1150                } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1151                    minimumPasswordMetrics.upperCase = Integer.parseInt(
1152                            parser.getAttributeValue(null, ATTR_VALUE));
1153                } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1154                    minimumPasswordMetrics.lowerCase = Integer.parseInt(
1155                            parser.getAttributeValue(null, ATTR_VALUE));
1156                } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1157                    minimumPasswordMetrics.letters = Integer.parseInt(
1158                            parser.getAttributeValue(null, ATTR_VALUE));
1159                } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1160                    minimumPasswordMetrics.numeric = Integer.parseInt(
1161                            parser.getAttributeValue(null, ATTR_VALUE));
1162                } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1163                    minimumPasswordMetrics.symbols = Integer.parseInt(
1164                            parser.getAttributeValue(null, ATTR_VALUE));
1165                } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1166                    minimumPasswordMetrics.nonLetter = Integer.parseInt(
1167                            parser.getAttributeValue(null, ATTR_VALUE));
1168                } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1169                    maximumTimeToUnlock = Long.parseLong(
1170                            parser.getAttributeValue(null, ATTR_VALUE));
1171                } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1172                    strongAuthUnlockTimeout = Long.parseLong(
1173                            parser.getAttributeValue(null, ATTR_VALUE));
1174                } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1175                    maximumFailedPasswordsForWipe = Integer.parseInt(
1176                            parser.getAttributeValue(null, ATTR_VALUE));
1177                } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1178                    specifiesGlobalProxy = Boolean.parseBoolean(
1179                            parser.getAttributeValue(null, ATTR_VALUE));
1180                } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1181                    globalProxySpec =
1182                        parser.getAttributeValue(null, ATTR_VALUE);
1183                } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1184                    globalProxyExclusionList =
1185                        parser.getAttributeValue(null, ATTR_VALUE);
1186                } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1187                    passwordExpirationTimeout = Long.parseLong(
1188                            parser.getAttributeValue(null, ATTR_VALUE));
1189                } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1190                    passwordExpirationDate = Long.parseLong(
1191                            parser.getAttributeValue(null, ATTR_VALUE));
1192                } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1193                    encryptionRequested = Boolean.parseBoolean(
1194                            parser.getAttributeValue(null, ATTR_VALUE));
1195                } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1196                    testOnlyAdmin = Boolean.parseBoolean(
1197                            parser.getAttributeValue(null, ATTR_VALUE));
1198                } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1199                    disableCamera = Boolean.parseBoolean(
1200                            parser.getAttributeValue(null, ATTR_VALUE));
1201                } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1202                    disableCallerId = Boolean.parseBoolean(
1203                            parser.getAttributeValue(null, ATTR_VALUE));
1204                } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1205                    disableContactsSearch = Boolean.parseBoolean(
1206                            parser.getAttributeValue(null, ATTR_VALUE));
1207                } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1208                    disableBluetoothContactSharing = Boolean.parseBoolean(parser
1209                            .getAttributeValue(null, ATTR_VALUE));
1210                } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1211                    disableScreenCapture = Boolean.parseBoolean(
1212                            parser.getAttributeValue(null, ATTR_VALUE));
1213                } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1214                    requireAutoTime = Boolean.parseBoolean(
1215                            parser.getAttributeValue(null, ATTR_VALUE));
1216                } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1217                    forceEphemeralUsers = Boolean.parseBoolean(
1218                            parser.getAttributeValue(null, ATTR_VALUE));
1219                } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1220                    isNetworkLoggingEnabled = Boolean.parseBoolean(
1221                            parser.getAttributeValue(null, ATTR_VALUE));
1222                    lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1223                            parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1224                    numNetworkLoggingNotifications = Integer.parseInt(
1225                            parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1226                } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1227                    disabledKeyguardFeatures = Integer.parseInt(
1228                            parser.getAttributeValue(null, ATTR_VALUE));
1229                } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1230                    readAttributeValues(
1231                            parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1232                } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1233                    trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1234                } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1235                    crossProfileWidgetProviders = new ArrayList<>();
1236                    readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders);
1237                } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1238                    permittedAccessiblityServices = readPackageList(parser, tag);
1239                } else if (TAG_PERMITTED_IMES.equals(tag)) {
1240                    permittedInputMethods = readPackageList(parser, tag);
1241                } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) {
1242                    permittedNotificationListeners = readPackageList(parser, tag);
1243                } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1244                    keepUninstalledPackages = readPackageList(parser, tag);
1245                } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1246                    userRestrictions = UserRestrictionsUtils.readRestrictions(parser);
1247                } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) {
1248                    readAttributeValues(
1249                            parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1250                } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1251                    type = parser.next();
1252                    if (type == XmlPullParser.TEXT) {
1253                        shortSupportMessage = parser.getText();
1254                    } else {
1255                        Log.w(LOG_TAG, "Missing text when loading short support message");
1256                    }
1257                } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1258                    type = parser.next();
1259                    if (type == XmlPullParser.TEXT) {
1260                        longSupportMessage = parser.getText();
1261                    } else {
1262                        Log.w(LOG_TAG, "Missing text when loading long support message");
1263                    }
1264                } else if (TAG_PARENT_ADMIN.equals(tag)) {
1265                    Preconditions.checkState(!isParent);
1266
1267                    parentAdmin = new ActiveAdmin(info, /* parent */ true);
1268                    parentAdmin.readFromXml(parser);
1269                } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1270                    organizationColor = Integer.parseInt(
1271                            parser.getAttributeValue(null, ATTR_VALUE));
1272                } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1273                    type = parser.next();
1274                    if (type == XmlPullParser.TEXT) {
1275                        organizationName = parser.getText();
1276                    } else {
1277                        Log.w(LOG_TAG, "Missing text when loading organization name");
1278                    }
1279                } else if (TAG_IS_LOGOUT_BUTTON_ENABLED.equals(tag)) {
1280                    isLogoutButtonEnabled = Boolean.parseBoolean(
1281                            parser.getAttributeValue(null, ATTR_VALUE));
1282                } else {
1283                    Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1284                    XmlUtils.skipCurrentTag(parser);
1285                }
1286            }
1287        }
1288
1289        private List<String> readPackageList(XmlPullParser parser,
1290                String tag) throws XmlPullParserException, IOException {
1291            List<String> result = new ArrayList<String>();
1292            int outerDepth = parser.getDepth();
1293            int outerType;
1294            while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1295                    && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1296                if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1297                    continue;
1298                }
1299                String outerTag = parser.getName();
1300                if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1301                    String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1302                    if (packageName != null) {
1303                        result.add(packageName);
1304                    } else {
1305                        Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1306                    }
1307                } else {
1308                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
1309                }
1310            }
1311            return result;
1312        }
1313
1314        private void readAttributeValues(
1315                XmlPullParser parser, String tag, Collection<String> result)
1316                throws XmlPullParserException, IOException {
1317            result.clear();
1318            int outerDepthDAM = parser.getDepth();
1319            int typeDAM;
1320            while ((typeDAM=parser.next()) != END_DOCUMENT
1321                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1322                if (typeDAM == END_TAG || typeDAM == TEXT) {
1323                    continue;
1324                }
1325                String tagDAM = parser.getName();
1326                if (tag.equals(tagDAM)) {
1327                    result.add(parser.getAttributeValue(null, ATTR_VALUE));
1328                } else {
1329                    Slog.e(LOG_TAG, "Expected tag " + tag +  " but found " + tagDAM);
1330                }
1331            }
1332        }
1333
1334        private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1335                XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1336            int outerDepthDAM = parser.getDepth();
1337            int typeDAM;
1338            final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1339            while ((typeDAM=parser.next()) != END_DOCUMENT
1340                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1341                if (typeDAM == END_TAG || typeDAM == TEXT) {
1342                    continue;
1343                }
1344                String tagDAM = parser.getName();
1345                if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1346                    final String component = parser.getAttributeValue(null, ATTR_VALUE);
1347                    final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1348                    result.put(component, trustAgentInfo);
1349                } else {
1350                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1351                }
1352            }
1353            return result;
1354        }
1355
1356        private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1357                throws XmlPullParserException, IOException  {
1358            int outerDepthDAM = parser.getDepth();
1359            int typeDAM;
1360            TrustAgentInfo result = new TrustAgentInfo(null);
1361            while ((typeDAM=parser.next()) != END_DOCUMENT
1362                    && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1363                if (typeDAM == END_TAG || typeDAM == TEXT) {
1364                    continue;
1365                }
1366                String tagDAM = parser.getName();
1367                if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1368                    result.options = PersistableBundle.restoreFromXml(parser);
1369                } else {
1370                    Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1371                }
1372            }
1373            return result;
1374        }
1375
1376        boolean hasUserRestrictions() {
1377            return userRestrictions != null && userRestrictions.size() > 0;
1378        }
1379
1380        Bundle ensureUserRestrictions() {
1381            if (userRestrictions == null) {
1382                userRestrictions = new Bundle();
1383            }
1384            return userRestrictions;
1385        }
1386
1387        void dump(String prefix, PrintWriter pw) {
1388            pw.print(prefix); pw.print("uid="); pw.println(getUid());
1389            pw.print(prefix); pw.print("testOnlyAdmin=");
1390            pw.println(testOnlyAdmin);
1391            pw.print(prefix); pw.println("policies:");
1392            ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1393            if (pols != null) {
1394                for (int i=0; i<pols.size(); i++) {
1395                    pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
1396                }
1397            }
1398            pw.print(prefix); pw.print("passwordQuality=0x");
1399                    pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
1400            pw.print(prefix); pw.print("minimumPasswordLength=");
1401                    pw.println(minimumPasswordMetrics.length);
1402            pw.print(prefix); pw.print("passwordHistoryLength=");
1403                    pw.println(passwordHistoryLength);
1404            pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1405                    pw.println(minimumPasswordMetrics.upperCase);
1406            pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1407                    pw.println(minimumPasswordMetrics.lowerCase);
1408            pw.print(prefix); pw.print("minimumPasswordLetters=");
1409                    pw.println(minimumPasswordMetrics.letters);
1410            pw.print(prefix); pw.print("minimumPasswordNumeric=");
1411                    pw.println(minimumPasswordMetrics.numeric);
1412            pw.print(prefix); pw.print("minimumPasswordSymbols=");
1413                    pw.println(minimumPasswordMetrics.symbols);
1414            pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1415                    pw.println(minimumPasswordMetrics.nonLetter);
1416            pw.print(prefix); pw.print("maximumTimeToUnlock=");
1417                    pw.println(maximumTimeToUnlock);
1418            pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1419                    pw.println(strongAuthUnlockTimeout);
1420            pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1421                    pw.println(maximumFailedPasswordsForWipe);
1422            pw.print(prefix); pw.print("specifiesGlobalProxy=");
1423                    pw.println(specifiesGlobalProxy);
1424            pw.print(prefix); pw.print("passwordExpirationTimeout=");
1425                    pw.println(passwordExpirationTimeout);
1426            pw.print(prefix); pw.print("passwordExpirationDate=");
1427                    pw.println(passwordExpirationDate);
1428            if (globalProxySpec != null) {
1429                pw.print(prefix); pw.print("globalProxySpec=");
1430                        pw.println(globalProxySpec);
1431            }
1432            if (globalProxyExclusionList != null) {
1433                pw.print(prefix); pw.print("globalProxyEclusionList=");
1434                        pw.println(globalProxyExclusionList);
1435            }
1436            pw.print(prefix); pw.print("encryptionRequested=");
1437                    pw.println(encryptionRequested);
1438            pw.print(prefix); pw.print("disableCamera=");
1439                    pw.println(disableCamera);
1440            pw.print(prefix); pw.print("disableCallerId=");
1441                    pw.println(disableCallerId);
1442            pw.print(prefix); pw.print("disableContactsSearch=");
1443                    pw.println(disableContactsSearch);
1444            pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1445                    pw.println(disableBluetoothContactSharing);
1446            pw.print(prefix); pw.print("disableScreenCapture=");
1447                    pw.println(disableScreenCapture);
1448            pw.print(prefix); pw.print("requireAutoTime=");
1449                    pw.println(requireAutoTime);
1450            pw.print(prefix); pw.print("forceEphemeralUsers=");
1451                    pw.println(forceEphemeralUsers);
1452            pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1453                    pw.println(isNetworkLoggingEnabled);
1454            pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1455                    pw.println(disabledKeyguardFeatures);
1456            pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1457                    pw.println(crossProfileWidgetProviders);
1458            if (permittedAccessiblityServices != null) {
1459                pw.print(prefix); pw.print("permittedAccessibilityServices=");
1460                    pw.println(permittedAccessiblityServices);
1461            }
1462            if (permittedInputMethods != null) {
1463                pw.print(prefix); pw.print("permittedInputMethods=");
1464                    pw.println(permittedInputMethods);
1465            }
1466            if (permittedNotificationListeners != null) {
1467                pw.print(prefix); pw.print("permittedNotificationListeners=");
1468                pw.println(permittedNotificationListeners);
1469            }
1470            if (keepUninstalledPackages != null) {
1471                pw.print(prefix); pw.print("keepUninstalledPackages=");
1472                    pw.println(keepUninstalledPackages);
1473            }
1474            pw.print(prefix); pw.print("organizationColor=");
1475                    pw.println(organizationColor);
1476            if (organizationName != null) {
1477                pw.print(prefix); pw.print("organizationName=");
1478                    pw.println(organizationName);
1479            }
1480            pw.print(prefix); pw.println("userRestrictions:");
1481            UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
1482            pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet=");
1483                    pw.println(defaultEnabledRestrictionsAlreadySet);
1484            pw.print(prefix); pw.print("isParent=");
1485                    pw.println(isParent);
1486            if (parentAdmin != null) {
1487                pw.print(prefix);  pw.println("parentAdmin:");
1488                parentAdmin.dump(prefix + "  ", pw);
1489            }
1490        }
1491    }
1492
1493    private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1494        boolean removedAdmin = false;
1495        if (VERBOSE_LOG) {
1496            Slog.d(LOG_TAG, "Handling package changes package " + packageName
1497                    + " for user " + userHandle);
1498        }
1499        DevicePolicyData policy = getUserData(userHandle);
1500        synchronized (this) {
1501            for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1502                ActiveAdmin aa = policy.mAdminList.get(i);
1503                try {
1504                    // If we're checking all packages or if the specific one we're checking matches,
1505                    // then check if the package and receiver still exist.
1506                    final String adminPackage = aa.info.getPackageName();
1507                    if (packageName == null || packageName.equals(adminPackage)) {
1508                        if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1509                                || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1510                                PackageManager.MATCH_DIRECT_BOOT_AWARE
1511                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1512                                userHandle) == null) {
1513                            removedAdmin = true;
1514                            policy.mAdminList.remove(i);
1515                            policy.mAdminMap.remove(aa.info.getComponent());
1516                        }
1517                    }
1518                } catch (RemoteException re) {
1519                    // Shouldn't happen.
1520                }
1521            }
1522            if (removedAdmin) {
1523                validatePasswordOwnerLocked(policy);
1524            }
1525
1526            boolean removedDelegate = false;
1527
1528            // Check if a delegate was removed.
1529            for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1530                final String delegatePackage = policy.mDelegationMap.keyAt(i);
1531                if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1532                    policy.mDelegationMap.removeAt(i);
1533                    removedDelegate = true;
1534                }
1535            }
1536
1537            // If it's an owner package, we may need to refresh the bound connection.
1538            final ComponentName owner = getOwnerComponent(userHandle);
1539            if ((packageName != null) && (owner != null)
1540                    && (owner.getPackageName().equals(packageName))) {
1541                startOwnerService(userHandle, "package-broadcast");
1542            }
1543
1544            // Persist updates if the removed package was an admin or delegate.
1545            if (removedAdmin || removedDelegate) {
1546                saveSettingsLocked(policy.mUserHandle);
1547            }
1548        }
1549        if (removedAdmin) {
1550            // The removed admin might have disabled camera, so update user restrictions.
1551            pushUserRestrictions(userHandle);
1552        }
1553    }
1554
1555    private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1556        try {
1557            return targetPackage != null
1558                    && (changedPackage == null || changedPackage.equals(targetPackage))
1559                    && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1560        } catch (RemoteException e) {
1561            // Shouldn't happen
1562        }
1563
1564        return false;
1565    }
1566
1567    /**
1568     * Unit test will subclass it to inject mocks.
1569     */
1570    @VisibleForTesting
1571    static class Injector {
1572
1573        public final Context mContext;
1574
1575        Injector(Context context) {
1576            mContext = context;
1577        }
1578
1579        public boolean hasFeature() {
1580            return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1581        }
1582
1583        Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1584            final String packageName = mContext.getPackageName();
1585            return mContext.createPackageContextAsUser(packageName, 0, user);
1586        }
1587
1588        Resources getResources() {
1589            return mContext.getResources();
1590        }
1591
1592        Owners newOwners() {
1593            return new Owners(getUserManager(), getUserManagerInternal(),
1594                    getPackageManagerInternal());
1595        }
1596
1597        UserManager getUserManager() {
1598            return UserManager.get(mContext);
1599        }
1600
1601        UserManagerInternal getUserManagerInternal() {
1602            return LocalServices.getService(UserManagerInternal.class);
1603        }
1604
1605        PackageManagerInternal getPackageManagerInternal() {
1606            return LocalServices.getService(PackageManagerInternal.class);
1607        }
1608
1609        NotificationManager getNotificationManager() {
1610            return mContext.getSystemService(NotificationManager.class);
1611        }
1612
1613        IIpConnectivityMetrics getIIpConnectivityMetrics() {
1614            return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1615                ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1616        }
1617
1618        PackageManager getPackageManager() {
1619            return mContext.getPackageManager();
1620        }
1621
1622        PowerManagerInternal getPowerManagerInternal() {
1623            return LocalServices.getService(PowerManagerInternal.class);
1624        }
1625
1626        TelephonyManager getTelephonyManager() {
1627            return TelephonyManager.from(mContext);
1628        }
1629
1630        TrustManager getTrustManager() {
1631            return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1632        }
1633
1634        AlarmManager getAlarmManager() {
1635            return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1636        }
1637
1638        IWindowManager getIWindowManager() {
1639            return IWindowManager.Stub
1640                    .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1641        }
1642
1643        IActivityManager getIActivityManager() {
1644            return ActivityManager.getService();
1645        }
1646
1647        IPackageManager getIPackageManager() {
1648            return AppGlobals.getPackageManager();
1649        }
1650
1651        IBackupManager getIBackupManager() {
1652            return IBackupManager.Stub.asInterface(
1653                    ServiceManager.getService(Context.BACKUP_SERVICE));
1654        }
1655
1656        IAudioService getIAudioService() {
1657            return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1658        }
1659
1660        boolean isBuildDebuggable() {
1661            return Build.IS_DEBUGGABLE;
1662        }
1663
1664        LockPatternUtils newLockPatternUtils() {
1665            return new LockPatternUtils(mContext);
1666        }
1667
1668        boolean storageManagerIsFileBasedEncryptionEnabled() {
1669            return StorageManager.isFileEncryptedNativeOnly();
1670        }
1671
1672        boolean storageManagerIsNonDefaultBlockEncrypted() {
1673            long identity = Binder.clearCallingIdentity();
1674            try {
1675                return StorageManager.isNonDefaultBlockEncrypted();
1676            } finally {
1677                Binder.restoreCallingIdentity(identity);
1678            }
1679        }
1680
1681        boolean storageManagerIsEncrypted() {
1682            return StorageManager.isEncrypted();
1683        }
1684
1685        boolean storageManagerIsEncryptable() {
1686            return StorageManager.isEncryptable();
1687        }
1688
1689        Looper getMyLooper() {
1690            return Looper.myLooper();
1691        }
1692
1693        WifiManager getWifiManager() {
1694            return mContext.getSystemService(WifiManager.class);
1695        }
1696
1697        long binderClearCallingIdentity() {
1698            return Binder.clearCallingIdentity();
1699        }
1700
1701        void binderRestoreCallingIdentity(long token) {
1702            Binder.restoreCallingIdentity(token);
1703        }
1704
1705        int binderGetCallingUid() {
1706            return Binder.getCallingUid();
1707        }
1708
1709        int binderGetCallingPid() {
1710            return Binder.getCallingPid();
1711        }
1712
1713        UserHandle binderGetCallingUserHandle() {
1714            return Binder.getCallingUserHandle();
1715        }
1716
1717        boolean binderIsCallingUidMyUid() {
1718            return getCallingUid() == Process.myUid();
1719        }
1720
1721        void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
1722             Binder.withCleanCallingIdentity(action);
1723        }
1724
1725        final int userHandleGetCallingUserId() {
1726            return UserHandle.getUserId(binderGetCallingUid());
1727        }
1728
1729        File environmentGetUserSystemDirectory(int userId) {
1730            return Environment.getUserSystemDirectory(userId);
1731        }
1732
1733        void powerManagerGoToSleep(long time, int reason, int flags) {
1734            mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1735        }
1736
1737        void powerManagerReboot(String reason) {
1738            mContext.getSystemService(PowerManager.class).reboot(reason);
1739        }
1740
1741        void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1742                boolean wipeEuicc) throws IOException {
1743            RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc);
1744        }
1745
1746        boolean systemPropertiesGetBoolean(String key, boolean def) {
1747            return SystemProperties.getBoolean(key, def);
1748        }
1749
1750        long systemPropertiesGetLong(String key, long def) {
1751            return SystemProperties.getLong(key, def);
1752        }
1753
1754        String systemPropertiesGet(String key, String def) {
1755            return SystemProperties.get(key, def);
1756        }
1757
1758        String systemPropertiesGet(String key) {
1759            return SystemProperties.get(key);
1760        }
1761
1762        void systemPropertiesSet(String key, String value) {
1763            SystemProperties.set(key, value);
1764        }
1765
1766        boolean userManagerIsSplitSystemUser() {
1767            return UserManager.isSplitSystemUser();
1768        }
1769
1770        String getDevicePolicyFilePathForSystemUser() {
1771            return "/data/system/";
1772        }
1773
1774        PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1775                @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
1776            return PendingIntent.getActivityAsUser(
1777                    context, requestCode, intent, flags, options, user);
1778        }
1779
1780        void registerContentObserver(Uri uri, boolean notifyForDescendents,
1781                ContentObserver observer, int userHandle) {
1782            mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1783                    observer, userHandle);
1784        }
1785
1786        int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1787            return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1788                    name, def, userHandle);
1789        }
1790
1791        String settingsSecureGetStringForUser(String name, int userHandle) {
1792            return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
1793                    userHandle);
1794        }
1795
1796        void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1797            Settings.Secure.putIntForUser(mContext.getContentResolver(),
1798                    name, value, userHandle);
1799        }
1800
1801        void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1802            Settings.Secure.putStringForUser(mContext.getContentResolver(),
1803                    name, value, userHandle);
1804        }
1805
1806        void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1807            Settings.Global.putStringForUser(mContext.getContentResolver(),
1808                    name, value, userHandle);
1809        }
1810
1811        void settingsSecurePutInt(String name, int value) {
1812            Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1813        }
1814
1815        int settingsGlobalGetInt(String name, int def) {
1816            return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1817        }
1818
1819        String settingsGlobalGetString(String name) {
1820            return Settings.Global.getString(mContext.getContentResolver(), name);
1821        }
1822
1823        void settingsGlobalPutInt(String name, int value) {
1824            Settings.Global.putInt(mContext.getContentResolver(), name, value);
1825        }
1826
1827        void settingsSecurePutString(String name, String value) {
1828            Settings.Secure.putString(mContext.getContentResolver(), name, value);
1829        }
1830
1831        void settingsGlobalPutString(String name, String value) {
1832            Settings.Global.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 boolean setTime(ComponentName who, long millis) {
9151        Preconditions.checkNotNull(who, "ComponentName is null in setTime");
9152        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9153        // Don't allow set time when auto time is on.
9154        if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
9155            return false;
9156        }
9157        mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
9158        return true;
9159    }
9160
9161    @Override
9162    public boolean setTimeZone(ComponentName who, String timeZone) {
9163        Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone");
9164        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9165        // Don't allow set timezone when auto timezone is on.
9166        if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
9167            return false;
9168        }
9169        mInjector.binderWithCleanCallingIdentity(() ->
9170            mInjector.getAlarmManager().setTimeZone(timeZone));
9171        return true;
9172    }
9173
9174    @Override
9175    public void setSecureSetting(ComponentName who, String setting, String value) {
9176        Preconditions.checkNotNull(who, "ComponentName is null");
9177        int callingUserId = mInjector.userHandleGetCallingUserId();
9178
9179        synchronized (this) {
9180            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9181
9182            if (isDeviceOwner(who, callingUserId)) {
9183                if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)
9184                        && !isCurrentUserDemo()) {
9185                    throw new SecurityException(String.format(
9186                            "Permission denial: Device owners cannot update %1$s", setting));
9187                }
9188            } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) {
9189                throw new SecurityException(String.format(
9190                        "Permission denial: Profile owners cannot update %1$s", setting));
9191            }
9192            if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
9193                if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
9194                    throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
9195                            + " is deprecated. Please use the user restriction "
9196                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead.");
9197                }
9198                if (!mUserManager.isManagedProfile(callingUserId)) {
9199                    Slog.e(LOG_TAG, "Ignoring setSecureSetting request for "
9200                            + setting + ". User restriction "
9201                            + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
9202                            + " should be used instead.");
9203                } else {
9204                    try {
9205                        setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
9206                                (Integer.parseInt(value) == 0) ? true : false);
9207                    } catch (NumberFormatException exc) {
9208                        Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
9209                    }
9210                }
9211                return;
9212            }
9213            long id = mInjector.binderClearCallingIdentity();
9214            try {
9215                if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
9216                    final String currentValue = mInjector.settingsSecureGetStringForUser(
9217                            Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
9218                    if (!TextUtils.equals(currentValue, value)) {
9219                        // Tell the content observer that the next change will be due to the owner
9220                        // changing the value. There is a small race condition here that we cannot
9221                        // avoid: Change notifications are sent asynchronously, so it is possible
9222                        // that there are prior notifications queued up before the one we are about
9223                        // to trigger. This is a corner case that will have no impact in practice.
9224                        mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
9225                    }
9226                    getUserData(callingUserId).mCurrentInputMethodSet = true;
9227                    saveSettingsLocked(callingUserId);
9228                }
9229                mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
9230            } finally {
9231                mInjector.binderRestoreCallingIdentity(id);
9232            }
9233        }
9234    }
9235
9236    @Override
9237    public void setMasterVolumeMuted(ComponentName who, boolean on) {
9238        Preconditions.checkNotNull(who, "ComponentName is null");
9239        synchronized (this) {
9240            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9241            setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
9242        }
9243    }
9244
9245    @Override
9246    public boolean isMasterVolumeMuted(ComponentName who) {
9247        Preconditions.checkNotNull(who, "ComponentName is null");
9248        synchronized (this) {
9249            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9250
9251            AudioManager audioManager =
9252                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
9253            return audioManager.isMasterMute();
9254        }
9255    }
9256
9257    @Override
9258    public void setUserIcon(ComponentName who, Bitmap icon) {
9259        synchronized (this) {
9260            Preconditions.checkNotNull(who, "ComponentName is null");
9261            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9262
9263            int userId = UserHandle.getCallingUserId();
9264            long id = mInjector.binderClearCallingIdentity();
9265            try {
9266                mUserManagerInternal.setUserIcon(userId, icon);
9267            } finally {
9268                mInjector.binderRestoreCallingIdentity(id);
9269            }
9270        }
9271    }
9272
9273    @Override
9274    public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
9275        Preconditions.checkNotNull(who, "ComponentName is null");
9276        final int userId = mInjector.userHandleGetCallingUserId();
9277        synchronized (this) {
9278            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9279            if (!isUserAffiliatedWithDeviceLocked(userId)) {
9280                throw new SecurityException("Admin " + who +
9281                        " is neither the device owner or affiliated user's profile owner.");
9282            }
9283        }
9284
9285        long ident = mInjector.binderClearCallingIdentity();
9286        try {
9287            // disallow disabling the keyguard if a password is currently set
9288            if (disabled && mLockPatternUtils.isSecure(userId)) {
9289                return false;
9290            }
9291            mLockPatternUtils.setLockScreenDisabled(disabled, userId);
9292            mInjector.getIWindowManager().dismissKeyguard(null);
9293        } catch (RemoteException e) {
9294            // Same process, does not happen.
9295        } finally {
9296            mInjector.binderRestoreCallingIdentity(ident);
9297        }
9298        return true;
9299    }
9300
9301    @Override
9302    public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
9303        int userId = UserHandle.getCallingUserId();
9304        synchronized (this) {
9305            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9306            if (!isUserAffiliatedWithDeviceLocked(userId)) {
9307                throw new SecurityException("Admin " + who +
9308                        " is neither the device owner or affiliated user's profile owner.");
9309            }
9310            DevicePolicyData policy = getUserData(userId);
9311            if (policy.mStatusBarDisabled != disabled) {
9312                boolean isLockTaskMode = false;
9313                try {
9314                    isLockTaskMode = mInjector.getIActivityManager().getLockTaskModeState()
9315                            != LOCK_TASK_MODE_NONE;
9316                } catch (RemoteException e) {
9317                    Slog.e(LOG_TAG, "Failed to get LockTask mode");
9318                }
9319                if (!isLockTaskMode) {
9320                    if (!setStatusBarDisabledInternal(disabled, userId)) {
9321                        return false;
9322                    }
9323                }
9324                policy.mStatusBarDisabled = disabled;
9325                saveSettingsLocked(userId);
9326            }
9327        }
9328        return true;
9329    }
9330
9331    private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
9332        long ident = mInjector.binderClearCallingIdentity();
9333        try {
9334            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
9335                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
9336            if (statusBarService != null) {
9337                int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
9338                int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
9339                statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
9340                statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
9341                return true;
9342            }
9343        } catch (RemoteException e) {
9344            Slog.e(LOG_TAG, "Failed to disable the status bar", e);
9345        } finally {
9346            mInjector.binderRestoreCallingIdentity(ident);
9347        }
9348        return false;
9349    }
9350
9351    /**
9352     * We need to update the internal state of whether a user has completed setup or a
9353     * device has paired once. After that, we ignore any changes that reset the
9354     * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
9355     * as we don't trust any apps that might try to reset them.
9356     * <p>
9357     * Unfortunately, we don't know which user's setup state was changed, so we write all of
9358     * them.
9359     */
9360    void updateUserSetupCompleteAndPaired() {
9361        List<UserInfo> users = mUserManager.getUsers(true);
9362        final int N = users.size();
9363        for (int i = 0; i < N; i++) {
9364            int userHandle = users.get(i).id;
9365            if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
9366                    userHandle) != 0) {
9367                DevicePolicyData policy = getUserData(userHandle);
9368                if (!policy.mUserSetupComplete) {
9369                    policy.mUserSetupComplete = true;
9370                    synchronized (this) {
9371                        saveSettingsLocked(userHandle);
9372                    }
9373                }
9374            }
9375            if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
9376                    userHandle) != 0) {
9377                DevicePolicyData policy = getUserData(userHandle);
9378                if (!policy.mPaired) {
9379                    policy.mPaired = true;
9380                    synchronized (this) {
9381                        saveSettingsLocked(userHandle);
9382                    }
9383                }
9384            }
9385        }
9386    }
9387
9388    private class SetupContentObserver extends ContentObserver {
9389        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
9390                Settings.Secure.USER_SETUP_COMPLETE);
9391        private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
9392                Settings.Global.DEVICE_PROVISIONED);
9393        private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
9394        private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
9395                Settings.Secure.DEFAULT_INPUT_METHOD);
9396
9397        @GuardedBy("DevicePolicyManagerService.this")
9398        private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
9399
9400        public SetupContentObserver(Handler handler) {
9401            super(handler);
9402        }
9403
9404        void register() {
9405            mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
9406            mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
9407            if (mIsWatch) {
9408                mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
9409            }
9410            mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
9411        }
9412
9413        private void addPendingChangeByOwnerLocked(int userId) {
9414            mUserIdsWithPendingChangesByOwner.add(userId);
9415        }
9416
9417        @Override
9418        public void onChange(boolean selfChange, Uri uri, int userId) {
9419            if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
9420                updateUserSetupCompleteAndPaired();
9421            } else if (mDeviceProvisioned.equals(uri)) {
9422                synchronized (DevicePolicyManagerService.this) {
9423                    // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
9424                    // is delayed until device is marked as provisioned.
9425                    setDeviceOwnerSystemPropertyLocked();
9426                }
9427            } else if (mDefaultImeChanged.equals(uri)) {
9428                synchronized (DevicePolicyManagerService.this) {
9429                    if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
9430                        // This change notification was triggered by the owner changing the current
9431                        // IME. Ignore it.
9432                        mUserIdsWithPendingChangesByOwner.remove(userId);
9433                    } else {
9434                        // This change notification was triggered by the user manually changing the
9435                        // current IME.
9436                        getUserData(userId).mCurrentInputMethodSet = false;
9437                        saveSettingsLocked(userId);
9438                    }
9439                }
9440            }
9441        }
9442    }
9443
9444    @VisibleForTesting
9445    final class LocalService extends DevicePolicyManagerInternal {
9446        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
9447
9448        @Override
9449        public List<String> getCrossProfileWidgetProviders(int profileId) {
9450            synchronized (DevicePolicyManagerService.this) {
9451                if (mOwners == null) {
9452                    return Collections.emptyList();
9453                }
9454                ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
9455                if (ownerComponent == null) {
9456                    return Collections.emptyList();
9457                }
9458
9459                DevicePolicyData policy = getUserDataUnchecked(profileId);
9460                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
9461
9462                if (admin == null || admin.crossProfileWidgetProviders == null
9463                        || admin.crossProfileWidgetProviders.isEmpty()) {
9464                    return Collections.emptyList();
9465                }
9466
9467                return admin.crossProfileWidgetProviders;
9468            }
9469        }
9470
9471        @Override
9472        public void addOnCrossProfileWidgetProvidersChangeListener(
9473                OnCrossProfileWidgetProvidersChangeListener listener) {
9474            synchronized (DevicePolicyManagerService.this) {
9475                if (mWidgetProviderListeners == null) {
9476                    mWidgetProviderListeners = new ArrayList<>();
9477                }
9478                if (!mWidgetProviderListeners.contains(listener)) {
9479                    mWidgetProviderListeners.add(listener);
9480                }
9481            }
9482        }
9483
9484        @Override
9485        public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
9486            synchronized(DevicePolicyManagerService.this) {
9487                return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
9488            }
9489        }
9490
9491        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
9492            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
9493            synchronized (DevicePolicyManagerService.this) {
9494                listeners = new ArrayList<>(mWidgetProviderListeners);
9495            }
9496            final int listenerCount = listeners.size();
9497            for (int i = 0; i < listenerCount; i++) {
9498                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
9499                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
9500            }
9501        }
9502
9503        @Override
9504        public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
9505            // This method is called from AM with its lock held, so don't take the DPMS lock.
9506            // b/29242568
9507
9508            ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9509            if (profileOwner != null) {
9510                return DevicePolicyManagerService.this
9511                        .createShowAdminSupportIntent(profileOwner, userId);
9512            }
9513
9514            final Pair<Integer, ComponentName> deviceOwner =
9515                    mOwners.getDeviceOwnerUserIdAndComponent();
9516            if (deviceOwner != null && deviceOwner.first == userId) {
9517                return DevicePolicyManagerService.this
9518                        .createShowAdminSupportIntent(deviceOwner.second, userId);
9519            }
9520
9521            // We're not specifying the device admin because there isn't one.
9522            if (useDefaultIfNoAdmin) {
9523                return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9524            }
9525            return null;
9526        }
9527
9528        @Override
9529        public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
9530            int source;
9531            long ident = mInjector.binderClearCallingIdentity();
9532            try {
9533                source = mUserManager.getUserRestrictionSource(userRestriction,
9534                        UserHandle.of(userId));
9535            } finally {
9536                mInjector.binderRestoreCallingIdentity(ident);
9537            }
9538            if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
9539                /*
9540                 * In this case, the user restriction is enforced by the system.
9541                 * So we won't show an admin support intent, even if it is also
9542                 * enforced by a profile/device owner.
9543                 */
9544                return null;
9545            }
9546            boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
9547            boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
9548            if (enforcedByDo && enforcedByPo) {
9549                // In this case, we'll show an admin support dialog that does not
9550                // specify the admin.
9551                return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
9552            } else if (enforcedByPo) {
9553                final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
9554                if (profileOwner != null) {
9555                    return DevicePolicyManagerService.this
9556                            .createShowAdminSupportIntent(profileOwner, userId);
9557                }
9558                // This could happen if another thread has changed the profile owner since we called
9559                // getUserRestrictionSource
9560                return null;
9561            } else if (enforcedByDo) {
9562                final Pair<Integer, ComponentName> deviceOwner
9563                        = mOwners.getDeviceOwnerUserIdAndComponent();
9564                if (deviceOwner != null) {
9565                    return DevicePolicyManagerService.this
9566                            .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
9567                }
9568                // This could happen if another thread has changed the device owner since we called
9569                // getUserRestrictionSource
9570                return null;
9571            }
9572            return null;
9573        }
9574
9575        @Override
9576        public boolean isUserAffiliatedWithDevice(int userId) {
9577            return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
9578        }
9579    }
9580
9581    private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
9582        // This method is called with AMS lock held, so don't take DPMS lock
9583        final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
9584        intent.putExtra(Intent.EXTRA_USER_ID, userId);
9585        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
9586        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9587        return intent;
9588    }
9589
9590    @Override
9591    public Intent createAdminSupportIntent(String restriction) {
9592        Preconditions.checkNotNull(restriction);
9593        final int uid = mInjector.binderGetCallingUid();
9594        final int userId = UserHandle.getUserId(uid);
9595        Intent intent = null;
9596        if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
9597                DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) {
9598            synchronized(this) {
9599                final DevicePolicyData policy = getUserData(userId);
9600                final int N = policy.mAdminList.size();
9601                for (int i = 0; i < N; i++) {
9602                    final ActiveAdmin admin = policy.mAdminList.get(i);
9603                    if ((admin.disableCamera &&
9604                                DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
9605                        (admin.disableScreenCapture && DevicePolicyManager
9606                                .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) {
9607                        intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
9608                        break;
9609                    }
9610                }
9611                // For the camera, a device owner on a different user can disable it globally,
9612                // so we need an additional check.
9613                if (intent == null
9614                        && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
9615                    final ActiveAdmin admin = getDeviceOwnerAdminLocked();
9616                    if (admin != null && admin.disableCamera) {
9617                        intent = createShowAdminSupportIntent(admin.info.getComponent(),
9618                                mOwners.getDeviceOwnerUserId());
9619                    }
9620                }
9621            }
9622        } else {
9623            // if valid, |restriction| can only be a user restriction
9624            intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
9625        }
9626        if (intent != null) {
9627            intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
9628        }
9629        return intent;
9630    }
9631
9632    /**
9633     * Returns true if specified admin is allowed to limit passwords and has a
9634     * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
9635     */
9636    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
9637        if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
9638            return false;
9639        }
9640        return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
9641    }
9642
9643    @Override
9644    public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
9645        if (policy != null && !policy.isValid()) {
9646            throw new IllegalArgumentException("Invalid system update policy.");
9647        }
9648        synchronized (this) {
9649            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9650            if (policy == null) {
9651                mOwners.clearSystemUpdatePolicy();
9652            } else {
9653                mOwners.setSystemUpdatePolicy(policy);
9654            }
9655            mOwners.writeDeviceOwner();
9656        }
9657        mContext.sendBroadcastAsUser(
9658                new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
9659                UserHandle.SYSTEM);
9660    }
9661
9662    @Override
9663    public SystemUpdatePolicy getSystemUpdatePolicy() {
9664        synchronized (this) {
9665            SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
9666            if (policy != null && !policy.isValid()) {
9667                Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
9668                return null;
9669            }
9670            return policy;
9671        }
9672    }
9673
9674    /**
9675     * Checks if the caller of the method is the device owner app.
9676     *
9677     * @param callerUid UID of the caller.
9678     * @return true if the caller is the device owner app
9679     */
9680    @VisibleForTesting
9681    boolean isCallerDeviceOwner(int callerUid) {
9682        synchronized (this) {
9683            if (!mOwners.hasDeviceOwner()) {
9684                return false;
9685            }
9686            if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
9687                return false;
9688            }
9689            final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
9690                    .getPackageName();
9691                try {
9692                    String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid);
9693                    for (String pkg : pkgs) {
9694                        if (deviceOwnerPackageName.equals(pkg)) {
9695                            return true;
9696                        }
9697                    }
9698                } catch (RemoteException e) {
9699                    return false;
9700                }
9701        }
9702
9703        return false;
9704    }
9705
9706    @Override
9707    public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
9708        mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
9709                "Only the system update service can broadcast update information");
9710
9711        if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
9712            Slog.w(LOG_TAG, "Only the system update service in the system user " +
9713                    "can broadcast update information.");
9714            return;
9715        }
9716
9717        if (!mOwners.saveSystemUpdateInfo(info)) {
9718            // Pending system update hasn't changed, don't send duplicate notification.
9719            return;
9720        }
9721
9722        final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
9723                .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
9724                        info == null ? -1 : info.getReceivedTime());
9725
9726        final long ident = mInjector.binderClearCallingIdentity();
9727        try {
9728            synchronized (this) {
9729                // Broadcast to device owner first if there is one.
9730                if (mOwners.hasDeviceOwner()) {
9731                    final UserHandle deviceOwnerUser =
9732                            UserHandle.of(mOwners.getDeviceOwnerUserId());
9733                    intent.setComponent(mOwners.getDeviceOwnerComponent());
9734                    mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
9735                }
9736            }
9737            // Get running users.
9738            final int runningUserIds[];
9739            try {
9740                runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
9741            } catch (RemoteException e) {
9742                // Shouldn't happen.
9743                Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
9744                return;
9745            }
9746            // Send broadcasts to corresponding profile owners if any.
9747            for (final int userId : runningUserIds) {
9748                synchronized (this) {
9749                    final ComponentName profileOwnerPackage =
9750                            mOwners.getProfileOwnerComponent(userId);
9751                    if (profileOwnerPackage != null) {
9752                        intent.setComponent(profileOwnerPackage);
9753                        mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
9754                    }
9755                }
9756            }
9757        } finally {
9758            mInjector.binderRestoreCallingIdentity(ident);
9759        }
9760    }
9761
9762    @Override
9763    public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
9764        Preconditions.checkNotNull(admin, "ComponentName is null");
9765        enforceProfileOrDeviceOwner(admin);
9766
9767        return mOwners.getSystemUpdateInfo();
9768    }
9769
9770    @Override
9771    public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
9772            throws RemoteException {
9773        int userId = UserHandle.getCallingUserId();
9774        synchronized (this) {
9775            // Ensure the caller is a DO/PO or a permission grant state delegate.
9776            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9777                    DELEGATION_PERMISSION_GRANT);
9778            DevicePolicyData userPolicy = getUserData(userId);
9779            if (userPolicy.mPermissionPolicy != policy) {
9780                userPolicy.mPermissionPolicy = policy;
9781                saveSettingsLocked(userId);
9782            }
9783        }
9784    }
9785
9786    @Override
9787    public int getPermissionPolicy(ComponentName admin) throws RemoteException {
9788        int userId = UserHandle.getCallingUserId();
9789        synchronized (this) {
9790            DevicePolicyData userPolicy = getUserData(userId);
9791            return userPolicy.mPermissionPolicy;
9792        }
9793    }
9794
9795    @Override
9796    public boolean setPermissionGrantState(ComponentName admin, String callerPackage,
9797            String packageName, String permission, int grantState) throws RemoteException {
9798        UserHandle user = mInjector.binderGetCallingUserHandle();
9799        synchronized (this) {
9800            // Ensure the caller is a DO/PO or a permission grant state delegate.
9801            enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9802                    DELEGATION_PERMISSION_GRANT);
9803            long ident = mInjector.binderClearCallingIdentity();
9804            try {
9805                if (getTargetSdk(packageName, user.getIdentifier())
9806                        < android.os.Build.VERSION_CODES.M) {
9807                    return false;
9808                }
9809                if (!isRuntimePermission(permission)) {
9810                    return false;
9811                }
9812                final PackageManager packageManager = mInjector.getPackageManager();
9813                switch (grantState) {
9814                    case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
9815                        mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
9816                                permission, user.getIdentifier(), true /* override policy */);
9817                        packageManager.updatePermissionFlags(permission, packageName,
9818                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9819                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9820                    } break;
9821
9822                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
9823                        mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
9824                                permission, user.getIdentifier(), true /* override policy */);
9825                        packageManager.updatePermissionFlags(permission, packageName,
9826                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
9827                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
9828                    } break;
9829
9830                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
9831                        packageManager.updatePermissionFlags(permission, packageName,
9832                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
9833                    } break;
9834                }
9835                return true;
9836            } catch (SecurityException se) {
9837                return false;
9838            } catch (NameNotFoundException e) {
9839                return false;
9840            } finally {
9841                mInjector.binderRestoreCallingIdentity(ident);
9842            }
9843        }
9844    }
9845
9846    @Override
9847    public int getPermissionGrantState(ComponentName admin, String callerPackage,
9848            String packageName, String permission) throws RemoteException {
9849        PackageManager packageManager = mInjector.getPackageManager();
9850
9851        UserHandle user = mInjector.binderGetCallingUserHandle();
9852        if (!isCallerWithSystemUid()) {
9853            // Ensure the caller is a DO/PO or a permission grant state delegate.
9854            enforceCanManageScope(admin, callerPackage,
9855                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT);
9856        }
9857        synchronized (this) {
9858            long ident = mInjector.binderClearCallingIdentity();
9859            try {
9860                int granted = mIPackageManager.checkPermission(permission,
9861                        packageName, user.getIdentifier());
9862                int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
9863                if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
9864                        != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
9865                    // Not controlled by policy
9866                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
9867                } else {
9868                    // Policy controlled so return result based on permission grant state
9869                    return granted == PackageManager.PERMISSION_GRANTED
9870                            ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
9871                            : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
9872                }
9873            } finally {
9874                mInjector.binderRestoreCallingIdentity(ident);
9875            }
9876        }
9877    }
9878
9879    boolean isPackageInstalledForUser(String packageName, int userHandle) {
9880        try {
9881            PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
9882                    userHandle);
9883            return (pi != null) && (pi.applicationInfo.flags != 0);
9884        } catch (RemoteException re) {
9885            throw new RuntimeException("Package manager has died", re);
9886        }
9887    }
9888
9889    public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
9890        final PackageManager packageManager = mInjector.getPackageManager();
9891        PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
9892        return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
9893                == PermissionInfo.PROTECTION_DANGEROUS;
9894    }
9895
9896    @Override
9897    public boolean isProvisioningAllowed(String action, String packageName) {
9898        Preconditions.checkNotNull(packageName);
9899
9900        final int callingUid = mInjector.binderGetCallingUid();
9901        final long ident = mInjector.binderClearCallingIdentity();
9902        try {
9903            final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
9904                    packageName, UserHandle.getUserId(callingUid));
9905            Preconditions.checkArgument(callingUid == uidForPackage,
9906                    "Caller uid doesn't match the one for the provided package.");
9907        } catch (NameNotFoundException e) {
9908            throw new IllegalArgumentException("Invalid package provided " + packageName, e);
9909        } finally {
9910            mInjector.binderRestoreCallingIdentity(ident);
9911        }
9912
9913        return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
9914    }
9915
9916    @Override
9917    public int checkProvisioningPreCondition(String action, String packageName) {
9918        Preconditions.checkNotNull(packageName);
9919        enforceCanManageProfileAndDeviceOwners();
9920        return checkProvisioningPreConditionSkipPermission(action, packageName);
9921    }
9922
9923    private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
9924        if (!mHasFeature) {
9925            return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
9926        }
9927
9928        final int callingUserId = mInjector.userHandleGetCallingUserId();
9929        if (action != null) {
9930            switch (action) {
9931                case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
9932                    return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
9933                case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
9934                    return checkDeviceOwnerProvisioningPreCondition(callingUserId);
9935                case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
9936                    return checkManagedUserProvisioningPreCondition(callingUserId);
9937                case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
9938                    return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
9939            }
9940        }
9941        throw new IllegalArgumentException("Unknown provisioning action " + action);
9942    }
9943
9944    /**
9945     * The device owner can only be set before the setup phase of the primary user has completed,
9946     * except for adb command if no accounts or additional users are present on the device.
9947     */
9948    private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
9949            int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
9950        if (mOwners.hasDeviceOwner()) {
9951            return CODE_HAS_DEVICE_OWNER;
9952        }
9953        if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
9954            return CODE_USER_HAS_PROFILE_OWNER;
9955        }
9956        if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
9957            return CODE_USER_NOT_RUNNING;
9958        }
9959        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
9960            return CODE_HAS_PAIRED;
9961        }
9962        if (isAdb) {
9963            // if shell command runs after user setup completed check device status. Otherwise, OK.
9964            if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
9965                if (!mInjector.userManagerIsSplitSystemUser()) {
9966                    if (mUserManager.getUserCount() > 1) {
9967                        return CODE_NONSYSTEM_USER_EXISTS;
9968                    }
9969                    if (hasIncompatibleAccountsOrNonAdb) {
9970                        return CODE_ACCOUNTS_NOT_EMPTY;
9971                    }
9972                } else {
9973                    // STOPSHIP Do proper check in split user mode
9974                }
9975            }
9976            return CODE_OK;
9977        } else {
9978            if (!mInjector.userManagerIsSplitSystemUser()) {
9979                // In non-split user mode, DO has to be user 0
9980                if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
9981                    return CODE_NOT_SYSTEM_USER;
9982                }
9983                // In non-split user mode, only provision DO before setup wizard completes
9984                if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
9985                    return CODE_USER_SETUP_COMPLETED;
9986                }
9987            } else {
9988                // STOPSHIP Do proper check in split user mode
9989            }
9990            return CODE_OK;
9991        }
9992    }
9993
9994    private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
9995        synchronized (this) {
9996            // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
9997            return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
9998                    deviceOwnerUserId, /* isAdb= */ false,
9999                    /* hasIncompatibleAccountsOrNonAdb=*/ true);
10000        }
10001    }
10002
10003    private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
10004        if (!hasFeatureManagedUsers()) {
10005            return CODE_MANAGED_USERS_NOT_SUPPORTED;
10006        }
10007        if (callingUserId == UserHandle.USER_SYSTEM
10008                && mInjector.userManagerIsSplitSystemUser()) {
10009            // Managed-profiles cannot be setup on the system user.
10010            return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
10011        }
10012        if (getProfileOwner(callingUserId) != null) {
10013            // Managed user cannot have a managed profile.
10014            return CODE_USER_HAS_PROFILE_OWNER;
10015        }
10016
10017        final long ident = mInjector.binderClearCallingIdentity();
10018        try {
10019            final UserHandle callingUserHandle = UserHandle.of(callingUserId);
10020            final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
10021            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
10022                    callingUserHandle)) {
10023                // An admin can initiate provisioning if it has set the restriction.
10024                if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
10025                        UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
10026                    return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
10027                }
10028            }
10029            boolean canRemoveProfile = true;
10030            if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
10031                    callingUserHandle)) {
10032                // We can remove a profile if the admin itself has set the restriction.
10033                if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
10034                        UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
10035                        callingUserId)) {
10036                    canRemoveProfile = false;
10037                }
10038            }
10039            if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
10040                return CODE_CANNOT_ADD_MANAGED_PROFILE;
10041            }
10042        } finally {
10043            mInjector.binderRestoreCallingIdentity(ident);
10044        }
10045        return CODE_OK;
10046    }
10047
10048    private ComponentName getOwnerComponent(String packageName, int userId) {
10049        if (isDeviceOwnerPackage(packageName, userId)) {
10050            return mOwners.getDeviceOwnerComponent();
10051        }
10052        if (isProfileOwnerPackage(packageName, userId)) {
10053            return mOwners.getProfileOwnerComponent(userId);
10054        }
10055        return null;
10056    }
10057
10058    /**
10059     * Return device owner or profile owner set on a given user.
10060     */
10061    private @Nullable ComponentName getOwnerComponent(int userId) {
10062        synchronized (this) {
10063            if (mOwners.getDeviceOwnerUserId() == userId) {
10064                return mOwners.getDeviceOwnerComponent();
10065            }
10066            if (mOwners.hasProfileOwner(userId)) {
10067                return mOwners.getProfileOwnerComponent(userId);
10068            }
10069        }
10070        return null;
10071    }
10072
10073    private int checkManagedUserProvisioningPreCondition(int callingUserId) {
10074        if (!hasFeatureManagedUsers()) {
10075            return CODE_MANAGED_USERS_NOT_SUPPORTED;
10076        }
10077        if (!mInjector.userManagerIsSplitSystemUser()) {
10078            // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
10079            return CODE_NOT_SYSTEM_USER_SPLIT;
10080        }
10081        if (callingUserId == UserHandle.USER_SYSTEM) {
10082            // System user cannot be a managed user.
10083            return CODE_SYSTEM_USER;
10084        }
10085        if (hasUserSetupCompleted(callingUserId)) {
10086            return CODE_USER_SETUP_COMPLETED;
10087        }
10088        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
10089            return CODE_HAS_PAIRED;
10090        }
10091        return CODE_OK;
10092    }
10093
10094    private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
10095        if (!mInjector.userManagerIsSplitSystemUser()) {
10096            // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
10097            return CODE_NOT_SYSTEM_USER_SPLIT;
10098        }
10099        return checkDeviceOwnerProvisioningPreCondition(callingUserId);
10100    }
10101
10102    private boolean hasFeatureManagedUsers() {
10103        try {
10104            return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
10105        } catch (RemoteException e) {
10106            return false;
10107        }
10108    }
10109
10110    @Override
10111    public String getWifiMacAddress(ComponentName admin) {
10112        // Make sure caller has DO.
10113        synchronized (this) {
10114            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10115        }
10116
10117        final long ident = mInjector.binderClearCallingIdentity();
10118        try {
10119            final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
10120            if (wifiInfo == null) {
10121                return null;
10122            }
10123            return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
10124        } finally {
10125            mInjector.binderRestoreCallingIdentity(ident);
10126        }
10127    }
10128
10129    /**
10130     * Returns the target sdk version number that the given packageName was built for
10131     * in the given user.
10132     */
10133    private int getTargetSdk(String packageName, int userId) {
10134        final ApplicationInfo ai;
10135        try {
10136            ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
10137            final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
10138            return targetSdkVersion;
10139        } catch (RemoteException e) {
10140            // Shouldn't happen
10141            return 0;
10142        }
10143    }
10144
10145    @Override
10146    public boolean isManagedProfile(ComponentName admin) {
10147        enforceProfileOrDeviceOwner(admin);
10148        return isManagedProfile(mInjector.userHandleGetCallingUserId());
10149    }
10150
10151    @Override
10152    public boolean isSystemOnlyUser(ComponentName admin) {
10153        synchronized (this) {
10154            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10155        }
10156        final int callingUserId = mInjector.userHandleGetCallingUserId();
10157        return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
10158    }
10159
10160    @Override
10161    public void reboot(ComponentName admin) {
10162        Preconditions.checkNotNull(admin);
10163        // Make sure caller has DO.
10164        synchronized (this) {
10165            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10166        }
10167        long ident = mInjector.binderClearCallingIdentity();
10168        try {
10169            // Make sure there are no ongoing calls on the device.
10170            if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
10171                throw new IllegalStateException("Cannot be called with ongoing call on the device");
10172            }
10173            mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
10174        } finally {
10175            mInjector.binderRestoreCallingIdentity(ident);
10176        }
10177    }
10178
10179    @Override
10180    public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
10181        if (!mHasFeature) {
10182            return;
10183        }
10184        Preconditions.checkNotNull(who, "ComponentName is null");
10185        final int userHandle = mInjector.userHandleGetCallingUserId();
10186        synchronized (this) {
10187            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10188                    mInjector.binderGetCallingUid());
10189            if (!TextUtils.equals(admin.shortSupportMessage, message)) {
10190                admin.shortSupportMessage = message;
10191                saveSettingsLocked(userHandle);
10192            }
10193        }
10194    }
10195
10196    @Override
10197    public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
10198        if (!mHasFeature) {
10199            return null;
10200        }
10201        Preconditions.checkNotNull(who, "ComponentName is null");
10202        synchronized (this) {
10203            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10204                    mInjector.binderGetCallingUid());
10205            return admin.shortSupportMessage;
10206        }
10207    }
10208
10209    @Override
10210    public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
10211        if (!mHasFeature) {
10212            return;
10213        }
10214        Preconditions.checkNotNull(who, "ComponentName is null");
10215        final int userHandle = mInjector.userHandleGetCallingUserId();
10216        synchronized (this) {
10217            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10218                    mInjector.binderGetCallingUid());
10219            if (!TextUtils.equals(admin.longSupportMessage, message)) {
10220                admin.longSupportMessage = message;
10221                saveSettingsLocked(userHandle);
10222            }
10223        }
10224    }
10225
10226    @Override
10227    public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
10228        if (!mHasFeature) {
10229            return null;
10230        }
10231        Preconditions.checkNotNull(who, "ComponentName is null");
10232        synchronized (this) {
10233            ActiveAdmin admin = getActiveAdminForUidLocked(who,
10234                    mInjector.binderGetCallingUid());
10235            return admin.longSupportMessage;
10236        }
10237    }
10238
10239    @Override
10240    public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
10241        if (!mHasFeature) {
10242            return null;
10243        }
10244        Preconditions.checkNotNull(who, "ComponentName is null");
10245        if (!isCallerWithSystemUid()) {
10246            throw new SecurityException("Only the system can query support message for user");
10247        }
10248        synchronized (this) {
10249            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
10250            if (admin != null) {
10251                return admin.shortSupportMessage;
10252            }
10253        }
10254        return null;
10255    }
10256
10257    @Override
10258    public CharSequence getLongSupportMessageForUser(@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.longSupportMessage;
10270            }
10271        }
10272        return null;
10273    }
10274
10275    @Override
10276    public void setOrganizationColor(@NonNull ComponentName who, int color) {
10277        if (!mHasFeature) {
10278            return;
10279        }
10280        Preconditions.checkNotNull(who, "ComponentName is null");
10281        final int userHandle = mInjector.userHandleGetCallingUserId();
10282        enforceManagedProfile(userHandle, "set organization color");
10283        synchronized (this) {
10284            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10285                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10286            admin.organizationColor = color;
10287            saveSettingsLocked(userHandle);
10288        }
10289    }
10290
10291    @Override
10292    public void setOrganizationColorForUser(int color, int userId) {
10293        if (!mHasFeature) {
10294            return;
10295        }
10296        enforceFullCrossUsersPermission(userId);
10297        enforceManageUsers();
10298        enforceManagedProfile(userId, "set organization color");
10299        synchronized (this) {
10300            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
10301            admin.organizationColor = color;
10302            saveSettingsLocked(userId);
10303        }
10304    }
10305
10306    @Override
10307    public int getOrganizationColor(@NonNull ComponentName who) {
10308        if (!mHasFeature) {
10309            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
10310        }
10311        Preconditions.checkNotNull(who, "ComponentName is null");
10312        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
10313        synchronized (this) {
10314            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10315                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10316            return admin.organizationColor;
10317        }
10318    }
10319
10320    @Override
10321    public int getOrganizationColorForUser(int userHandle) {
10322        if (!mHasFeature) {
10323            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
10324        }
10325        enforceFullCrossUsersPermission(userHandle);
10326        enforceManagedProfile(userHandle, "get organization color");
10327        synchronized (this) {
10328            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
10329            return (profileOwner != null)
10330                    ? profileOwner.organizationColor
10331                    : ActiveAdmin.DEF_ORGANIZATION_COLOR;
10332        }
10333    }
10334
10335    @Override
10336    public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
10337        if (!mHasFeature) {
10338            return;
10339        }
10340        Preconditions.checkNotNull(who, "ComponentName is null");
10341        final int userHandle = mInjector.userHandleGetCallingUserId();
10342
10343        synchronized (this) {
10344            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10345                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10346            if (!TextUtils.equals(admin.organizationName, text)) {
10347                admin.organizationName = (text == null || text.length() == 0)
10348                        ? null : text.toString();
10349                saveSettingsLocked(userHandle);
10350            }
10351        }
10352    }
10353
10354    @Override
10355    public CharSequence getOrganizationName(@NonNull ComponentName who) {
10356        if (!mHasFeature) {
10357            return null;
10358        }
10359        Preconditions.checkNotNull(who, "ComponentName is null");
10360        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
10361        synchronized(this) {
10362            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
10363                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10364            return admin.organizationName;
10365        }
10366    }
10367
10368    @Override
10369    public CharSequence getDeviceOwnerOrganizationName() {
10370        if (!mHasFeature) {
10371            return null;
10372        }
10373        enforceDeviceOwnerOrManageUsers();
10374        synchronized(this) {
10375            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
10376            return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
10377        }
10378    }
10379
10380    @Override
10381    public CharSequence getOrganizationNameForUser(int userHandle) {
10382        if (!mHasFeature) {
10383            return null;
10384        }
10385        enforceFullCrossUsersPermission(userHandle);
10386        enforceManagedProfile(userHandle, "get organization name");
10387        synchronized (this) {
10388            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
10389            return (profileOwner != null)
10390                    ? profileOwner.organizationName
10391                    : null;
10392        }
10393    }
10394
10395    @Override
10396    public void setAffiliationIds(ComponentName admin, List<String> ids) {
10397        if (!mHasFeature) {
10398            return;
10399        }
10400        if (ids == null) {
10401            throw new IllegalArgumentException("ids must not be null");
10402        }
10403        for (String id : ids) {
10404            if (TextUtils.isEmpty(id)) {
10405                throw new IllegalArgumentException("ids must not contain empty string");
10406            }
10407        }
10408
10409        final Set<String> affiliationIds = new ArraySet<>(ids);
10410        final int callingUserId = mInjector.userHandleGetCallingUserId();
10411        synchronized (this) {
10412            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10413            getUserData(callingUserId).mAffiliationIds = affiliationIds;
10414            saveSettingsLocked(callingUserId);
10415            if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
10416                // Affiliation ids specified by the device owner are additionally stored in
10417                // UserHandle.USER_SYSTEM's DevicePolicyData.
10418                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
10419                saveSettingsLocked(UserHandle.USER_SYSTEM);
10420            }
10421
10422            // Affiliation status for any user, not just the calling user, might have changed.
10423            // The device owner user will still be affiliated after changing its affiliation ids,
10424            // but as a result of that other users might become affiliated or un-affiliated.
10425            maybePauseDeviceWideLoggingLocked();
10426            maybeResumeDeviceWideLoggingLocked();
10427            maybeClearLockTaskPolicyLocked();
10428        }
10429    }
10430
10431    @Override
10432    public List<String> getAffiliationIds(ComponentName admin) {
10433        if (!mHasFeature) {
10434            return Collections.emptyList();
10435        }
10436
10437        Preconditions.checkNotNull(admin);
10438        synchronized (this) {
10439            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10440            return new ArrayList<String>(
10441                    getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
10442        }
10443    }
10444
10445    @Override
10446    public boolean isAffiliatedUser() {
10447        if (!mHasFeature) {
10448            return false;
10449        }
10450
10451        synchronized (this) {
10452            return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
10453        }
10454    }
10455
10456    private boolean isUserAffiliatedWithDeviceLocked(int userId) {
10457        if (!mOwners.hasDeviceOwner()) {
10458            return false;
10459        }
10460        if (userId == mOwners.getDeviceOwnerUserId()) {
10461            // The user that the DO is installed on is always affiliated with the device.
10462            return true;
10463        }
10464        if (userId == UserHandle.USER_SYSTEM) {
10465            // The system user is always affiliated in a DO device, even if the DO is set on a
10466            // different user. This could be the case if the DO is set in the primary user
10467            // of a split user device.
10468            return true;
10469        }
10470        final ComponentName profileOwner = getProfileOwner(userId);
10471        if (profileOwner == null) {
10472            return false;
10473        }
10474        final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
10475        final Set<String> deviceAffiliationIds =
10476                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
10477        for (String id : userAffiliationIds) {
10478            if (deviceAffiliationIds.contains(id)) {
10479                return true;
10480            }
10481        }
10482        return false;
10483    }
10484
10485    private boolean areAllUsersAffiliatedWithDeviceLocked() {
10486        final long ident = mInjector.binderClearCallingIdentity();
10487        try {
10488            final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
10489            for (int i = 0; i < userInfos.size(); i++) {
10490                int userId = userInfos.get(i).id;
10491                if (!isUserAffiliatedWithDeviceLocked(userId)) {
10492                    Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
10493                    return false;
10494                }
10495            }
10496        } finally {
10497            mInjector.binderRestoreCallingIdentity(ident);
10498        }
10499
10500        return true;
10501    }
10502
10503    @Override
10504    public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
10505        if (!mHasFeature) {
10506            return;
10507        }
10508        Preconditions.checkNotNull(admin);
10509
10510        synchronized (this) {
10511            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10512            if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
10513                return;
10514            }
10515            mInjector.securityLogSetLoggingEnabledProperty(enabled);
10516            if (enabled) {
10517                mSecurityLogMonitor.start();
10518                maybePauseDeviceWideLoggingLocked();
10519            } else {
10520                mSecurityLogMonitor.stop();
10521            }
10522        }
10523    }
10524
10525    @Override
10526    public boolean isSecurityLoggingEnabled(ComponentName admin) {
10527        if (!mHasFeature) {
10528            return false;
10529        }
10530
10531        synchronized (this) {
10532            if (!isCallerWithSystemUid()) {
10533                Preconditions.checkNotNull(admin);
10534                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10535            }
10536            return mInjector.securityLogGetLoggingEnabledProperty();
10537        }
10538    }
10539
10540    private synchronized void recordSecurityLogRetrievalTime() {
10541        final long currentTime = System.currentTimeMillis();
10542        DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
10543        if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
10544            policyData.mLastSecurityLogRetrievalTime = currentTime;
10545            saveSettingsLocked(UserHandle.USER_SYSTEM);
10546        }
10547    }
10548
10549    @Override
10550    public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
10551        if (!mHasFeature) {
10552            return null;
10553        }
10554
10555        Preconditions.checkNotNull(admin);
10556        ensureDeviceOwnerAndAllUsersAffiliated(admin);
10557
10558        if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
10559                || !mInjector.securityLogGetLoggingEnabledProperty()) {
10560            return null;
10561        }
10562
10563        recordSecurityLogRetrievalTime();
10564
10565        ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
10566        try {
10567            SecurityLog.readPreviousEvents(output);
10568            return new ParceledListSlice<SecurityEvent>(output);
10569        } catch (IOException e) {
10570            Slog.w(LOG_TAG, "Fail to read previous events" , e);
10571            return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
10572        }
10573    }
10574
10575    @Override
10576    public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
10577        if (!mHasFeature) {
10578            return null;
10579        }
10580
10581        Preconditions.checkNotNull(admin);
10582        ensureDeviceOwnerAndAllUsersAffiliated(admin);
10583
10584        if (!mInjector.securityLogGetLoggingEnabledProperty()) {
10585            return null;
10586        }
10587
10588        recordSecurityLogRetrievalTime();
10589
10590        List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
10591        return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
10592    }
10593
10594    private void enforceCanManageDeviceAdmin() {
10595        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
10596                null);
10597    }
10598
10599    private void enforceCanManageProfileAndDeviceOwners() {
10600        mContext.enforceCallingOrSelfPermission(
10601                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
10602    }
10603
10604    private void enforceCallerSystemUserHandle() {
10605        final int callingUid = mInjector.binderGetCallingUid();
10606        final int userId = UserHandle.getUserId(callingUid);
10607        if (userId != UserHandle.USER_SYSTEM) {
10608            throw new SecurityException("Caller has to be in user 0");
10609        }
10610    }
10611
10612    @Override
10613    public boolean isUninstallInQueue(final String packageName) {
10614        enforceCanManageDeviceAdmin();
10615        final int userId = mInjector.userHandleGetCallingUserId();
10616        Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10617        synchronized (this) {
10618            return mPackagesToRemove.contains(packageUserPair);
10619        }
10620    }
10621
10622    @Override
10623    public void uninstallPackageWithActiveAdmins(final String packageName) {
10624        enforceCanManageDeviceAdmin();
10625        Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
10626
10627        final int userId = mInjector.userHandleGetCallingUserId();
10628
10629        enforceUserUnlocked(userId);
10630
10631        final ComponentName profileOwner = getProfileOwner(userId);
10632        if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
10633            throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
10634        }
10635
10636        final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
10637        if (getDeviceOwnerUserId() == userId && deviceOwner != null
10638                && packageName.equals(deviceOwner.getPackageName())) {
10639            throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
10640        }
10641
10642        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10643        synchronized (this) {
10644            mPackagesToRemove.add(packageUserPair);
10645        }
10646
10647        // All active admins on the user.
10648        final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
10649
10650        // Active admins in the target package.
10651        final List<ComponentName> packageActiveAdmins = new ArrayList<>();
10652        if (allActiveAdmins != null) {
10653            for (ComponentName activeAdmin : allActiveAdmins) {
10654                if (packageName.equals(activeAdmin.getPackageName())) {
10655                    packageActiveAdmins.add(activeAdmin);
10656                    removeActiveAdmin(activeAdmin, userId);
10657                }
10658            }
10659        }
10660        if (packageActiveAdmins.size() == 0) {
10661            startUninstallIntent(packageName, userId);
10662        } else {
10663            mHandler.postDelayed(new Runnable() {
10664                @Override
10665                public void run() {
10666                    for (ComponentName activeAdmin : packageActiveAdmins) {
10667                        removeAdminArtifacts(activeAdmin, userId);
10668                    }
10669                    startUninstallIntent(packageName, userId);
10670                }
10671            }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
10672        }
10673    }
10674
10675    @Override
10676    public boolean isDeviceProvisioned() {
10677        synchronized (this) {
10678            return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
10679        }
10680    }
10681
10682    private boolean isCurrentUserDemo() {
10683        if (UserManager.isDeviceInDemoMode(mContext)) {
10684            final int userId = mInjector.userHandleGetCallingUserId();
10685            final long callingIdentity = mInjector.binderClearCallingIdentity();
10686            try {
10687                return mUserManager.getUserInfo(userId).isDemo();
10688            } finally {
10689                mInjector.binderRestoreCallingIdentity(callingIdentity);
10690            }
10691        }
10692        return false;
10693    }
10694
10695    private void removePackageIfRequired(final String packageName, final int userId) {
10696        if (!packageHasActiveAdmins(packageName, userId)) {
10697            // Will not do anything if uninstall was not requested or was already started.
10698            startUninstallIntent(packageName, userId);
10699        }
10700    }
10701
10702    private void startUninstallIntent(final String packageName, final int userId) {
10703        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
10704        synchronized (this) {
10705            if (!mPackagesToRemove.contains(packageUserPair)) {
10706                // Do nothing if uninstall was not requested or was already started.
10707                return;
10708            }
10709            mPackagesToRemove.remove(packageUserPair);
10710        }
10711        try {
10712            if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
10713                // Package does not exist. Nothing to do.
10714                return;
10715            }
10716        } catch (RemoteException re) {
10717            Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
10718        }
10719
10720        try { // force stop the package before uninstalling
10721            mInjector.getIActivityManager().forceStopPackage(packageName, userId);
10722        } catch (RemoteException re) {
10723            Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
10724        }
10725        final Uri packageURI = Uri.parse("package:" + packageName);
10726        final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
10727        uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10728        mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
10729    }
10730
10731    /**
10732     * Removes the admin from the policy. Ideally called after the admin's
10733     * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
10734     *
10735     * @param adminReceiver The admin to remove
10736     * @param userHandle The user for which this admin has to be removed.
10737     */
10738    private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
10739        synchronized (this) {
10740            final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
10741            if (admin == null) {
10742                return;
10743            }
10744            final DevicePolicyData policy = getUserData(userHandle);
10745            final boolean doProxyCleanup = admin.info.usesPolicy(
10746                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
10747            policy.mAdminList.remove(admin);
10748            policy.mAdminMap.remove(adminReceiver);
10749            validatePasswordOwnerLocked(policy);
10750            if (doProxyCleanup) {
10751                resetGlobalProxyLocked(policy);
10752            }
10753            saveSettingsLocked(userHandle);
10754            updateMaximumTimeToLockLocked(userHandle);
10755            policy.mRemovingAdmins.remove(adminReceiver);
10756
10757            Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
10758        }
10759        // The removed admin might have disabled camera, so update user
10760        // restrictions.
10761        pushUserRestrictions(userHandle);
10762    }
10763
10764    @Override
10765    public void setDeviceProvisioningConfigApplied() {
10766        enforceManageUsers();
10767        synchronized (this) {
10768            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10769            policy.mDeviceProvisioningConfigApplied = true;
10770            saveSettingsLocked(UserHandle.USER_SYSTEM);
10771        }
10772    }
10773
10774    @Override
10775    public boolean isDeviceProvisioningConfigApplied() {
10776        enforceManageUsers();
10777        synchronized (this) {
10778            final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
10779            return policy.mDeviceProvisioningConfigApplied;
10780        }
10781    }
10782
10783    /**
10784     * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
10785     *
10786     * It's added for testing only. Please use this API carefully if it's used by other system app
10787     * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
10788     * apps.
10789     */
10790    @Override
10791    public void forceUpdateUserSetupComplete() {
10792        enforceCanManageProfileAndDeviceOwners();
10793        enforceCallerSystemUserHandle();
10794        // no effect if it's called from user build
10795        if (!mInjector.isBuildDebuggable()) {
10796            return;
10797        }
10798        final int userId = UserHandle.USER_SYSTEM;
10799        boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
10800                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
10801        DevicePolicyData policy = getUserData(userId);
10802        policy.mUserSetupComplete = isUserCompleted;
10803        synchronized (this) {
10804            saveSettingsLocked(userId);
10805        }
10806    }
10807
10808    // TODO(b/22388012): When backup is available for secondary users and profiles, consider
10809    // whether there are any privacy/security implications of enabling the backup service here
10810    // if there are other users or profiles unmanaged or managed by a different entity (i.e. not
10811    // affiliated).
10812    @Override
10813    public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
10814        if (!mHasFeature) {
10815            return;
10816        }
10817        Preconditions.checkNotNull(admin);
10818        synchronized (this) {
10819            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10820        }
10821
10822        final long ident = mInjector.binderClearCallingIdentity();
10823        try {
10824            IBackupManager ibm = mInjector.getIBackupManager();
10825            if (ibm != null) {
10826                ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
10827            }
10828        } catch (RemoteException e) {
10829            throw new IllegalStateException(
10830                "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
10831        } finally {
10832            mInjector.binderRestoreCallingIdentity(ident);
10833        }
10834    }
10835
10836    @Override
10837    public boolean isBackupServiceEnabled(ComponentName admin) {
10838        Preconditions.checkNotNull(admin);
10839        if (!mHasFeature) {
10840            return true;
10841        }
10842        synchronized (this) {
10843            try {
10844                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10845                IBackupManager ibm = mInjector.getIBackupManager();
10846                return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
10847            } catch (RemoteException e) {
10848                throw new IllegalStateException("Failed requesting backup service state.", e);
10849            }
10850        }
10851    }
10852
10853    @Override
10854    public boolean bindDeviceAdminServiceAsUser(
10855            @NonNull ComponentName admin, @NonNull IApplicationThread caller,
10856            @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
10857            @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
10858        if (!mHasFeature) {
10859            return false;
10860        }
10861        Preconditions.checkNotNull(admin);
10862        Preconditions.checkNotNull(caller);
10863        Preconditions.checkNotNull(serviceIntent);
10864        Preconditions.checkArgument(
10865                serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
10866                "Service intent must be explicit (with a package name or component): "
10867                        + serviceIntent);
10868        Preconditions.checkNotNull(connection);
10869        Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
10870                "target user id must be different from the calling user id");
10871
10872        if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
10873            throw new SecurityException("Not allowed to bind to target user id");
10874        }
10875
10876        final String targetPackage;
10877        synchronized (this) {
10878            targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
10879        }
10880
10881        final long callingIdentity = mInjector.binderClearCallingIdentity();
10882        try {
10883            // Validate and sanitize the incoming service intent.
10884            final Intent sanitizedIntent =
10885                    createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
10886            if (sanitizedIntent == null) {
10887                // Fail, cannot lookup the target service.
10888                return false;
10889            }
10890            // Ask ActivityManager to bind it. Notice that we are binding the service with the
10891            // caller app instead of DevicePolicyManagerService.
10892            return mInjector.getIActivityManager().bindService(
10893                    caller, activtiyToken, serviceIntent,
10894                    serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
10895                    connection, flags, mContext.getOpPackageName(),
10896                    targetUserId) != 0;
10897        } catch (RemoteException ex) {
10898            // Same process, should not happen.
10899        } finally {
10900            mInjector.binderRestoreCallingIdentity(callingIdentity);
10901        }
10902
10903        // Failed to bind.
10904        return false;
10905    }
10906
10907    @Override
10908    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
10909        if (!mHasFeature) {
10910            return Collections.emptyList();
10911        }
10912        Preconditions.checkNotNull(admin);
10913
10914        synchronized (this) {
10915            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10916
10917            final int callingUserId = mInjector.userHandleGetCallingUserId();
10918            final long callingIdentity = mInjector.binderClearCallingIdentity();
10919            try {
10920                ArrayList<UserHandle> targetUsers = new ArrayList<>();
10921                if (!isDeviceOwner(admin, callingUserId)) {
10922                    // Profile owners can only bind to the device owner.
10923                    if (canUserBindToDeviceOwnerLocked(callingUserId)) {
10924                        targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
10925                    }
10926                } else {
10927                    // Caller is the device owner: Look for profile owners that it can bind to.
10928                    final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
10929                    for (int i = 0; i < userInfos.size(); i++) {
10930                        final int userId = userInfos.get(i).id;
10931                        if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
10932                            targetUsers.add(UserHandle.of(userId));
10933                        }
10934                    }
10935                }
10936
10937                return targetUsers;
10938            } finally {
10939                mInjector.binderRestoreCallingIdentity(callingIdentity);
10940            }
10941        }
10942    }
10943
10944    private boolean canUserBindToDeviceOwnerLocked(int userId) {
10945        // There has to be a device owner, under another user id.
10946        if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
10947            return false;
10948        }
10949
10950        // The user must have a profile owner that belongs to the same package as the device owner.
10951        if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
10952                mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
10953            return false;
10954        }
10955
10956        // The user must be affiliated.
10957        return isUserAffiliatedWithDeviceLocked(userId);
10958    }
10959
10960    /**
10961     * Return true if a given user has any accounts that'll prevent installing a device or profile
10962     * owner {@code owner}.
10963     * - If the user has no accounts, then return false.
10964     * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
10965     * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
10966     *   ..._DISALLOWED, return true.
10967     * - Otherwise return false.
10968     *
10969     * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
10970     * when the caller is not ADB.
10971     *
10972     * DO NOT CALL IT WITH THE DPMS LOCK HELD.
10973     */
10974    private boolean hasIncompatibleAccountsOrNonAdbNoLock(
10975            int userId, @Nullable ComponentName owner) {
10976        if (!isAdb()) {
10977            return true;
10978        }
10979        wtfIfInLock();
10980
10981        final long token = mInjector.binderClearCallingIdentity();
10982        try {
10983            final AccountManager am = AccountManager.get(mContext);
10984            final Account accounts[] = am.getAccountsAsUser(userId);
10985            if (accounts.length == 0) {
10986                return false;
10987            }
10988            synchronized (this) {
10989                if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
10990                    Log.w(LOG_TAG,
10991                            "Non test-only owner can't be installed with existing accounts.");
10992                    return true;
10993                }
10994            }
10995
10996            final String[] feature_allow =
10997                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
10998            final String[] feature_disallow =
10999                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
11000
11001            boolean compatible = true;
11002            for (Account account : accounts) {
11003                if (hasAccountFeatures(am, account, feature_disallow)) {
11004                    Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
11005                    compatible = false;
11006                    break;
11007                }
11008                if (!hasAccountFeatures(am, account, feature_allow)) {
11009                    Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
11010                    compatible = false;
11011                    break;
11012                }
11013            }
11014            if (compatible) {
11015                Log.w(LOG_TAG, "All accounts are compatible");
11016            } else {
11017                Log.e(LOG_TAG, "Found incompatible accounts");
11018            }
11019            return !compatible;
11020        } finally {
11021            mInjector.binderRestoreCallingIdentity(token);
11022        }
11023    }
11024
11025    private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
11026        try {
11027            return am.hasFeatures(account, features, null, null).getResult();
11028        } catch (Exception e) {
11029            Log.w(LOG_TAG, "Failed to get account feature", e);
11030            return false;
11031        }
11032    }
11033
11034    private boolean isAdb() {
11035        final int callingUid = mInjector.binderGetCallingUid();
11036        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
11037    }
11038
11039    @Override
11040    public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
11041        if (!mHasFeature) {
11042            return;
11043        }
11044        Preconditions.checkNotNull(admin);
11045        getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11046
11047        if (enabled == isNetworkLoggingEnabledInternalLocked()) {
11048            // already in the requested state
11049            return;
11050        }
11051        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11052        deviceOwner.isNetworkLoggingEnabled = enabled;
11053        if (!enabled) {
11054            deviceOwner.numNetworkLoggingNotifications = 0;
11055            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
11056        }
11057        saveSettingsLocked(mInjector.userHandleGetCallingUserId());
11058
11059        setNetworkLoggingActiveInternal(enabled);
11060    }
11061
11062    private synchronized void setNetworkLoggingActiveInternal(boolean active) {
11063        final long callingIdentity = mInjector.binderClearCallingIdentity();
11064        try {
11065            if (active) {
11066                mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
11067                if (!mNetworkLogger.startNetworkLogging()) {
11068                    mNetworkLogger = null;
11069                    Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
11070                            + " service not being available yet.");
11071                }
11072                maybePauseDeviceWideLoggingLocked();
11073                sendNetworkLoggingNotificationLocked();
11074            } else {
11075                if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
11076                    Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
11077                            + " service not being available yet.");
11078                }
11079                mNetworkLogger = null;
11080                mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING);
11081            }
11082        } finally {
11083            mInjector.binderRestoreCallingIdentity(callingIdentity);
11084        }
11085    }
11086
11087    /** Pauses security and network logging if there are unaffiliated users on the device */
11088    private void maybePauseDeviceWideLoggingLocked() {
11089        if (!areAllUsersAffiliatedWithDeviceLocked()) {
11090            Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
11091                    + "paused if enabled.");
11092            mSecurityLogMonitor.pause();
11093            if (mNetworkLogger != null) {
11094                mNetworkLogger.pause();
11095            }
11096        }
11097    }
11098
11099    /** Resumes security and network logging (if they are enabled) if all users are affiliated */
11100    private void maybeResumeDeviceWideLoggingLocked() {
11101        if (areAllUsersAffiliatedWithDeviceLocked()) {
11102            final long ident = mInjector.binderClearCallingIdentity();
11103            try {
11104                mSecurityLogMonitor.resume();
11105                if (mNetworkLogger != null) {
11106                    mNetworkLogger.resume();
11107                }
11108            } finally {
11109                mInjector.binderRestoreCallingIdentity(ident);
11110            }
11111        }
11112    }
11113
11114    /** Deletes any security and network logs that might have been collected so far */
11115    private void discardDeviceWideLogsLocked() {
11116        mSecurityLogMonitor.discardLogs();
11117        if (mNetworkLogger != null) {
11118            mNetworkLogger.discardLogs();
11119        }
11120        // TODO: We should discard pre-boot security logs here too, as otherwise those
11121        // logs (which might contain data from the user just removed) will be
11122        // available after next boot.
11123    }
11124
11125    @Override
11126    public boolean isNetworkLoggingEnabled(ComponentName admin) {
11127        if (!mHasFeature) {
11128            return false;
11129        }
11130        synchronized (this) {
11131            enforceDeviceOwnerOrManageUsers();
11132            return isNetworkLoggingEnabledInternalLocked();
11133        }
11134    }
11135
11136    private boolean isNetworkLoggingEnabledInternalLocked() {
11137        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11138        return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
11139    }
11140
11141    /*
11142     * A maximum of 1200 events are returned, and the total marshalled size is in the order of
11143     * 100kB, so returning a List instead of ParceledListSlice is acceptable.
11144     * Ideally this would be done with ParceledList, however it only supports homogeneous types.
11145     *
11146     * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
11147     */
11148    @Override
11149    public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) {
11150        if (!mHasFeature) {
11151            return null;
11152        }
11153        Preconditions.checkNotNull(admin);
11154        ensureDeviceOwnerAndAllUsersAffiliated(admin);
11155
11156        synchronized (this) {
11157            if (mNetworkLogger == null
11158                    || !isNetworkLoggingEnabledInternalLocked()) {
11159                return null;
11160            }
11161
11162            final long currentTime = System.currentTimeMillis();
11163            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
11164            if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
11165                policyData.mLastNetworkLogsRetrievalTime = currentTime;
11166                saveSettingsLocked(UserHandle.USER_SYSTEM);
11167            }
11168            return mNetworkLogger.retrieveLogs(batchToken);
11169        }
11170    }
11171
11172    private void sendNetworkLoggingNotificationLocked() {
11173        final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11174        if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
11175            return;
11176        }
11177        if (deviceOwner.numNetworkLoggingNotifications >=
11178                ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
11179            return;
11180        }
11181        final long now = System.currentTimeMillis();
11182        if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
11183            return;
11184        }
11185        deviceOwner.numNetworkLoggingNotifications++;
11186        if (deviceOwner.numNetworkLoggingNotifications
11187                >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
11188            deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
11189        } else {
11190            deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
11191        }
11192        final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
11193        intent.setPackage("com.android.systemui");
11194        final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
11195                UserHandle.CURRENT);
11196        Notification notification =
11197                new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
11198                .setSmallIcon(R.drawable.ic_info_outline)
11199                .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
11200                .setContentText(mContext.getString(R.string.network_logging_notification_text))
11201                .setTicker(mContext.getString(R.string.network_logging_notification_title))
11202                .setShowWhen(true)
11203                .setContentIntent(pendingIntent)
11204                .setStyle(new Notification.BigTextStyle()
11205                        .bigText(mContext.getString(R.string.network_logging_notification_text)))
11206                .build();
11207        mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification);
11208        saveSettingsLocked(mOwners.getDeviceOwnerUserId());
11209    }
11210
11211    /**
11212     * Return the package name of owner in a given user.
11213     */
11214    private String getOwnerPackageNameForUserLocked(int userId) {
11215        return mOwners.getDeviceOwnerUserId() == userId
11216                ? mOwners.getDeviceOwnerPackageName()
11217                : mOwners.getProfileOwnerPackage(userId);
11218    }
11219
11220    /**
11221     * @param rawIntent Original service intent specified by caller. It must be explicit.
11222     * @param expectedPackageName The expected package name of the resolved service.
11223     * @return Intent that have component explicitly set. {@code null} if no service is resolved
11224     *     with the given intent.
11225     * @throws SecurityException if the intent is resolved to an invalid service.
11226     */
11227    private Intent createCrossUserServiceIntent(
11228            @NonNull Intent rawIntent, @NonNull String expectedPackageName,
11229            @UserIdInt int targetUserId) throws RemoteException, SecurityException {
11230        ResolveInfo info = mIPackageManager.resolveService(
11231                rawIntent,
11232                rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
11233                0,  // flags
11234                targetUserId);
11235        if (info == null || info.serviceInfo == null) {
11236            Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
11237                    + " or user " + targetUserId + " is not running");
11238            return null;
11239        }
11240        if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
11241            throw new SecurityException("Only allow to bind service in " + expectedPackageName);
11242        }
11243        // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
11244        if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
11245            throw new SecurityException(
11246                    "Service must be protected by BIND_DEVICE_ADMIN permission");
11247        }
11248        // It is the system server to bind the service, it would be extremely dangerous if it
11249        // can be exploited to bind any service. Set the component explicitly to make sure we
11250        // do not bind anything accidentally.
11251        rawIntent.setComponent(info.serviceInfo.getComponentName());
11252        return rawIntent;
11253    }
11254
11255    @Override
11256    public long getLastSecurityLogRetrievalTime() {
11257        enforceDeviceOwnerOrManageUsers();
11258        return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
11259     }
11260
11261    @Override
11262    public long getLastBugReportRequestTime() {
11263        enforceDeviceOwnerOrManageUsers();
11264        return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
11265     }
11266
11267    @Override
11268    public long getLastNetworkLogRetrievalTime() {
11269        enforceDeviceOwnerOrManageUsers();
11270        return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
11271    }
11272
11273    @Override
11274    public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
11275        if (!mHasFeature) {
11276            return false;
11277        }
11278        if (token == null || token.length < 32) {
11279            throw new IllegalArgumentException("token must be at least 32-byte long");
11280        }
11281        synchronized (this) {
11282            final int userHandle = mInjector.userHandleGetCallingUserId();
11283            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11284
11285            DevicePolicyData policy = getUserData(userHandle);
11286            long ident = mInjector.binderClearCallingIdentity();
11287            try {
11288                if (policy.mPasswordTokenHandle != 0) {
11289                    mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
11290                }
11291
11292                policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle);
11293                saveSettingsLocked(userHandle);
11294                return policy.mPasswordTokenHandle != 0;
11295            } finally {
11296                mInjector.binderRestoreCallingIdentity(ident);
11297            }
11298        }
11299    }
11300
11301    @Override
11302    public boolean clearResetPasswordToken(ComponentName admin) {
11303        if (!mHasFeature) {
11304            return false;
11305        }
11306        synchronized (this) {
11307            final int userHandle = mInjector.userHandleGetCallingUserId();
11308            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11309
11310            DevicePolicyData policy = getUserData(userHandle);
11311            if (policy.mPasswordTokenHandle != 0) {
11312                long ident = mInjector.binderClearCallingIdentity();
11313                try {
11314                    boolean result = mLockPatternUtils.removeEscrowToken(
11315                            policy.mPasswordTokenHandle, userHandle);
11316                    policy.mPasswordTokenHandle = 0;
11317                    saveSettingsLocked(userHandle);
11318                    return result;
11319                } finally {
11320                    mInjector.binderRestoreCallingIdentity(ident);
11321                }
11322            }
11323        }
11324        return false;
11325    }
11326
11327    @Override
11328    public boolean isResetPasswordTokenActive(ComponentName admin) {
11329        synchronized (this) {
11330            final int userHandle = mInjector.userHandleGetCallingUserId();
11331            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11332
11333            DevicePolicyData policy = getUserData(userHandle);
11334            if (policy.mPasswordTokenHandle != 0) {
11335                long ident = mInjector.binderClearCallingIdentity();
11336                try {
11337                    return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle,
11338                            userHandle);
11339                } finally {
11340                    mInjector.binderRestoreCallingIdentity(ident);
11341                }
11342            }
11343        }
11344        return false;
11345    }
11346
11347    @Override
11348    public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
11349            int flags) {
11350        Preconditions.checkNotNull(token);
11351        synchronized (this) {
11352            final int userHandle = mInjector.userHandleGetCallingUserId();
11353            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11354
11355            DevicePolicyData policy = getUserData(userHandle);
11356            if (policy.mPasswordTokenHandle != 0) {
11357                final String password = passwordOrNull != null ? passwordOrNull : "";
11358                return resetPasswordInternal(password, policy.mPasswordTokenHandle, token,
11359                        flags, mInjector.binderGetCallingUid(), userHandle);
11360            } else {
11361                Slog.w(LOG_TAG, "No saved token handle");
11362            }
11363        }
11364        return false;
11365    }
11366
11367    @Override
11368    public boolean isCurrentInputMethodSetByOwner() {
11369        enforceProfileOwnerOrSystemUser();
11370        return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet;
11371    }
11372
11373    @Override
11374    public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
11375        final int userId = user.getIdentifier();
11376        enforceProfileOwnerOrFullCrossUsersPermission(userId);
11377        synchronized (this) {
11378            return new StringParceledListSlice(
11379                    new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
11380        }
11381    }
11382
11383    @Override
11384    public boolean clearApplicationUserData(ComponentName admin, String packageName,
11385            IPackageDataObserver callback) {
11386        Preconditions.checkNotNull(admin, "ComponentName is null");
11387        synchronized (this) {
11388            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11389        }
11390        final int userId = UserHandle.getCallingUserId();
11391
11392        long ident = mInjector.binderClearCallingIdentity();
11393        try {
11394            return ActivityManager.getService().clearApplicationUserData(packageName, callback,
11395                    userId);
11396        } catch(RemoteException re) {
11397            // Same process, should not happen.
11398        } catch (SecurityException se) {
11399            // This can happen e.g. for device admin packages, do not throw out the exception,
11400            // because callers have no means to know beforehand for which packages this might
11401            // happen.
11402            Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName,
11403                    se);
11404        } finally {
11405            mInjector.binderRestoreCallingIdentity(ident);
11406        }
11407
11408        if (callback != null) {
11409            try {
11410                // If there was a throw above, we send back that removal failed
11411                callback.onRemoveCompleted(packageName, false);
11412            } catch (RemoteException re) {
11413                // Caller is no longer available, ignore
11414            }
11415        }
11416        return false;
11417    }
11418
11419    @Override
11420    public synchronized void setLogoutButtonEnabled(ComponentName admin, boolean enabled) {
11421        if (!mHasFeature) {
11422            return;
11423        }
11424        Preconditions.checkNotNull(admin);
11425        getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11426
11427        if (enabled == isLogoutButtonEnabledInternalLocked()) {
11428            // already in the requested state
11429            return;
11430        }
11431        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11432        deviceOwner.isLogoutButtonEnabled = enabled;
11433        saveSettingsLocked(mInjector.userHandleGetCallingUserId());
11434    }
11435
11436    @Override
11437    public boolean isLogoutButtonEnabled() {
11438        if (!mHasFeature) {
11439            return false;
11440        }
11441        synchronized (this) {
11442            return isLogoutButtonEnabledInternalLocked();
11443        }
11444    }
11445
11446    private boolean isLogoutButtonEnabledInternalLocked() {
11447        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
11448        return (deviceOwner != null) && deviceOwner.isLogoutButtonEnabled;
11449    }
11450
11451}
11452