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