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