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