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