DevicePolicyManagerService.java revision 3db81ae38d942831057960347e4bc0d297b85127
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.PASSWORD_QUALITY_COMPLEX;
21import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
24
25import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB;
26import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
27import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
28import static org.xmlpull.v1.XmlPullParser.END_TAG;
29import static org.xmlpull.v1.XmlPullParser.TEXT;
30
31import android.Manifest.permission;
32import android.accessibilityservice.AccessibilityServiceInfo;
33import android.accounts.Account;
34import android.accounts.AccountManager;
35import android.annotation.IntDef;
36import android.annotation.NonNull;
37import android.annotation.Nullable;
38import android.annotation.UserIdInt;
39import android.app.Activity;
40import android.app.ActivityManager;
41import android.app.AlarmManager;
42import android.app.AppGlobals;
43import android.app.IActivityManager;
44import android.app.IApplicationThread;
45import android.app.IServiceConnection;
46import android.app.Notification;
47import android.app.NotificationManager;
48import android.app.PendingIntent;
49import android.app.StatusBarManager;
50import android.app.admin.DeviceAdminInfo;
51import android.app.admin.DeviceAdminReceiver;
52import android.app.admin.DevicePolicyManager;
53import android.app.admin.DevicePolicyManagerInternal;
54import android.app.admin.IDevicePolicyManager;
55import android.app.admin.NetworkEvent;
56import android.app.admin.PasswordMetrics;
57import android.app.admin.SecurityLog;
58import android.app.admin.SecurityLog.SecurityEvent;
59import android.app.admin.SystemUpdatePolicy;
60import android.app.backup.IBackupManager;
61import android.content.BroadcastReceiver;
62import android.content.ComponentName;
63import android.content.Context;
64import android.content.Intent;
65import android.content.IntentFilter;
66import android.content.pm.ActivityInfo;
67import android.content.pm.ApplicationInfo;
68import android.content.pm.IPackageManager;
69import android.content.pm.PackageInfo;
70import android.content.pm.PackageManager;
71import android.content.pm.PackageManager.NameNotFoundException;
72import android.content.pm.PackageManagerInternal;
73import android.content.pm.ParceledListSlice;
74import android.content.pm.ResolveInfo;
75import android.content.pm.ServiceInfo;
76import android.content.pm.UserInfo;
77import android.database.ContentObserver;
78import android.graphics.Bitmap;
79import android.graphics.Color;
80import android.media.AudioManager;
81import android.media.IAudioService;
82import android.net.ConnectivityManager;
83import android.net.IIpConnectivityMetrics;
84import android.net.ProxyInfo;
85import android.net.Uri;
86import android.net.metrics.IpConnectivityLog;
87import android.net.wifi.WifiInfo;
88import android.net.wifi.WifiManager;
89import android.os.AsyncTask;
90import android.os.Binder;
91import android.os.Build;
92import android.os.Bundle;
93import android.os.Environment;
94import android.os.FileUtils;
95import android.os.Handler;
96import android.os.IBinder;
97import android.os.Looper;
98import android.os.ParcelFileDescriptor;
99import android.os.PersistableBundle;
100import android.os.PowerManager;
101import android.os.PowerManagerInternal;
102import android.os.Process;
103import android.os.RecoverySystem;
104import android.os.RemoteCallback;
105import android.os.RemoteException;
106import android.os.ServiceManager;
107import android.os.SystemClock;
108import android.os.SystemProperties;
109import android.os.UserHandle;
110import android.os.UserManager;
111import android.os.UserManagerInternal;
112import android.os.storage.StorageManager;
113import android.provider.ContactsContract.QuickContact;
114import android.provider.ContactsInternal;
115import android.provider.Settings;
116import android.security.Credentials;
117import android.security.IKeyChainAliasCallback;
118import android.security.IKeyChainService;
119import android.security.KeyChain;
120import android.security.KeyChain.KeyChainConnection;
121import android.service.persistentdata.PersistentDataBlockManager;
122import android.telephony.TelephonyManager;
123import android.text.TextUtils;
124import android.util.ArrayMap;
125import android.util.ArraySet;
126import android.util.Log;
127import android.util.Pair;
128import android.util.Slog;
129import android.util.SparseArray;
130import android.util.Xml;
131import android.view.IWindowManager;
132import android.view.accessibility.AccessibilityManager;
133import android.view.accessibility.IAccessibilityManager;
134import android.view.inputmethod.InputMethodInfo;
135import android.view.inputmethod.InputMethodManager;
136
137import com.android.internal.R;
138import com.android.internal.annotations.VisibleForTesting;
139import com.android.internal.logging.MetricsLogger;
140import com.android.internal.statusbar.IStatusBarService;
141import com.android.internal.util.ArrayUtils;
142import com.android.internal.util.FastXmlSerializer;
143import com.android.internal.util.JournaledFile;
144import com.android.internal.util.ParcelableString;
145import com.android.internal.util.Preconditions;
146import com.android.internal.util.XmlUtils;
147import com.android.internal.widget.LockPatternUtils;
148import com.android.server.LocalServices;
149import com.android.server.SystemService;
150import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
151import com.android.server.pm.UserRestrictionsUtils;
152import com.google.android.collect.Sets;
153
154import org.xmlpull.v1.XmlPullParser;
155import org.xmlpull.v1.XmlPullParserException;
156import org.xmlpull.v1.XmlSerializer;
157
158import java.io.ByteArrayInputStream;
159import java.io.File;
160import java.io.FileDescriptor;
161import java.io.FileInputStream;
162import java.io.FileNotFoundException;
163import java.io.FileOutputStream;
164import java.io.IOException;
165import java.io.PrintWriter;
166import java.lang.annotation.Retention;
167import java.lang.annotation.RetentionPolicy;
168import java.nio.charset.StandardCharsets;
169import java.security.cert.CertificateException;
170import java.security.cert.CertificateFactory;
171import java.security.cert.X509Certificate;
172import java.text.DateFormat;
173import java.util.ArrayList;
174import java.util.Arrays;
175import java.util.Collections;
176import java.util.Date;
177import java.util.List;
178import java.util.Map.Entry;
179import java.util.Set;
180import java.util.concurrent.atomic.AtomicBoolean;
181
182/**
183 * Implementation of the device policy APIs.
184 */
185public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
186
187    private static final String LOG_TAG = "DevicePolicyManager";
188
189    private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
190
191    private static final String DEVICE_POLICIES_XML = "device_policies.xml";
192
193    private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
194
195    private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
196
197    private static final String TAG_STATUS_BAR = "statusbar";
198
199    private static final String ATTR_DISABLED = "disabled";
200
201    private static final String ATTR_NAME = "name";
202
203    private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
204            "do-not-ask-credentials-on-boot";
205
206    private static final String TAG_AFFILIATION_ID = "affiliation-id";
207
208    private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval";
209
210    private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request";
211
212    private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval";
213
214    private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
215
216    private static final String ATTR_ID = "id";
217
218    private static final String ATTR_VALUE = "value";
219
220    private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
221
222    private static final int REQUEST_EXPIRE_PASSWORD = 5571;
223
224    private static final long MS_PER_DAY = 86400 * 1000;
225
226    private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
227
228    private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
229            = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
230
231    private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
232    private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
233
234    private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
235    private static final String ATTR_SETUP_COMPLETE = "setup-complete";
236    private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
237    private static final String ATTR_PERMISSION_POLICY = "permission-policy";
238    private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
239            "device-provisioning-config-applied";
240    private static final String ATTR_DEVICE_PAIRED = "device-paired";
241
242    private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
243    private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
244            = "application-restrictions-manager";
245
246    /**
247     *  System property whose value is either "true" or "false", indicating whether
248     *  device owner is present.
249     */
250    private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
251
252    private static final int STATUS_BAR_DISABLE_MASK =
253            StatusBarManager.DISABLE_EXPAND |
254            StatusBarManager.DISABLE_NOTIFICATION_ICONS |
255            StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
256            StatusBarManager.DISABLE_SEARCH;
257
258    private static final int STATUS_BAR_DISABLE2_MASK =
259            StatusBarManager.DISABLE2_QUICK_SETTINGS;
260
261    private static final Set<String> SECURE_SETTINGS_WHITELIST;
262    private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
263    private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
264    private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
265    static {
266        SECURE_SETTINGS_WHITELIST = new ArraySet<>();
267        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
268        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
269        SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
270
271        SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
272        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
273        SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
274
275        GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
276        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
277        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
278        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
279        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
280        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
281        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
282        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
283        GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
284
285        GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
286        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
287        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
288        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
289        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
290        GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
291    }
292
293    /**
294     * Keyguard features that when set on a managed profile that doesn't have its own challenge will
295     * affect the profile's parent user. These can also be set on the managed profile's parent DPM
296     * instance.
297     */
298    private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
299            DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
300            | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
301
302    /**
303     * Keyguard features that when set on a profile affect the profile content or challenge only.
304     * These cannot be set on the managed profile's parent DPM instance
305     */
306    private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
307            DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
308
309    /** Keyguard features that are allowed to be set on a managed profile */
310    private static final int PROFILE_KEYGUARD_FEATURES =
311            PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
312
313    private static final int CODE_OK = 0;
314    private static final int CODE_HAS_DEVICE_OWNER = 1;
315    private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
316    private static final int CODE_USER_NOT_RUNNING = 3;
317    private static final int CODE_USER_SETUP_COMPLETED = 4;
318    private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
319    private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
320    private static final int CODE_NOT_SYSTEM_USER = 7;
321    private static final int CODE_HAS_PAIRED = 8;
322
323    @Retention(RetentionPolicy.SOURCE)
324    @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
325            CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
326    private @interface DeviceOwnerPreConditionCode {}
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                }
3097                if (isProfileOwner(adminReceiver, userHandle)) {
3098                    final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3099                            userHandle, /* parent */ false);
3100                    clearProfileOwnerLocked(admin, userHandle);
3101                }
3102            }
3103            // Remove the admin skipping sending the broadcast.
3104            removeAdminArtifacts(adminReceiver, userHandle);
3105            Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3106        } finally {
3107            mInjector.binderRestoreCallingIdentity(ident);
3108        }
3109    }
3110
3111    /**
3112     * Return if a given package has testOnly="true", in which case we'll relax certain rules
3113     * for CTS.
3114     *
3115     * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
3116     * to check wehter an active admin is test-only or not.
3117     *
3118     * The system allows this flag to be changed when an app is updated, which is not good
3119     * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3120     * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3121     */
3122    private boolean isPackageTestOnly(String packageName, int userHandle) {
3123        final ApplicationInfo ai;
3124        try {
3125            ai = mIPackageManager.getApplicationInfo(packageName,
3126                    (PackageManager.MATCH_DIRECT_BOOT_AWARE
3127                            | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3128        } catch (RemoteException e) {
3129            throw new IllegalStateException(e);
3130        }
3131        if (ai == null) {
3132            throw new IllegalStateException("Couldn't find package: "
3133                    + packageName + " on user " + userHandle);
3134        }
3135        return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3136    }
3137
3138    /**
3139     * See {@link #isPackageTestOnly}.
3140     */
3141    private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3142        final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3143        return (admin != null) && admin.testOnlyAdmin;
3144    }
3145
3146    private void enforceShell(String method) {
3147        final int callingUid = Binder.getCallingUid();
3148        if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3149            throw new SecurityException("Non-shell user attempted to call " + method);
3150        }
3151    }
3152
3153    @Override
3154    public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3155        if (!mHasFeature) {
3156            return;
3157        }
3158        enforceFullCrossUsersPermission(userHandle);
3159        enforceUserUnlocked(userHandle);
3160        synchronized (this) {
3161            ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3162            if (admin == null) {
3163                return;
3164            }
3165            // Active device/profile owners must remain active admins.
3166            if (isDeviceOwner(adminReceiver, userHandle)
3167                    || isProfileOwner(adminReceiver, userHandle)) {
3168                Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3169                        adminReceiver);
3170                return;
3171            }
3172            if (admin.getUid() != mInjector.binderGetCallingUid()) {
3173                mContext.enforceCallingOrSelfPermission(
3174                        android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3175            }
3176            long ident = mInjector.binderClearCallingIdentity();
3177            try {
3178                removeActiveAdminLocked(adminReceiver, userHandle);
3179            } finally {
3180                mInjector.binderRestoreCallingIdentity(ident);
3181            }
3182        }
3183    }
3184
3185    @Override
3186    public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3187        ComponentName profileOwner = getProfileOwner(userHandle);
3188        // Profile challenge is supported on N or newer release.
3189        return profileOwner != null &&
3190                getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3191    }
3192
3193    @Override
3194    public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3195        if (!mHasFeature) {
3196            return;
3197        }
3198        Preconditions.checkNotNull(who, "ComponentName is null");
3199        validateQualityConstant(quality);
3200
3201        synchronized (this) {
3202            ActiveAdmin ap = getActiveAdminForCallerLocked(
3203                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3204            if (ap.minimumPasswordMetrics.quality != quality) {
3205                ap.minimumPasswordMetrics.quality = quality;
3206                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3207            }
3208        }
3209    }
3210
3211    @Override
3212    public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3213        if (!mHasFeature) {
3214            return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3215        }
3216        enforceFullCrossUsersPermission(userHandle);
3217        synchronized (this) {
3218            int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3219
3220            if (who != null) {
3221                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3222                return admin != null ? admin.minimumPasswordMetrics.quality : mode;
3223            }
3224
3225            // Return the strictest policy across all participating admins.
3226            List<ActiveAdmin> admins =
3227                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3228            final int N = admins.size();
3229            for (int i = 0; i < N; i++) {
3230                ActiveAdmin admin = admins.get(i);
3231                if (mode < admin.minimumPasswordMetrics.quality) {
3232                    mode = admin.minimumPasswordMetrics.quality;
3233                }
3234            }
3235            return mode;
3236        }
3237    }
3238
3239    private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3240            int userHandle, boolean parent) {
3241        if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3242            // If this user has a separate challenge, only return its restrictions.
3243            return getUserDataUnchecked(userHandle).mAdminList;
3244        } else {
3245            // Return all admins for this user and the profiles that are visible from this
3246            // user that do not use a separate work challenge.
3247            ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3248            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3249                DevicePolicyData policy = getUserData(userInfo.id);
3250                if (!userInfo.isManagedProfile()) {
3251                    admins.addAll(policy.mAdminList);
3252                } else {
3253                    // For managed profiles, we always include the policies set on the parent
3254                    // profile. Additionally, we include the ones set on the managed profile
3255                    // if no separate challenge is in place.
3256                    boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3257                    final int N = policy.mAdminList.size();
3258                    for (int i = 0; i < N; i++) {
3259                        ActiveAdmin admin = policy.mAdminList.get(i);
3260                        if (admin.hasParentActiveAdmin()) {
3261                            admins.add(admin.getParentActiveAdmin());
3262                        }
3263                        if (!hasSeparateChallenge) {
3264                            admins.add(admin);
3265                        }
3266                    }
3267                }
3268            }
3269            return admins;
3270        }
3271    }
3272
3273    private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3274        long ident = mInjector.binderClearCallingIdentity();
3275        try {
3276            return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3277        } finally {
3278            mInjector.binderRestoreCallingIdentity(ident);
3279        }
3280    }
3281
3282    @Override
3283    public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3284        if (!mHasFeature) {
3285            return;
3286        }
3287        Preconditions.checkNotNull(who, "ComponentName is null");
3288        synchronized (this) {
3289            ActiveAdmin ap = getActiveAdminForCallerLocked(
3290                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3291            if (ap.minimumPasswordMetrics.length != length) {
3292                ap.minimumPasswordMetrics.length = length;
3293                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3294            }
3295        }
3296    }
3297
3298    @Override
3299    public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3300        if (!mHasFeature) {
3301            return 0;
3302        }
3303        enforceFullCrossUsersPermission(userHandle);
3304        synchronized (this) {
3305            int length = 0;
3306
3307            if (who != null) {
3308                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3309                return admin != null ? admin.minimumPasswordMetrics.length : length;
3310            }
3311
3312            // Return the strictest policy across all participating admins.
3313            List<ActiveAdmin> admins =
3314                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3315            final int N = admins.size();
3316            for (int i = 0; i < N; i++) {
3317                ActiveAdmin admin = admins.get(i);
3318                if (length < admin.minimumPasswordMetrics.length) {
3319                    length = admin.minimumPasswordMetrics.length;
3320                }
3321            }
3322            return length;
3323        }
3324    }
3325
3326    @Override
3327    public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3328        if (!mHasFeature) {
3329            return;
3330        }
3331        Preconditions.checkNotNull(who, "ComponentName is null");
3332        synchronized (this) {
3333            ActiveAdmin ap = getActiveAdminForCallerLocked(
3334                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3335            if (ap.passwordHistoryLength != length) {
3336                ap.passwordHistoryLength = length;
3337                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3338            }
3339        }
3340    }
3341
3342    @Override
3343    public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3344        if (!mHasFeature) {
3345            return 0;
3346        }
3347        enforceFullCrossUsersPermission(userHandle);
3348        synchronized (this) {
3349            int length = 0;
3350
3351            if (who != null) {
3352                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3353                return admin != null ? admin.passwordHistoryLength : length;
3354            }
3355
3356            // Return the strictest policy across all participating admins.
3357            List<ActiveAdmin> admins =
3358                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3359            final int N = admins.size();
3360            for (int i = 0; i < N; i++) {
3361                ActiveAdmin admin = admins.get(i);
3362                if (length < admin.passwordHistoryLength) {
3363                    length = admin.passwordHistoryLength;
3364                }
3365            }
3366
3367            return length;
3368        }
3369    }
3370
3371    @Override
3372    public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3373        if (!mHasFeature) {
3374            return;
3375        }
3376        Preconditions.checkNotNull(who, "ComponentName is null");
3377        Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3378        final int userHandle = mInjector.userHandleGetCallingUserId();
3379        synchronized (this) {
3380            ActiveAdmin ap = getActiveAdminForCallerLocked(
3381                    who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3382            // Calling this API automatically bumps the expiration date
3383            final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3384            ap.passwordExpirationDate = expiration;
3385            ap.passwordExpirationTimeout = timeout;
3386            if (timeout > 0L) {
3387                Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3388                        + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3389                        .format(new Date(expiration)));
3390            }
3391            saveSettingsLocked(userHandle);
3392
3393            // in case this is the first one, set the alarm on the appropriate user.
3394            setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3395        }
3396    }
3397
3398    /**
3399     * Return a single admin's expiration cycle time, or the min of all cycle times.
3400     * Returns 0 if not configured.
3401     */
3402    @Override
3403    public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3404        if (!mHasFeature) {
3405            return 0L;
3406        }
3407        enforceFullCrossUsersPermission(userHandle);
3408        synchronized (this) {
3409            long timeout = 0L;
3410
3411            if (who != null) {
3412                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3413                return admin != null ? admin.passwordExpirationTimeout : timeout;
3414            }
3415
3416            // Return the strictest policy across all participating admins.
3417            List<ActiveAdmin> admins =
3418                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3419            final int N = admins.size();
3420            for (int i = 0; i < N; i++) {
3421                ActiveAdmin admin = admins.get(i);
3422                if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3423                        && timeout > admin.passwordExpirationTimeout)) {
3424                    timeout = admin.passwordExpirationTimeout;
3425                }
3426            }
3427            return timeout;
3428        }
3429    }
3430
3431    @Override
3432    public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3433        final int userId = UserHandle.getCallingUserId();
3434        List<String> changedProviders = null;
3435
3436        synchronized (this) {
3437            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3438                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3439            if (activeAdmin.crossProfileWidgetProviders == null) {
3440                activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3441            }
3442            List<String> providers = activeAdmin.crossProfileWidgetProviders;
3443            if (!providers.contains(packageName)) {
3444                providers.add(packageName);
3445                changedProviders = new ArrayList<>(providers);
3446                saveSettingsLocked(userId);
3447            }
3448        }
3449
3450        if (changedProviders != null) {
3451            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3452            return true;
3453        }
3454
3455        return false;
3456    }
3457
3458    @Override
3459    public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3460        final int userId = UserHandle.getCallingUserId();
3461        List<String> changedProviders = null;
3462
3463        synchronized (this) {
3464            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3465                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3466            if (activeAdmin.crossProfileWidgetProviders == null) {
3467                return false;
3468            }
3469            List<String> providers = activeAdmin.crossProfileWidgetProviders;
3470            if (providers.remove(packageName)) {
3471                changedProviders = new ArrayList<>(providers);
3472                saveSettingsLocked(userId);
3473            }
3474        }
3475
3476        if (changedProviders != null) {
3477            mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3478            return true;
3479        }
3480
3481        return false;
3482    }
3483
3484    @Override
3485    public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3486        synchronized (this) {
3487            ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3488                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3489            if (activeAdmin.crossProfileWidgetProviders == null
3490                    || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3491                return null;
3492            }
3493            if (mInjector.binderIsCallingUidMyUid()) {
3494                return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3495            } else {
3496                return activeAdmin.crossProfileWidgetProviders;
3497            }
3498        }
3499    }
3500
3501    /**
3502     * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3503     * Returns 0 if not configured.
3504     */
3505    private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3506        long timeout = 0L;
3507
3508        if (who != null) {
3509            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3510            return admin != null ? admin.passwordExpirationDate : timeout;
3511        }
3512
3513        // Return the strictest policy across all participating admins.
3514        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3515        final int N = admins.size();
3516        for (int i = 0; i < N; i++) {
3517            ActiveAdmin admin = admins.get(i);
3518            if (timeout == 0L || (admin.passwordExpirationDate != 0
3519                    && timeout > admin.passwordExpirationDate)) {
3520                timeout = admin.passwordExpirationDate;
3521            }
3522        }
3523        return timeout;
3524    }
3525
3526    @Override
3527    public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3528        if (!mHasFeature) {
3529            return 0L;
3530        }
3531        enforceFullCrossUsersPermission(userHandle);
3532        synchronized (this) {
3533            return getPasswordExpirationLocked(who, userHandle, parent);
3534        }
3535    }
3536
3537    @Override
3538    public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3539        if (!mHasFeature) {
3540            return;
3541        }
3542        Preconditions.checkNotNull(who, "ComponentName is null");
3543        synchronized (this) {
3544            ActiveAdmin ap = getActiveAdminForCallerLocked(
3545                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3546            if (ap.minimumPasswordMetrics.upperCase != length) {
3547                ap.minimumPasswordMetrics.upperCase = length;
3548                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3549            }
3550        }
3551    }
3552
3553    @Override
3554    public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3555        if (!mHasFeature) {
3556            return 0;
3557        }
3558        enforceFullCrossUsersPermission(userHandle);
3559        synchronized (this) {
3560            int length = 0;
3561
3562            if (who != null) {
3563                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3564                return admin != null ? admin.minimumPasswordMetrics.upperCase : length;
3565            }
3566
3567            // Return the strictest policy across all participating admins.
3568            List<ActiveAdmin> admins =
3569                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3570            final int N = admins.size();
3571            for (int i = 0; i < N; i++) {
3572                ActiveAdmin admin = admins.get(i);
3573                if (length < admin.minimumPasswordMetrics.upperCase) {
3574                    length = admin.minimumPasswordMetrics.upperCase;
3575                }
3576            }
3577            return length;
3578        }
3579    }
3580
3581    @Override
3582    public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3583        Preconditions.checkNotNull(who, "ComponentName is null");
3584        synchronized (this) {
3585            ActiveAdmin ap = getActiveAdminForCallerLocked(
3586                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3587            if (ap.minimumPasswordMetrics.lowerCase != length) {
3588                ap.minimumPasswordMetrics.lowerCase = length;
3589                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3590            }
3591        }
3592    }
3593
3594    @Override
3595    public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3596        if (!mHasFeature) {
3597            return 0;
3598        }
3599        enforceFullCrossUsersPermission(userHandle);
3600        synchronized (this) {
3601            int length = 0;
3602
3603            if (who != null) {
3604                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3605                return admin != null ? admin.minimumPasswordMetrics.lowerCase : length;
3606            }
3607
3608            // Return the strictest policy across all participating admins.
3609            List<ActiveAdmin> admins =
3610                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3611            final int N = admins.size();
3612            for (int i = 0; i < N; i++) {
3613                ActiveAdmin admin = admins.get(i);
3614                if (length < admin.minimumPasswordMetrics.lowerCase) {
3615                    length = admin.minimumPasswordMetrics.lowerCase;
3616                }
3617            }
3618            return length;
3619        }
3620    }
3621
3622    @Override
3623    public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3624        if (!mHasFeature) {
3625            return;
3626        }
3627        Preconditions.checkNotNull(who, "ComponentName is null");
3628        synchronized (this) {
3629            ActiveAdmin ap = getActiveAdminForCallerLocked(
3630                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3631            if (ap.minimumPasswordMetrics.letters != length) {
3632                ap.minimumPasswordMetrics.letters = length;
3633                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3634            }
3635        }
3636    }
3637
3638    @Override
3639    public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3640        if (!mHasFeature) {
3641            return 0;
3642        }
3643        enforceFullCrossUsersPermission(userHandle);
3644        synchronized (this) {
3645            int length = 0;
3646
3647            if (who != null) {
3648                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3649                return admin != null ? admin.minimumPasswordMetrics.letters : length;
3650            }
3651
3652            // Return the strictest policy across all participating admins.
3653            List<ActiveAdmin> admins =
3654                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3655            final int N = admins.size();
3656            for (int i = 0; i < N; i++) {
3657                ActiveAdmin admin = admins.get(i);
3658                if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3659                    continue;
3660                }
3661                if (length < admin.minimumPasswordMetrics.letters) {
3662                    length = admin.minimumPasswordMetrics.letters;
3663                }
3664            }
3665            return length;
3666        }
3667    }
3668
3669    @Override
3670    public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3671        if (!mHasFeature) {
3672            return;
3673        }
3674        Preconditions.checkNotNull(who, "ComponentName is null");
3675        synchronized (this) {
3676            ActiveAdmin ap = getActiveAdminForCallerLocked(
3677                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3678            if (ap.minimumPasswordMetrics.numeric != length) {
3679                ap.minimumPasswordMetrics.numeric = length;
3680                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3681            }
3682        }
3683    }
3684
3685    @Override
3686    public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3687        if (!mHasFeature) {
3688            return 0;
3689        }
3690        enforceFullCrossUsersPermission(userHandle);
3691        synchronized (this) {
3692            int length = 0;
3693
3694            if (who != null) {
3695                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3696                return admin != null ? admin.minimumPasswordMetrics.numeric : length;
3697            }
3698
3699            // Return the strictest policy across all participating admins.
3700            List<ActiveAdmin> admins =
3701                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3702            final int N = admins.size();
3703            for (int i = 0; i < N; i++) {
3704                ActiveAdmin admin = admins.get(i);
3705                if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3706                    continue;
3707                }
3708                if (length < admin.minimumPasswordMetrics.numeric) {
3709                    length = admin.minimumPasswordMetrics.numeric;
3710                }
3711            }
3712            return length;
3713        }
3714    }
3715
3716    @Override
3717    public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3718        if (!mHasFeature) {
3719            return;
3720        }
3721        Preconditions.checkNotNull(who, "ComponentName is null");
3722        synchronized (this) {
3723            ActiveAdmin ap = getActiveAdminForCallerLocked(
3724                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3725            if (ap.minimumPasswordMetrics.symbols != length) {
3726                ap.minimumPasswordMetrics.symbols = length;
3727                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3728            }
3729        }
3730    }
3731
3732    @Override
3733    public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3734        if (!mHasFeature) {
3735            return 0;
3736        }
3737        enforceFullCrossUsersPermission(userHandle);
3738        synchronized (this) {
3739            int length = 0;
3740
3741            if (who != null) {
3742                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3743                return admin != null ? admin.minimumPasswordMetrics.symbols : length;
3744            }
3745
3746            // Return the strictest policy across all participating admins.
3747            List<ActiveAdmin> admins =
3748                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3749            final int N = admins.size();
3750            for (int i = 0; i < N; i++) {
3751                ActiveAdmin admin = admins.get(i);
3752                if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3753                    continue;
3754                }
3755                if (length < admin.minimumPasswordMetrics.symbols) {
3756                    length = admin.minimumPasswordMetrics.symbols;
3757                }
3758            }
3759            return length;
3760        }
3761    }
3762
3763    @Override
3764    public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3765        if (!mHasFeature) {
3766            return;
3767        }
3768        Preconditions.checkNotNull(who, "ComponentName is null");
3769        synchronized (this) {
3770            ActiveAdmin ap = getActiveAdminForCallerLocked(
3771                    who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3772            if (ap.minimumPasswordMetrics.nonLetter != length) {
3773                ap.minimumPasswordMetrics.nonLetter = length;
3774                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3775            }
3776        }
3777    }
3778
3779    @Override
3780    public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3781        if (!mHasFeature) {
3782            return 0;
3783        }
3784        enforceFullCrossUsersPermission(userHandle);
3785        synchronized (this) {
3786            int length = 0;
3787
3788            if (who != null) {
3789                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3790                return admin != null ? admin.minimumPasswordMetrics.nonLetter : length;
3791            }
3792
3793            // Return the strictest policy across all participating admins.
3794            List<ActiveAdmin> admins =
3795                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3796            final int N = admins.size();
3797            for (int i = 0; i < N; i++) {
3798                ActiveAdmin admin = admins.get(i);
3799                if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3800                    continue;
3801                }
3802                if (length < admin.minimumPasswordMetrics.nonLetter) {
3803                    length = admin.minimumPasswordMetrics.nonLetter;
3804                }
3805            }
3806            return length;
3807        }
3808    }
3809
3810    @Override
3811    public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3812        if (!mHasFeature) {
3813            return true;
3814        }
3815        enforceFullCrossUsersPermission(userHandle);
3816
3817        synchronized (this) {
3818            // This API can only be called by an active device admin,
3819            // so try to retrieve it to check that the caller is one.
3820            getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3821            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3822            return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3823        }
3824    }
3825
3826    @Override
3827    public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3828        if (!mHasFeature) {
3829            return true;
3830        }
3831        enforceFullCrossUsersPermission(userHandle);
3832        enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3833
3834        synchronized (this) {
3835            int targetUser = getProfileParentId(userHandle);
3836            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3837            return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3838        }
3839    }
3840
3841    private boolean isActivePasswordSufficientForUserLocked(
3842            DevicePolicyData policy, int userHandle, boolean parent) {
3843        final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3844        if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) {
3845            return false;
3846        }
3847        if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3848                && policy.mActivePasswordMetrics.length < getPasswordMinimumLength(
3849                        null, userHandle, parent)) {
3850            return false;
3851        }
3852        if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3853            return true;
3854        }
3855        return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase(
3856                    null, userHandle, parent)
3857                && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase(
3858                        null, userHandle, parent)
3859                && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters(
3860                        null, userHandle, parent)
3861                && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric(
3862                        null, userHandle, parent)
3863                && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols(
3864                        null, userHandle, parent)
3865                && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter(
3866                        null, userHandle, parent);
3867    }
3868
3869    @Override
3870    public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3871        enforceFullCrossUsersPermission(userHandle);
3872        synchronized (this) {
3873            if (!isCallerWithSystemUid()) {
3874                // This API can only be called by an active device admin,
3875                // so try to retrieve it to check that the caller is one.
3876                getActiveAdminForCallerLocked(
3877                        null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3878            }
3879
3880            DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3881
3882            return policy.mFailedPasswordAttempts;
3883        }
3884    }
3885
3886    @Override
3887    public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3888        if (!mHasFeature) {
3889            return;
3890        }
3891        Preconditions.checkNotNull(who, "ComponentName is null");
3892        synchronized (this) {
3893            // This API can only be called by an active device admin,
3894            // so try to retrieve it to check that the caller is one.
3895            getActiveAdminForCallerLocked(
3896                    who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3897            ActiveAdmin ap = getActiveAdminForCallerLocked(
3898                    who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3899            if (ap.maximumFailedPasswordsForWipe != num) {
3900                ap.maximumFailedPasswordsForWipe = num;
3901                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3902            }
3903        }
3904    }
3905
3906    @Override
3907    public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3908        if (!mHasFeature) {
3909            return 0;
3910        }
3911        enforceFullCrossUsersPermission(userHandle);
3912        synchronized (this) {
3913            ActiveAdmin admin = (who != null)
3914                    ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3915                    : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3916            return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3917        }
3918    }
3919
3920    @Override
3921    public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3922        if (!mHasFeature) {
3923            return UserHandle.USER_NULL;
3924        }
3925        enforceFullCrossUsersPermission(userHandle);
3926        synchronized (this) {
3927            ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3928                    userHandle, parent);
3929            return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3930        }
3931    }
3932
3933    /**
3934     * Returns the admin with the strictest policy on maximum failed passwords for:
3935     * <ul>
3936     *   <li>this user if it has a separate profile challenge, or
3937     *   <li>this user and all profiles that don't have their own challenge otherwise.
3938     * </ul>
3939     * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3940     * the primary profile.
3941     * Returns {@code null} if no participating admin has that policy set.
3942     */
3943    private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3944            int userHandle, boolean parent) {
3945        int count = 0;
3946        ActiveAdmin strictestAdmin = null;
3947
3948        // Return the strictest policy across all participating admins.
3949        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3950        final int N = admins.size();
3951        for (int i = 0; i < N; i++) {
3952            ActiveAdmin admin = admins.get(i);
3953            if (admin.maximumFailedPasswordsForWipe ==
3954                    ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3955                continue;  // No max number of failed passwords policy set for this profile.
3956            }
3957
3958            // We always favor the primary profile if several profiles have the same value set.
3959            int userId = admin.getUserHandle().getIdentifier();
3960            if (count == 0 ||
3961                    count > admin.maximumFailedPasswordsForWipe ||
3962                    (count == admin.maximumFailedPasswordsForWipe &&
3963                            getUserInfo(userId).isPrimary())) {
3964                count = admin.maximumFailedPasswordsForWipe;
3965                strictestAdmin = admin;
3966            }
3967        }
3968        return strictestAdmin;
3969    }
3970
3971    private UserInfo getUserInfo(@UserIdInt int userId) {
3972        final long token = mInjector.binderClearCallingIdentity();
3973        try {
3974            return mUserManager.getUserInfo(userId);
3975        } finally {
3976            mInjector.binderRestoreCallingIdentity(token);
3977        }
3978    }
3979
3980    @Override
3981    public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3982        if (!mHasFeature) {
3983            return false;
3984        }
3985        final int callingUid = mInjector.binderGetCallingUid();
3986        final int userHandle = mInjector.userHandleGetCallingUserId();
3987
3988        String password = passwordOrNull != null ? passwordOrNull : "";
3989
3990        // Password resetting to empty/null is not allowed for managed profiles.
3991        if (TextUtils.isEmpty(password)) {
3992            enforceNotManagedProfile(userHandle, "clear the active password");
3993        }
3994
3995        int quality;
3996        synchronized (this) {
3997            // If caller has PO (or DO) it can change the password, so see if that's the case first.
3998            ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3999                    null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
4000            final boolean preN;
4001            if (admin != null) {
4002                preN = getTargetSdk(admin.info.getPackageName(),
4003                        userHandle) <= android.os.Build.VERSION_CODES.M;
4004            } else {
4005                // Otherwise, make sure the caller has any active admin with the right policy.
4006                admin = getActiveAdminForCallerLocked(null,
4007                        DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
4008                preN = getTargetSdk(admin.info.getPackageName(),
4009                        userHandle) <= android.os.Build.VERSION_CODES.M;
4010
4011                // As of N, password resetting to empty/null is not allowed anymore.
4012                // TODO Should we allow DO/PO to set an empty password?
4013                if (TextUtils.isEmpty(password)) {
4014                    if (!preN) {
4015                        throw new SecurityException("Cannot call with null password");
4016                    } else {
4017                        Slog.e(LOG_TAG, "Cannot call with null password");
4018                        return false;
4019                    }
4020                }
4021                // As of N, password cannot be changed by the admin if it is already set.
4022                if (isLockScreenSecureUnchecked(userHandle)) {
4023                    if (!preN) {
4024                        throw new SecurityException("Admin cannot change current password");
4025                    } else {
4026                        Slog.e(LOG_TAG, "Admin cannot change current password");
4027                        return false;
4028                    }
4029                }
4030            }
4031            // Do not allow to reset password when current user has a managed profile
4032            if (!isManagedProfile(userHandle)) {
4033                for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4034                    if (userInfo.isManagedProfile()) {
4035                        if (!preN) {
4036                            throw new IllegalStateException(
4037                                    "Cannot reset password on user has managed profile");
4038                        } else {
4039                            Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4040                            return false;
4041                        }
4042                    }
4043                }
4044            }
4045            // Do not allow to reset password when user is locked
4046            if (!mUserManager.isUserUnlocked(userHandle)) {
4047                if (!preN) {
4048                    throw new IllegalStateException("Cannot reset password when user is locked");
4049                } else {
4050                    Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4051                    return false;
4052                }
4053            }
4054
4055            quality = getPasswordQuality(null, userHandle, /* parent */ false);
4056            if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4057                quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4058            }
4059            final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
4060            if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
4061                final int realQuality = metrics.quality;
4062                if (realQuality < quality
4063                        && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4064                    Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4065                            + Integer.toHexString(realQuality)
4066                            + " does not meet required quality 0x"
4067                            + Integer.toHexString(quality));
4068                    return false;
4069                }
4070                quality = Math.max(realQuality, quality);
4071            }
4072            int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4073            if (password.length() < length) {
4074                Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4075                        + " does not meet required length " + length);
4076                return false;
4077            }
4078            if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4079                int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4080                if(metrics.letters < neededLetters) {
4081                    Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
4082                            + " does not meet required number of letters " + neededLetters);
4083                    return false;
4084                }
4085                int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4086                if (metrics.numeric < neededNumeric) {
4087                    Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
4088                            + " does not meet required number of numerical digits "
4089                            + neededNumeric);
4090                    return false;
4091                }
4092                int neededLowerCase = getPasswordMinimumLowerCase(
4093                        null, userHandle, /* parent */ false);
4094                if (metrics.lowerCase < neededLowerCase) {
4095                    Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
4096                            + metrics.lowerCase
4097                            + " does not meet required number of lowercase letters "
4098                            + neededLowerCase);
4099                    return false;
4100                }
4101                int neededUpperCase = getPasswordMinimumUpperCase(
4102                        null, userHandle, /* parent */ false);
4103                if (metrics.upperCase < neededUpperCase) {
4104                    Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
4105                            + metrics.upperCase
4106                            + " does not meet required number of uppercase letters "
4107                            + neededUpperCase);
4108                    return false;
4109                }
4110                int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4111                if (metrics.symbols < neededSymbols) {
4112                    Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
4113                            + " does not meet required number of special symbols " + neededSymbols);
4114                    return false;
4115                }
4116                int neededNonLetter = getPasswordMinimumNonLetter(
4117                        null, userHandle, /* parent */ false);
4118                if (metrics.nonLetter < neededNonLetter) {
4119                    Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
4120                            + metrics.nonLetter
4121                            + " does not meet required number of non-letter characters "
4122                            + neededNonLetter);
4123                    return false;
4124                }
4125            }
4126        }
4127
4128        DevicePolicyData policy = getUserData(userHandle);
4129        if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4130            Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4131            return false;
4132        }
4133
4134        boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4135        boolean doNotAskCredentialsOnBoot =
4136                (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4137        if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4138            setDoNotAskCredentialsOnBoot();
4139        }
4140
4141        // Don't do this with the lock held, because it is going to call
4142        // back in to the service.
4143        final long ident = mInjector.binderClearCallingIdentity();
4144        try {
4145            if (!TextUtils.isEmpty(password)) {
4146                mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4147            } else {
4148                mLockPatternUtils.clearLock(userHandle);
4149            }
4150            boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4151            if (requireEntry) {
4152                mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4153                        UserHandle.USER_ALL);
4154            }
4155            synchronized (this) {
4156                int newOwner = requireEntry ? callingUid : -1;
4157                if (policy.mPasswordOwner != newOwner) {
4158                    policy.mPasswordOwner = newOwner;
4159                    saveSettingsLocked(userHandle);
4160                }
4161            }
4162        } finally {
4163            mInjector.binderRestoreCallingIdentity(ident);
4164        }
4165
4166        return true;
4167    }
4168
4169    private boolean isLockScreenSecureUnchecked(int userId) {
4170        long ident = mInjector.binderClearCallingIdentity();
4171        try {
4172            return mLockPatternUtils.isSecure(userId);
4173        } finally {
4174            mInjector.binderRestoreCallingIdentity(ident);
4175        }
4176    }
4177
4178    private void setDoNotAskCredentialsOnBoot() {
4179        synchronized (this) {
4180            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4181            if (!policyData.doNotAskCredentialsOnBoot) {
4182                policyData.doNotAskCredentialsOnBoot = true;
4183                saveSettingsLocked(UserHandle.USER_SYSTEM);
4184            }
4185        }
4186    }
4187
4188    @Override
4189    public boolean getDoNotAskCredentialsOnBoot() {
4190        mContext.enforceCallingOrSelfPermission(
4191                android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4192        synchronized (this) {
4193            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4194            return policyData.doNotAskCredentialsOnBoot;
4195        }
4196    }
4197
4198    @Override
4199    public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4200        if (!mHasFeature) {
4201            return;
4202        }
4203        Preconditions.checkNotNull(who, "ComponentName is null");
4204        final int userHandle = mInjector.userHandleGetCallingUserId();
4205        synchronized (this) {
4206            ActiveAdmin ap = getActiveAdminForCallerLocked(
4207                    who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4208            if (ap.maximumTimeToUnlock != timeMs) {
4209                ap.maximumTimeToUnlock = timeMs;
4210                saveSettingsLocked(userHandle);
4211                updateMaximumTimeToLockLocked(userHandle);
4212            }
4213        }
4214    }
4215
4216    void updateMaximumTimeToLockLocked(int userHandle) {
4217        // Calculate the min timeout for all profiles - including the ones with a separate
4218        // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4219        // challenge only and keep the screen on. However there is no easy way of doing that at the
4220        // moment so we set the screen off timeout regardless of whether it affects the parent user
4221        // or the profile challenge only.
4222        long timeMs = Long.MAX_VALUE;
4223        int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4224        for (int profileId : profileIds) {
4225            DevicePolicyData policy = getUserDataUnchecked(profileId);
4226            final int N = policy.mAdminList.size();
4227            for (int i = 0; i < N; i++) {
4228                ActiveAdmin admin = policy.mAdminList.get(i);
4229                if (admin.maximumTimeToUnlock > 0
4230                        && timeMs > admin.maximumTimeToUnlock) {
4231                    timeMs = admin.maximumTimeToUnlock;
4232                }
4233                // If userInfo.id is a managed profile, we also need to look at
4234                // the policies set on the parent.
4235                if (admin.hasParentActiveAdmin()) {
4236                    final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4237                    if (parentAdmin.maximumTimeToUnlock > 0
4238                            && timeMs > parentAdmin.maximumTimeToUnlock) {
4239                        timeMs = parentAdmin.maximumTimeToUnlock;
4240                    }
4241                }
4242            }
4243        }
4244
4245        // We only store the last maximum time to lock on the parent profile. So if calling from a
4246        // managed profile, retrieve the policy for the parent.
4247        DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4248        if (policy.mLastMaximumTimeToLock == timeMs) {
4249            return;
4250        }
4251        policy.mLastMaximumTimeToLock = timeMs;
4252
4253        final long ident = mInjector.binderClearCallingIdentity();
4254        try {
4255            if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4256                // Make sure KEEP_SCREEN_ON is disabled, since that
4257                // would allow bypassing of the maximum time to lock.
4258                mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4259            }
4260
4261            mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4262                    (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4263        } finally {
4264            mInjector.binderRestoreCallingIdentity(ident);
4265        }
4266    }
4267
4268    @Override
4269    public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4270        if (!mHasFeature) {
4271            return 0;
4272        }
4273        enforceFullCrossUsersPermission(userHandle);
4274        synchronized (this) {
4275            if (who != null) {
4276                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4277                return admin != null ? admin.maximumTimeToUnlock : 0;
4278            }
4279            // Return the strictest policy across all participating admins.
4280            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4281                    userHandle, parent);
4282            return getMaximumTimeToLockPolicyFromAdmins(admins);
4283        }
4284    }
4285
4286    @Override
4287    public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4288        if (!mHasFeature) {
4289            return 0;
4290        }
4291        enforceFullCrossUsersPermission(userHandle);
4292        synchronized (this) {
4293            // All admins for this user.
4294            ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4295            for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4296                DevicePolicyData policy = getUserData(userInfo.id);
4297                admins.addAll(policy.mAdminList);
4298                // If it is a managed profile, it may have parent active admins
4299                if (userInfo.isManagedProfile()) {
4300                    for (ActiveAdmin admin : policy.mAdminList) {
4301                        if (admin.hasParentActiveAdmin()) {
4302                            admins.add(admin.getParentActiveAdmin());
4303                        }
4304                    }
4305                }
4306            }
4307            return getMaximumTimeToLockPolicyFromAdmins(admins);
4308        }
4309    }
4310
4311    private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4312        long time = 0;
4313        final int N = admins.size();
4314        for (int i = 0; i < N; i++) {
4315            ActiveAdmin admin = admins.get(i);
4316            if (time == 0) {
4317                time = admin.maximumTimeToUnlock;
4318            } else if (admin.maximumTimeToUnlock != 0
4319                    && time > admin.maximumTimeToUnlock) {
4320                time = admin.maximumTimeToUnlock;
4321            }
4322        }
4323        return time;
4324    }
4325
4326    @Override
4327    public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4328            boolean parent) {
4329        if (!mHasFeature) {
4330            return;
4331        }
4332        Preconditions.checkNotNull(who, "ComponentName is null");
4333        Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4334        // timeoutMs with value 0 means that the admin doesn't participate
4335        // timeoutMs is clamped to the interval in case the internal constants change in the future
4336        if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) {
4337            timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4338        }
4339        if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4340            timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4341        }
4342
4343        final int userHandle = mInjector.userHandleGetCallingUserId();
4344        synchronized (this) {
4345            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4346                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4347            if (ap.strongAuthUnlockTimeout != timeoutMs) {
4348                ap.strongAuthUnlockTimeout = timeoutMs;
4349                saveSettingsLocked(userHandle);
4350            }
4351        }
4352    }
4353
4354    /**
4355     * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4356     * admins if who is null.
4357     * Returns 0 if not configured for the provided admin.
4358     */
4359    @Override
4360    public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4361        if (!mHasFeature) {
4362            return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4363        }
4364        enforceFullCrossUsersPermission(userId);
4365        synchronized (this) {
4366            if (who != null) {
4367                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4368                return admin != null ? admin.strongAuthUnlockTimeout : 0;
4369            }
4370
4371            // Return the strictest policy across all participating admins.
4372            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4373
4374            long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4375            for (int i = 0; i < admins.size(); i++) {
4376                final long timeout = admins.get(i).strongAuthUnlockTimeout;
4377                if (timeout != 0) { // take only participating admins into account
4378                    strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4379                }
4380            }
4381            return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4382        }
4383    }
4384
4385    @Override
4386    public void lockNow(boolean parent) {
4387        if (!mHasFeature) {
4388            return;
4389        }
4390        synchronized (this) {
4391            // This API can only be called by an active device admin,
4392            // so try to retrieve it to check that the caller is one.
4393            getActiveAdminForCallerLocked(
4394                    null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4395
4396            int userToLock = mInjector.userHandleGetCallingUserId();
4397
4398            // Unless this is a managed profile with work challenge enabled, lock all users.
4399            if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4400                userToLock = UserHandle.USER_ALL;
4401            }
4402            final long ident = mInjector.binderClearCallingIdentity();
4403            try {
4404                mLockPatternUtils.requireStrongAuth(
4405                        STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4406                if (userToLock == UserHandle.USER_ALL) {
4407                    // Power off the display
4408                    mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4409                            PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4410                    mInjector.getIWindowManager().lockNow(null);
4411                }
4412            } catch (RemoteException e) {
4413            } finally {
4414                mInjector.binderRestoreCallingIdentity(ident);
4415            }
4416        }
4417    }
4418
4419    @Override
4420    public void enforceCanManageCaCerts(ComponentName who) {
4421        if (who == null) {
4422            if (!isCallerDelegatedCertInstaller()) {
4423                mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4424            }
4425        } else {
4426            synchronized (this) {
4427                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4428            }
4429        }
4430    }
4431
4432    private void enforceCanManageInstalledKeys(ComponentName who) {
4433        if (who == null) {
4434            if (!isCallerDelegatedCertInstaller()) {
4435                throw new SecurityException("who == null, but caller is not cert installer");
4436            }
4437        } else {
4438            synchronized (this) {
4439                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4440            }
4441        }
4442    }
4443
4444    private boolean isCallerDelegatedCertInstaller() {
4445        final int callingUid = mInjector.binderGetCallingUid();
4446        final int userHandle = UserHandle.getUserId(callingUid);
4447        synchronized (this) {
4448            final DevicePolicyData policy = getUserData(userHandle);
4449            if (policy.mDelegatedCertInstallerPackage == null) {
4450                return false;
4451            }
4452
4453            try {
4454                int uid = mContext.getPackageManager().getPackageUidAsUser(
4455                        policy.mDelegatedCertInstallerPackage, userHandle);
4456                return uid == callingUid;
4457            } catch (NameNotFoundException e) {
4458                return false;
4459            }
4460        }
4461    }
4462
4463    @Override
4464    public boolean approveCaCert(String alias, int userId, boolean approval) {
4465        enforceManageUsers();
4466        synchronized (this) {
4467            Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4468            boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4469            if (!changed) {
4470                return false;
4471            }
4472            saveSettingsLocked(userId);
4473        }
4474        new MonitoringCertNotificationTask().execute(userId);
4475        return true;
4476    }
4477
4478    @Override
4479    public boolean isCaCertApproved(String alias, int userId) {
4480        enforceManageUsers();
4481        synchronized (this) {
4482            return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4483        }
4484    }
4485
4486    private void removeCaApprovalsIfNeeded(int userId) {
4487        for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4488            boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4489            if (userInfo.isManagedProfile()){
4490                isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4491            }
4492            if (!isSecure) {
4493                synchronized (this) {
4494                    getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4495                    saveSettingsLocked(userInfo.id);
4496                }
4497
4498                new MonitoringCertNotificationTask().execute(userInfo.id);
4499            }
4500        }
4501    }
4502
4503    @Override
4504    public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4505        enforceCanManageCaCerts(admin);
4506
4507        byte[] pemCert;
4508        try {
4509            X509Certificate cert = parseCert(certBuffer);
4510            pemCert = Credentials.convertToPem(cert);
4511        } catch (CertificateException ce) {
4512            Log.e(LOG_TAG, "Problem converting cert", ce);
4513            return false;
4514        } catch (IOException ioe) {
4515            Log.e(LOG_TAG, "Problem reading cert", ioe);
4516            return false;
4517        }
4518
4519        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4520        final long id = mInjector.binderClearCallingIdentity();
4521        try {
4522            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4523            try {
4524                keyChainConnection.getService().installCaCertificate(pemCert);
4525                return true;
4526            } catch (RemoteException e) {
4527                Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4528            } finally {
4529                keyChainConnection.close();
4530            }
4531        } catch (InterruptedException e1) {
4532            Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4533            Thread.currentThread().interrupt();
4534        } finally {
4535            mInjector.binderRestoreCallingIdentity(id);
4536        }
4537        return false;
4538    }
4539
4540    private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4541        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4542        return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4543                certBuffer));
4544    }
4545
4546    @Override
4547    public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4548        enforceCanManageCaCerts(admin);
4549
4550        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4551        final long id = mInjector.binderClearCallingIdentity();
4552        try {
4553            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4554            try {
4555                for (int i = 0 ; i < aliases.length; i++) {
4556                    keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4557                }
4558            } catch (RemoteException e) {
4559                Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4560            } finally {
4561                keyChainConnection.close();
4562            }
4563        } catch (InterruptedException ie) {
4564            Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4565            Thread.currentThread().interrupt();
4566        } finally {
4567            mInjector.binderRestoreCallingIdentity(id);
4568        }
4569    }
4570
4571    @Override
4572    public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4573            String alias, boolean requestAccess) {
4574        enforceCanManageInstalledKeys(who);
4575
4576        final int callingUid = mInjector.binderGetCallingUid();
4577        final long id = mInjector.binderClearCallingIdentity();
4578        try {
4579            final KeyChainConnection keyChainConnection =
4580                    KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4581            try {
4582                IKeyChainService keyChain = keyChainConnection.getService();
4583                if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4584                    return false;
4585                }
4586                if (requestAccess) {
4587                    keyChain.setGrant(callingUid, alias, true);
4588                }
4589                return true;
4590            } catch (RemoteException e) {
4591                Log.e(LOG_TAG, "Installing certificate", e);
4592            } finally {
4593                keyChainConnection.close();
4594            }
4595        } catch (InterruptedException e) {
4596            Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4597            Thread.currentThread().interrupt();
4598        } finally {
4599            mInjector.binderRestoreCallingIdentity(id);
4600        }
4601        return false;
4602    }
4603
4604    @Override
4605    public boolean removeKeyPair(ComponentName who, String alias) {
4606        enforceCanManageInstalledKeys(who);
4607
4608        final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4609        final long id = Binder.clearCallingIdentity();
4610        try {
4611            final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4612            try {
4613                IKeyChainService keyChain = keyChainConnection.getService();
4614                return keyChain.removeKeyPair(alias);
4615            } catch (RemoteException e) {
4616                Log.e(LOG_TAG, "Removing keypair", e);
4617            } finally {
4618                keyChainConnection.close();
4619            }
4620        } catch (InterruptedException e) {
4621            Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4622            Thread.currentThread().interrupt();
4623        } finally {
4624            Binder.restoreCallingIdentity(id);
4625        }
4626        return false;
4627    }
4628
4629    @Override
4630    public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4631            final IBinder response) {
4632        // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4633        if (!isCallerWithSystemUid()) {
4634            return;
4635        }
4636
4637        final UserHandle caller = mInjector.binderGetCallingUserHandle();
4638        // If there is a profile owner, redirect to that; otherwise query the device owner.
4639        ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4640        if (aliasChooser == null && caller.isSystem()) {
4641            ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4642            if (deviceOwnerAdmin != null) {
4643                aliasChooser = deviceOwnerAdmin.info.getComponent();
4644            }
4645        }
4646        if (aliasChooser == null) {
4647            sendPrivateKeyAliasResponse(null, response);
4648            return;
4649        }
4650
4651        Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4652        intent.setComponent(aliasChooser);
4653        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4654        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4655        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4656        intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4657        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4658
4659        final long id = mInjector.binderClearCallingIdentity();
4660        try {
4661            mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4662                @Override
4663                public void onReceive(Context context, Intent intent) {
4664                    final String chosenAlias = getResultData();
4665                    sendPrivateKeyAliasResponse(chosenAlias, response);
4666                }
4667            }, null, Activity.RESULT_OK, null, null);
4668        } finally {
4669            mInjector.binderRestoreCallingIdentity(id);
4670        }
4671    }
4672
4673    private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4674        final IKeyChainAliasCallback keyChainAliasResponse =
4675                IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4676        new AsyncTask<Void, Void, Void>() {
4677            @Override
4678            protected Void doInBackground(Void... unused) {
4679                try {
4680                    keyChainAliasResponse.alias(alias);
4681                } catch (Exception e) {
4682                    // Catch everything (not just RemoteException): caller could throw a
4683                    // RuntimeException back across processes.
4684                    Log.e(LOG_TAG, "error while responding to callback", e);
4685                }
4686                return null;
4687            }
4688        }.execute();
4689    }
4690
4691    @Override
4692    public void setCertInstallerPackage(ComponentName who, String installerPackage)
4693            throws SecurityException {
4694        int userHandle = UserHandle.getCallingUserId();
4695        synchronized (this) {
4696            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4697            if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4698                if (installerPackage != null &&
4699                        !isPackageInstalledForUser(installerPackage, userHandle)) {
4700                    throw new IllegalArgumentException("Package " + installerPackage
4701                            + " is not installed on the current user");
4702                }
4703            }
4704            DevicePolicyData policy = getUserData(userHandle);
4705            policy.mDelegatedCertInstallerPackage = installerPackage;
4706            saveSettingsLocked(userHandle);
4707        }
4708    }
4709
4710    @Override
4711    public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4712        int userHandle = UserHandle.getCallingUserId();
4713        synchronized (this) {
4714            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4715            DevicePolicyData policy = getUserData(userHandle);
4716            return policy.mDelegatedCertInstallerPackage;
4717        }
4718    }
4719
4720    /**
4721     * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4722     * not installed and therefore not available.
4723     *
4724     * @throws SecurityException if the caller is not a profile or device owner.
4725     * @throws UnsupportedOperationException if the package does not support being set as always-on.
4726     */
4727    @Override
4728    public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4729            throws SecurityException {
4730        synchronized (this) {
4731            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4732        }
4733
4734        final int userId = mInjector.userHandleGetCallingUserId();
4735        final long token = mInjector.binderClearCallingIdentity();
4736        try {
4737            if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4738                return false;
4739            }
4740            ConnectivityManager connectivityManager = (ConnectivityManager)
4741                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4742            if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4743                throw new UnsupportedOperationException();
4744            }
4745        } finally {
4746            mInjector.binderRestoreCallingIdentity(token);
4747        }
4748        return true;
4749    }
4750
4751    @Override
4752    public String getAlwaysOnVpnPackage(ComponentName admin)
4753            throws SecurityException {
4754        synchronized (this) {
4755            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4756        }
4757
4758        final int userId = mInjector.userHandleGetCallingUserId();
4759        final long token = mInjector.binderClearCallingIdentity();
4760        try{
4761            ConnectivityManager connectivityManager = (ConnectivityManager)
4762                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4763            return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4764        } finally {
4765            mInjector.binderRestoreCallingIdentity(token);
4766        }
4767    }
4768
4769    private void wipeDataLocked(boolean wipeExtRequested, String reason, boolean force) {
4770        if (wipeExtRequested) {
4771            StorageManager sm = (StorageManager) mContext.getSystemService(
4772                    Context.STORAGE_SERVICE);
4773            sm.wipeAdoptableDisks();
4774        }
4775        try {
4776            RecoverySystem.rebootWipeUserData(mContext, false /* shutdown */, reason, force);
4777        } catch (IOException | SecurityException e) {
4778            Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4779        }
4780    }
4781
4782    @Override
4783    public void wipeData(int flags) {
4784        if (!mHasFeature) {
4785            return;
4786        }
4787        final int userHandle = mInjector.userHandleGetCallingUserId();
4788        enforceFullCrossUsersPermission(userHandle);
4789        synchronized (this) {
4790            // This API can only be called by an active device admin,
4791            // so try to retrieve it to check that the caller is one.
4792            final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4793                    DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4794
4795            final String source = admin.info.getComponent().flattenToShortString();
4796
4797            long ident = mInjector.binderClearCallingIdentity();
4798            try {
4799                if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4800                    if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4801                        throw new SecurityException(
4802                               "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4803                    }
4804                    PersistentDataBlockManager manager = (PersistentDataBlockManager)
4805                            mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4806                    if (manager != null) {
4807                        manager.wipe();
4808                    }
4809                }
4810                boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4811                // If the admin is the only one who has set the restriction: force wipe, even if
4812                // {@link UserManager.DISALLOW_FACTORY_RESET} is set. Reason is that the admin
4813                // could remove this user restriction anyway.
4814                boolean force = (userHandle == UserHandle.USER_SYSTEM)
4815                        && isAdminOnlyOneWhoSetRestriction(admin,
4816                                UserManager.DISALLOW_FACTORY_RESET, UserHandle.USER_SYSTEM);
4817                wipeDeviceOrUserLocked(wipeExtRequested, userHandle,
4818                        "DevicePolicyManager.wipeData() from " + source, force);
4819            } finally {
4820                mInjector.binderRestoreCallingIdentity(ident);
4821            }
4822        }
4823    }
4824
4825    private boolean isAdminOnlyOneWhoSetRestriction(ActiveAdmin admin, String userRestriction,
4826            int userId) {
4827        int source = mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId));
4828        if (isDeviceOwner(admin.info.getComponent(), userId)) {
4829            return source == UserManager.RESTRICTION_SOURCE_DEVICE_OWNER;
4830        } else if (isProfileOwner(admin.info.getComponent(), userId)) {
4831            return source == UserManager.RESTRICTION_SOURCE_PROFILE_OWNER;
4832        }
4833        return false;
4834    }
4835
4836    private void wipeDeviceOrUserLocked(boolean wipeExtRequested, final int userHandle,
4837            String reason, boolean force) {
4838        if (userHandle == UserHandle.USER_SYSTEM) {
4839            wipeDataLocked(wipeExtRequested, reason, force);
4840        } else {
4841            mHandler.post(new Runnable() {
4842                @Override
4843                public void run() {
4844                    try {
4845                        IActivityManager am = mInjector.getIActivityManager();
4846                        if (am.getCurrentUser().id == userHandle) {
4847                            am.switchUser(UserHandle.USER_SYSTEM);
4848                        }
4849
4850                        boolean isManagedProfile = isManagedProfile(userHandle);
4851                        if (!mUserManager.removeUser(userHandle)) {
4852                            Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4853                        } else if (isManagedProfile) {
4854                            sendWipeProfileNotification();
4855                        }
4856                    } catch (RemoteException re) {
4857                        // Shouldn't happen
4858                    }
4859                }
4860            });
4861        }
4862    }
4863
4864    private void sendWipeProfileNotification() {
4865        String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4866        Notification notification = new Notification.Builder(mContext)
4867                .setSmallIcon(android.R.drawable.stat_sys_warning)
4868                .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4869                .setContentText(contentText)
4870                .setColor(mContext.getColor(R.color.system_notification_accent_color))
4871                .setStyle(new Notification.BigTextStyle().bigText(contentText))
4872                .build();
4873        mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4874    }
4875
4876    private void clearWipeProfileNotification() {
4877        mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4878    }
4879
4880    @Override
4881    public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4882        if (!mHasFeature) {
4883            return;
4884        }
4885        enforceFullCrossUsersPermission(userHandle);
4886        mContext.enforceCallingOrSelfPermission(
4887                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4888
4889        synchronized (this) {
4890            ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4891            if (admin == null) {
4892                result.sendResult(null);
4893                return;
4894            }
4895            Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4896            intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4897            intent.setComponent(admin.info.getComponent());
4898            mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4899                    null, new BroadcastReceiver() {
4900                @Override
4901                public void onReceive(Context context, Intent intent) {
4902                    result.sendResult(getResultExtras(false));
4903                }
4904            }, null, Activity.RESULT_OK, null, null);
4905        }
4906    }
4907
4908    @Override
4909    public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
4910        if (!mHasFeature) {
4911            return;
4912        }
4913        enforceFullCrossUsersPermission(userHandle);
4914
4915        // Managed Profile password can only be changed when it has a separate challenge.
4916        if (!isSeparateProfileChallengeEnabled(userHandle)) {
4917            enforceNotManagedProfile(userHandle, "set the active password");
4918        }
4919
4920        mContext.enforceCallingOrSelfPermission(
4921                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4922        validateQualityConstant(metrics.quality);
4923
4924        DevicePolicyData policy = getUserData(userHandle);
4925
4926        long ident = mInjector.binderClearCallingIdentity();
4927        try {
4928            synchronized (this) {
4929                policy.mActivePasswordMetrics = metrics;
4930                policy.mFailedPasswordAttempts = 0;
4931                saveSettingsLocked(userHandle);
4932                updatePasswordExpirationsLocked(userHandle);
4933                setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
4934
4935                // Send a broadcast to each profile using this password as its primary unlock.
4936                sendAdminCommandForLockscreenPoliciesLocked(
4937                        DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4938                        DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle);
4939            }
4940            removeCaApprovalsIfNeeded(userHandle);
4941        } finally {
4942            mInjector.binderRestoreCallingIdentity(ident);
4943        }
4944    }
4945
4946    /**
4947     * Called any time the device password is updated. Resets all password expiration clocks.
4948     */
4949    private void updatePasswordExpirationsLocked(int userHandle) {
4950        ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4951        List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4952                userHandle, /* parent */ false);
4953        final int N = admins.size();
4954        for (int i = 0; i < N; i++) {
4955            ActiveAdmin admin = admins.get(i);
4956            if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4957                affectedUserIds.add(admin.getUserHandle().getIdentifier());
4958                long timeout = admin.passwordExpirationTimeout;
4959                long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4960                admin.passwordExpirationDate = expiration;
4961            }
4962        }
4963        for (int affectedUserId : affectedUserIds) {
4964            saveSettingsLocked(affectedUserId);
4965        }
4966    }
4967
4968    @Override
4969    public void reportFailedPasswordAttempt(int userHandle) {
4970        enforceFullCrossUsersPermission(userHandle);
4971        if (!isSeparateProfileChallengeEnabled(userHandle)) {
4972            enforceNotManagedProfile(userHandle,
4973                    "report failed password attempt if separate profile challenge is not in place");
4974        }
4975        mContext.enforceCallingOrSelfPermission(
4976                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4977
4978        final long ident = mInjector.binderClearCallingIdentity();
4979        try {
4980            boolean wipeData = false;
4981            int identifier = 0;
4982            synchronized (this) {
4983                DevicePolicyData policy = getUserData(userHandle);
4984                policy.mFailedPasswordAttempts++;
4985                saveSettingsLocked(userHandle);
4986                if (mHasFeature) {
4987                    ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4988                            userHandle, /* parent */ false);
4989                    int max = strictestAdmin != null
4990                            ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4991                    if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4992                        // Wipe the user/profile associated with the policy that was violated. This
4993                        // is not necessarily calling user: if the policy that fired was from a
4994                        // managed profile rather than the main user profile, we wipe former only.
4995                        wipeData = true;
4996                        identifier = strictestAdmin.getUserHandle().getIdentifier();
4997                    }
4998
4999                    sendAdminCommandForLockscreenPoliciesLocked(
5000                            DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
5001                            DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5002                }
5003            }
5004            if (wipeData) {
5005                // Call without holding lock.
5006                wipeDeviceOrUserLocked(false, identifier,
5007                        "reportFailedPasswordAttempt()", false);
5008            }
5009        } finally {
5010            mInjector.binderRestoreCallingIdentity(ident);
5011        }
5012
5013        if (mInjector.securityLogIsLoggingEnabled()) {
5014            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5015                    /*method strength*/ 1);
5016        }
5017    }
5018
5019    @Override
5020    public void reportSuccessfulPasswordAttempt(int userHandle) {
5021        enforceFullCrossUsersPermission(userHandle);
5022        mContext.enforceCallingOrSelfPermission(
5023                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5024
5025        synchronized (this) {
5026            DevicePolicyData policy = getUserData(userHandle);
5027            if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
5028                long ident = mInjector.binderClearCallingIdentity();
5029                try {
5030                    policy.mFailedPasswordAttempts = 0;
5031                    policy.mPasswordOwner = -1;
5032                    saveSettingsLocked(userHandle);
5033                    if (mHasFeature) {
5034                        sendAdminCommandForLockscreenPoliciesLocked(
5035                                DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
5036                                DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
5037                    }
5038                } finally {
5039                    mInjector.binderRestoreCallingIdentity(ident);
5040                }
5041            }
5042        }
5043
5044        if (mInjector.securityLogIsLoggingEnabled()) {
5045            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5046                    /*method strength*/ 1);
5047        }
5048    }
5049
5050    @Override
5051    public void reportFailedFingerprintAttempt(int userHandle) {
5052        enforceFullCrossUsersPermission(userHandle);
5053        mContext.enforceCallingOrSelfPermission(
5054                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5055        if (mInjector.securityLogIsLoggingEnabled()) {
5056            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5057                    /*method strength*/ 0);
5058        }
5059    }
5060
5061    @Override
5062    public void reportSuccessfulFingerprintAttempt(int userHandle) {
5063        enforceFullCrossUsersPermission(userHandle);
5064        mContext.enforceCallingOrSelfPermission(
5065                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5066        if (mInjector.securityLogIsLoggingEnabled()) {
5067            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5068                    /*method strength*/ 0);
5069        }
5070    }
5071
5072    @Override
5073    public void reportKeyguardDismissed(int userHandle) {
5074        enforceFullCrossUsersPermission(userHandle);
5075        mContext.enforceCallingOrSelfPermission(
5076                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5077
5078        if (mInjector.securityLogIsLoggingEnabled()) {
5079            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5080        }
5081    }
5082
5083    @Override
5084    public void reportKeyguardSecured(int userHandle) {
5085        enforceFullCrossUsersPermission(userHandle);
5086        mContext.enforceCallingOrSelfPermission(
5087                android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5088
5089        if (mInjector.securityLogIsLoggingEnabled()) {
5090            SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5091        }
5092    }
5093
5094    @Override
5095    public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5096            String exclusionList) {
5097        if (!mHasFeature) {
5098            return null;
5099        }
5100        synchronized(this) {
5101            Preconditions.checkNotNull(who, "ComponentName is null");
5102
5103            // Only check if system user has set global proxy. We don't allow other users to set it.
5104            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5105            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5106                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5107
5108            // Scan through active admins and find if anyone has already
5109            // set the global proxy.
5110            Set<ComponentName> compSet = policy.mAdminMap.keySet();
5111            for (ComponentName component : compSet) {
5112                ActiveAdmin ap = policy.mAdminMap.get(component);
5113                if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5114                    // Another admin already sets the global proxy
5115                    // Return it to the caller.
5116                    return component;
5117                }
5118            }
5119
5120            // If the user is not system, don't set the global proxy. Fail silently.
5121            if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5122                Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5123                        + UserHandle.getCallingUserId() + " is not permitted.");
5124                return null;
5125            }
5126            if (proxySpec == null) {
5127                admin.specifiesGlobalProxy = false;
5128                admin.globalProxySpec = null;
5129                admin.globalProxyExclusionList = null;
5130            } else {
5131
5132                admin.specifiesGlobalProxy = true;
5133                admin.globalProxySpec = proxySpec;
5134                admin.globalProxyExclusionList = exclusionList;
5135            }
5136
5137            // Reset the global proxy accordingly
5138            // Do this using system permissions, as apps cannot write to secure settings
5139            long origId = mInjector.binderClearCallingIdentity();
5140            try {
5141                resetGlobalProxyLocked(policy);
5142            } finally {
5143                mInjector.binderRestoreCallingIdentity(origId);
5144            }
5145            return null;
5146        }
5147    }
5148
5149    @Override
5150    public ComponentName getGlobalProxyAdmin(int userHandle) {
5151        if (!mHasFeature) {
5152            return null;
5153        }
5154        enforceFullCrossUsersPermission(userHandle);
5155        synchronized(this) {
5156            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5157            // Scan through active admins and find if anyone has already
5158            // set the global proxy.
5159            final int N = policy.mAdminList.size();
5160            for (int i = 0; i < N; i++) {
5161                ActiveAdmin ap = policy.mAdminList.get(i);
5162                if (ap.specifiesGlobalProxy) {
5163                    // Device admin sets the global proxy
5164                    // Return it to the caller.
5165                    return ap.info.getComponent();
5166                }
5167            }
5168        }
5169        // No device admin sets the global proxy.
5170        return null;
5171    }
5172
5173    @Override
5174    public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5175        synchronized (this) {
5176            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5177        }
5178        long token = mInjector.binderClearCallingIdentity();
5179        try {
5180            ConnectivityManager connectivityManager = (ConnectivityManager)
5181                    mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5182            connectivityManager.setGlobalProxy(proxyInfo);
5183        } finally {
5184            mInjector.binderRestoreCallingIdentity(token);
5185        }
5186    }
5187
5188    private void resetGlobalProxyLocked(DevicePolicyData policy) {
5189        final int N = policy.mAdminList.size();
5190        for (int i = 0; i < N; i++) {
5191            ActiveAdmin ap = policy.mAdminList.get(i);
5192            if (ap.specifiesGlobalProxy) {
5193                saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5194                return;
5195            }
5196        }
5197        // No device admins defining global proxies - reset global proxy settings to none
5198        saveGlobalProxyLocked(null, null);
5199    }
5200
5201    private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5202        if (exclusionList == null) {
5203            exclusionList = "";
5204        }
5205        if (proxySpec == null) {
5206            proxySpec = "";
5207        }
5208        // Remove white spaces
5209        proxySpec = proxySpec.trim();
5210        String data[] = proxySpec.split(":");
5211        int proxyPort = 8080;
5212        if (data.length > 1) {
5213            try {
5214                proxyPort = Integer.parseInt(data[1]);
5215            } catch (NumberFormatException e) {}
5216        }
5217        exclusionList = exclusionList.trim();
5218
5219        ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5220        if (!proxyProperties.isValid()) {
5221            Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5222            return;
5223        }
5224        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5225        mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5226        mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5227                exclusionList);
5228    }
5229
5230    /**
5231     * Set the storage encryption request for a single admin.  Returns the new total request
5232     * status (for all admins).
5233     */
5234    @Override
5235    public int setStorageEncryption(ComponentName who, boolean encrypt) {
5236        if (!mHasFeature) {
5237            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5238        }
5239        Preconditions.checkNotNull(who, "ComponentName is null");
5240        final int userHandle = UserHandle.getCallingUserId();
5241        synchronized (this) {
5242            // Check for permissions
5243            // Only system user can set storage encryption
5244            if (userHandle != UserHandle.USER_SYSTEM) {
5245                Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5246                        + UserHandle.getCallingUserId() + " is not permitted.");
5247                return 0;
5248            }
5249
5250            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5251                    DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5252
5253            // Quick exit:  If the filesystem does not support encryption, we can exit early.
5254            if (!isEncryptionSupported()) {
5255                return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5256            }
5257
5258            // (1) Record the value for the admin so it's sticky
5259            if (ap.encryptionRequested != encrypt) {
5260                ap.encryptionRequested = encrypt;
5261                saveSettingsLocked(userHandle);
5262            }
5263
5264            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5265            // (2) Compute "max" for all admins
5266            boolean newRequested = false;
5267            final int N = policy.mAdminList.size();
5268            for (int i = 0; i < N; i++) {
5269                newRequested |= policy.mAdminList.get(i).encryptionRequested;
5270            }
5271
5272            // Notify OS of new request
5273            setEncryptionRequested(newRequested);
5274
5275            // Return the new global request status
5276            return newRequested
5277                    ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5278                    : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5279        }
5280    }
5281
5282    /**
5283     * Get the current storage encryption request status for a given admin, or aggregate of all
5284     * active admins.
5285     */
5286    @Override
5287    public boolean getStorageEncryption(ComponentName who, int userHandle) {
5288        if (!mHasFeature) {
5289            return false;
5290        }
5291        enforceFullCrossUsersPermission(userHandle);
5292        synchronized (this) {
5293            // Check for permissions if a particular caller is specified
5294            if (who != null) {
5295                // When checking for a single caller, status is based on caller's request
5296                ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5297                return ap != null ? ap.encryptionRequested : false;
5298            }
5299
5300            // If no particular caller is specified, return the aggregate set of requests.
5301            // This is short circuited by returning true on the first hit.
5302            DevicePolicyData policy = getUserData(userHandle);
5303            final int N = policy.mAdminList.size();
5304            for (int i = 0; i < N; i++) {
5305                if (policy.mAdminList.get(i).encryptionRequested) {
5306                    return true;
5307                }
5308            }
5309            return false;
5310        }
5311    }
5312
5313    /**
5314     * Get the current encryption status of the device.
5315     */
5316    @Override
5317    public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5318        if (!mHasFeature) {
5319            // Ok to return current status.
5320        }
5321        enforceFullCrossUsersPermission(userHandle);
5322
5323        // It's not critical here, but let's make sure the package name is correct, in case
5324        // we start using it for different purposes.
5325        ensureCallerPackage(callerPackage);
5326
5327        final ApplicationInfo ai;
5328        try {
5329            ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5330        } catch (RemoteException e) {
5331            throw new SecurityException(e);
5332        }
5333
5334        boolean legacyApp = false;
5335        if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5336            legacyApp = true;
5337        }
5338
5339        final int rawStatus = getEncryptionStatus();
5340        if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5341            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5342        }
5343        return rawStatus;
5344    }
5345
5346    /**
5347     * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
5348     */
5349    private boolean isEncryptionSupported() {
5350        // Note, this can be implemented as
5351        //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5352        // But is provided as a separate internal method if there's a faster way to do a
5353        // simple check for supported-or-not.
5354        return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5355    }
5356
5357    /**
5358     * Hook to low-levels:  Reporting the current status of encryption.
5359     * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5360     * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5361     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5362     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5363     * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5364     */
5365    private int getEncryptionStatus() {
5366        if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5367            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5368        } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5369            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5370        } else if (mInjector.storageManagerIsEncrypted()) {
5371            return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5372        } else if (mInjector.storageManagerIsEncryptable()) {
5373            return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5374        } else {
5375            return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5376        }
5377    }
5378
5379    /**
5380     * Hook to low-levels:  If needed, record the new admin setting for encryption.
5381     */
5382    private void setEncryptionRequested(boolean encrypt) {
5383    }
5384
5385    /**
5386     * Set whether the screen capture is disabled for the user managed by the specified admin.
5387     */
5388    @Override
5389    public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5390        if (!mHasFeature) {
5391            return;
5392        }
5393        Preconditions.checkNotNull(who, "ComponentName is null");
5394        final int userHandle = UserHandle.getCallingUserId();
5395        synchronized (this) {
5396            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5397                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5398            if (ap.disableScreenCapture != disabled) {
5399                ap.disableScreenCapture = disabled;
5400                saveSettingsLocked(userHandle);
5401                updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5402            }
5403        }
5404    }
5405
5406    /**
5407     * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5408     * active admin (if given admin is null).
5409     */
5410    @Override
5411    public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5412        if (!mHasFeature) {
5413            return false;
5414        }
5415        synchronized (this) {
5416            if (who != null) {
5417                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5418                return (admin != null) ? admin.disableScreenCapture : false;
5419            }
5420
5421            DevicePolicyData policy = getUserData(userHandle);
5422            final int N = policy.mAdminList.size();
5423            for (int i = 0; i < N; i++) {
5424                ActiveAdmin admin = policy.mAdminList.get(i);
5425                if (admin.disableScreenCapture) {
5426                    return true;
5427                }
5428            }
5429            return false;
5430        }
5431    }
5432
5433    private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5434            final boolean disabled) {
5435        mHandler.post(new Runnable() {
5436            @Override
5437            public void run() {
5438                try {
5439                    mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5440                } catch (RemoteException e) {
5441                    Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5442                }
5443            }
5444        });
5445    }
5446
5447    /**
5448     * Set whether auto time is required by the specified admin (must be device owner).
5449     */
5450    @Override
5451    public void setAutoTimeRequired(ComponentName who, boolean required) {
5452        if (!mHasFeature) {
5453            return;
5454        }
5455        Preconditions.checkNotNull(who, "ComponentName is null");
5456        final int userHandle = UserHandle.getCallingUserId();
5457        synchronized (this) {
5458            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5459                    DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5460            if (admin.requireAutoTime != required) {
5461                admin.requireAutoTime = required;
5462                saveSettingsLocked(userHandle);
5463            }
5464        }
5465
5466        // Turn AUTO_TIME on in settings if it is required
5467        if (required) {
5468            long ident = mInjector.binderClearCallingIdentity();
5469            try {
5470                mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5471            } finally {
5472                mInjector.binderRestoreCallingIdentity(ident);
5473            }
5474        }
5475    }
5476
5477    /**
5478     * Returns whether or not auto time is required by the device owner.
5479     */
5480    @Override
5481    public boolean getAutoTimeRequired() {
5482        if (!mHasFeature) {
5483            return false;
5484        }
5485        synchronized (this) {
5486            ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5487            return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5488        }
5489    }
5490
5491    @Override
5492    public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5493        if (!mHasFeature) {
5494            return;
5495        }
5496        Preconditions.checkNotNull(who, "ComponentName is null");
5497        // Allow setting this policy to true only if there is a split system user.
5498        if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5499            throw new UnsupportedOperationException(
5500                    "Cannot force ephemeral users on systems without split system user.");
5501        }
5502        boolean removeAllUsers = false;
5503        synchronized (this) {
5504            final ActiveAdmin deviceOwner =
5505                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5506            if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5507                deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5508                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5509                mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5510                removeAllUsers = forceEphemeralUsers;
5511            }
5512        }
5513        if (removeAllUsers) {
5514            long identitity = mInjector.binderClearCallingIdentity();
5515            try {
5516                mUserManagerInternal.removeAllUsers();
5517            } finally {
5518                mInjector.binderRestoreCallingIdentity(identitity);
5519            }
5520        }
5521    }
5522
5523    @Override
5524    public boolean getForceEphemeralUsers(ComponentName who) {
5525        if (!mHasFeature) {
5526            return false;
5527        }
5528        Preconditions.checkNotNull(who, "ComponentName is null");
5529        synchronized (this) {
5530            final ActiveAdmin deviceOwner =
5531                    getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5532            return deviceOwner.forceEphemeralUsers;
5533        }
5534    }
5535
5536    private boolean isDeviceOwnerManagedSingleUserDevice() {
5537        synchronized (this) {
5538            if (!mOwners.hasDeviceOwner()) {
5539                return false;
5540            }
5541        }
5542        final long callingIdentity = mInjector.binderClearCallingIdentity();
5543        try {
5544            if (mInjector.userManagerIsSplitSystemUser()) {
5545                // In split system user mode, only allow the case where the device owner is managing
5546                // the only non-system user of the device
5547                return (mUserManager.getUserCount() == 2
5548                        && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5549            } else  {
5550                return mUserManager.getUserCount() == 1;
5551            }
5552        } finally {
5553            mInjector.binderRestoreCallingIdentity(callingIdentity);
5554        }
5555    }
5556
5557    private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5558        synchronized (this) {
5559            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5560        }
5561        if (!isDeviceOwnerManagedSingleUserDevice()) {
5562            throw new SecurityException(
5563                    "There should only be one user, managed by Device Owner");
5564        }
5565    }
5566
5567    @Override
5568    public boolean requestBugreport(ComponentName who) {
5569        if (!mHasFeature) {
5570            return false;
5571        }
5572        Preconditions.checkNotNull(who, "ComponentName is null");
5573        ensureDeviceOwnerManagingSingleUser(who);
5574
5575        if (mRemoteBugreportServiceIsActive.get()
5576                || (getDeviceOwnerRemoteBugreportUri() != null)) {
5577            Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5578            return false;
5579        }
5580
5581        final long currentTime = System.currentTimeMillis();
5582        synchronized (this) {
5583            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
5584            if (currentTime > policyData.mLastBugReportRequestTime) {
5585                policyData.mLastBugReportRequestTime = currentTime;
5586                saveSettingsLocked(UserHandle.USER_SYSTEM);
5587            }
5588        }
5589
5590        final long callingIdentity = mInjector.binderClearCallingIdentity();
5591        try {
5592            mInjector.getIActivityManager().requestBugReport(
5593                    ActivityManager.BUGREPORT_OPTION_REMOTE);
5594
5595            mRemoteBugreportServiceIsActive.set(true);
5596            mRemoteBugreportSharingAccepted.set(false);
5597            registerRemoteBugreportReceivers();
5598            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5599                    RemoteBugreportUtils.buildNotification(mContext,
5600                            DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5601            mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5602                    RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5603            return true;
5604        } catch (RemoteException re) {
5605            // should never happen
5606            Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5607            return false;
5608        } finally {
5609            mInjector.binderRestoreCallingIdentity(callingIdentity);
5610        }
5611    }
5612
5613    synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5614        Intent intent = new Intent(action);
5615        intent.setComponent(mOwners.getDeviceOwnerComponent());
5616        if (extras != null) {
5617            intent.putExtras(extras);
5618        }
5619        mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5620    }
5621
5622    private synchronized String getDeviceOwnerRemoteBugreportUri() {
5623        return mOwners.getDeviceOwnerRemoteBugreportUri();
5624    }
5625
5626    private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5627            String bugreportHash) {
5628        mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5629    }
5630
5631    private void registerRemoteBugreportReceivers() {
5632        try {
5633            IntentFilter filterFinished = new IntentFilter(
5634                    DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5635                    RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5636            mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5637        } catch (IntentFilter.MalformedMimeTypeException e) {
5638            // should never happen, as setting a constant
5639            Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5640        }
5641        IntentFilter filterConsent = new IntentFilter();
5642        filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5643        filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5644        mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5645    }
5646
5647    private void onBugreportFinished(Intent intent) {
5648        mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5649        mRemoteBugreportServiceIsActive.set(false);
5650        Uri bugreportUri = intent.getData();
5651        String bugreportUriString = null;
5652        if (bugreportUri != null) {
5653            bugreportUriString = bugreportUri.toString();
5654        }
5655        String bugreportHash = intent.getStringExtra(
5656                DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5657        if (mRemoteBugreportSharingAccepted.get()) {
5658            shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5659            mInjector.getNotificationManager().cancel(LOG_TAG,
5660                    RemoteBugreportUtils.NOTIFICATION_ID);
5661        } else {
5662            setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5663            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5664                    RemoteBugreportUtils.buildNotification(mContext,
5665                            DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5666                            UserHandle.ALL);
5667        }
5668        mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5669    }
5670
5671    private void onBugreportFailed() {
5672        mRemoteBugreportServiceIsActive.set(false);
5673        mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5674                RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5675        mRemoteBugreportSharingAccepted.set(false);
5676        setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5677        mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5678        Bundle extras = new Bundle();
5679        extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5680                DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5681        sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5682        mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5683        mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5684    }
5685
5686    private void onBugreportSharingAccepted() {
5687        mRemoteBugreportSharingAccepted.set(true);
5688        String bugreportUriString = null;
5689        String bugreportHash = null;
5690        synchronized (this) {
5691            bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5692            bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5693        }
5694        if (bugreportUriString != null) {
5695            shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5696        } else if (mRemoteBugreportServiceIsActive.get()) {
5697            mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5698                    RemoteBugreportUtils.buildNotification(mContext,
5699                            DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5700                            UserHandle.ALL);
5701        }
5702    }
5703
5704    private void onBugreportSharingDeclined() {
5705        if (mRemoteBugreportServiceIsActive.get()) {
5706            mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5707                    RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5708            mRemoteBugreportServiceIsActive.set(false);
5709            mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5710            mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5711        }
5712        mRemoteBugreportSharingAccepted.set(false);
5713        setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5714        sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5715    }
5716
5717    private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5718            String bugreportHash) {
5719        ParcelFileDescriptor pfd = null;
5720        try {
5721            if (bugreportUriString == null) {
5722                throw new FileNotFoundException();
5723            }
5724            Uri bugreportUri = Uri.parse(bugreportUriString);
5725            pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5726
5727            synchronized (this) {
5728                Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5729                intent.setComponent(mOwners.getDeviceOwnerComponent());
5730                intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5731                intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5732                mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5733                        bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5734                mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5735            }
5736        } catch (FileNotFoundException e) {
5737            Bundle extras = new Bundle();
5738            extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5739                    DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5740            sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5741        } finally {
5742            try {
5743                if (pfd != null) {
5744                    pfd.close();
5745                }
5746            } catch (IOException ex) {
5747                // Ignore
5748            }
5749            mRemoteBugreportSharingAccepted.set(false);
5750            setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5751        }
5752    }
5753
5754    /**
5755     * Disables all device cameras according to the specified admin.
5756     */
5757    @Override
5758    public void setCameraDisabled(ComponentName who, boolean disabled) {
5759        if (!mHasFeature) {
5760            return;
5761        }
5762        Preconditions.checkNotNull(who, "ComponentName is null");
5763        final int userHandle = mInjector.userHandleGetCallingUserId();
5764        synchronized (this) {
5765            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5766                    DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5767            if (ap.disableCamera != disabled) {
5768                ap.disableCamera = disabled;
5769                saveSettingsLocked(userHandle);
5770            }
5771        }
5772        // Tell the user manager that the restrictions have changed.
5773        pushUserRestrictions(userHandle);
5774    }
5775
5776    /**
5777     * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5778     * active admins.
5779     */
5780    @Override
5781    public boolean getCameraDisabled(ComponentName who, int userHandle) {
5782        return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5783    }
5784
5785    private boolean getCameraDisabled(ComponentName who, int userHandle,
5786            boolean mergeDeviceOwnerRestriction) {
5787        if (!mHasFeature) {
5788            return false;
5789        }
5790        synchronized (this) {
5791            if (who != null) {
5792                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5793                return (admin != null) ? admin.disableCamera : false;
5794            }
5795            // First, see if DO has set it.  If so, it's device-wide.
5796            if (mergeDeviceOwnerRestriction) {
5797                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5798                if (deviceOwner != null && deviceOwner.disableCamera) {
5799                    return true;
5800                }
5801            }
5802
5803            // Then check each device admin on the user.
5804            DevicePolicyData policy = getUserData(userHandle);
5805            // Determine whether or not the device camera is disabled for any active admins.
5806            final int N = policy.mAdminList.size();
5807            for (int i = 0; i < N; i++) {
5808                ActiveAdmin admin = policy.mAdminList.get(i);
5809                if (admin.disableCamera) {
5810                    return true;
5811                }
5812            }
5813            return false;
5814        }
5815    }
5816
5817    @Override
5818    public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5819        if (!mHasFeature) {
5820            return;
5821        }
5822        Preconditions.checkNotNull(who, "ComponentName is null");
5823        final int userHandle = mInjector.userHandleGetCallingUserId();
5824        if (isManagedProfile(userHandle)) {
5825            if (parent) {
5826                which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5827            } else {
5828                which = which & PROFILE_KEYGUARD_FEATURES;
5829            }
5830        }
5831        synchronized (this) {
5832            ActiveAdmin ap = getActiveAdminForCallerLocked(
5833                    who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5834            if (ap.disabledKeyguardFeatures != which) {
5835                ap.disabledKeyguardFeatures = which;
5836                saveSettingsLocked(userHandle);
5837            }
5838        }
5839    }
5840
5841    /**
5842     * Gets the disabled state for features in keyguard for the given admin,
5843     * or the aggregate of all active admins if who is null.
5844     */
5845    @Override
5846    public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5847        if (!mHasFeature) {
5848            return 0;
5849        }
5850        enforceFullCrossUsersPermission(userHandle);
5851        final long ident = mInjector.binderClearCallingIdentity();
5852        try {
5853            synchronized (this) {
5854                if (who != null) {
5855                    ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5856                    return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5857                }
5858
5859                final List<ActiveAdmin> admins;
5860                if (!parent && isManagedProfile(userHandle)) {
5861                    // If we are being asked about a managed profile, just return keyguard features
5862                    // disabled by admins in the profile.
5863                    admins = getUserDataUnchecked(userHandle).mAdminList;
5864                } else {
5865                    // Otherwise return those set by admins in the user and its profiles.
5866                    admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5867                }
5868
5869                int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5870                final int N = admins.size();
5871                for (int i = 0; i < N; i++) {
5872                    ActiveAdmin admin = admins.get(i);
5873                    int userId = admin.getUserHandle().getIdentifier();
5874                    boolean isRequestedUser = !parent && (userId == userHandle);
5875                    if (isRequestedUser || !isManagedProfile(userId)) {
5876                        // If we are being asked explicitly about this user
5877                        // return all disabled features even if its a managed profile.
5878                        which |= admin.disabledKeyguardFeatures;
5879                    } else {
5880                        // Otherwise a managed profile is only allowed to disable
5881                        // some features on the parent user.
5882                        which |= (admin.disabledKeyguardFeatures
5883                                & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5884                    }
5885                }
5886                return which;
5887            }
5888        } finally {
5889            mInjector.binderRestoreCallingIdentity(ident);
5890        }
5891    }
5892
5893    @Override
5894    public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5895        if (!mHasFeature) {
5896            return;
5897        }
5898        Preconditions.checkNotNull(who, "ComponentName is null");
5899        Preconditions.checkNotNull(packageList, "packageList is null");
5900        final int userHandle = UserHandle.getCallingUserId();
5901        synchronized (this) {
5902            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5903                    DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5904            admin.keepUninstalledPackages = packageList;
5905            saveSettingsLocked(userHandle);
5906            mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5907        }
5908    }
5909
5910    @Override
5911    public List<String> getKeepUninstalledPackages(ComponentName who) {
5912        Preconditions.checkNotNull(who, "ComponentName is null");
5913        if (!mHasFeature) {
5914            return null;
5915        }
5916        // TODO In split system user mode, allow apps on user 0 to query the list
5917        synchronized (this) {
5918            // Check if this is the device owner who is calling
5919            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5920            return getKeepUninstalledPackagesLocked();
5921        }
5922    }
5923
5924    private List<String> getKeepUninstalledPackagesLocked() {
5925        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5926        return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5927    }
5928
5929    @Override
5930    public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5931        if (!mHasFeature) {
5932            return false;
5933        }
5934        if (admin == null
5935                || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5936            throw new IllegalArgumentException("Invalid component " + admin
5937                    + " for device owner");
5938        }
5939        synchronized (this) {
5940            enforceCanSetDeviceOwnerLocked(admin, userId);
5941            if (getActiveAdminUncheckedLocked(admin, userId) == null
5942                    || getUserData(userId).mRemovingAdmins.contains(admin)) {
5943                throw new IllegalArgumentException("Not active admin: " + admin);
5944            }
5945
5946            // Shutting down backup manager service permanently.
5947            long ident = mInjector.binderClearCallingIdentity();
5948            try {
5949                if (mInjector.getIBackupManager() != null) {
5950                    mInjector.getIBackupManager()
5951                            .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5952                }
5953            } catch (RemoteException e) {
5954                throw new IllegalStateException("Failed deactivating backup service.", e);
5955            } finally {
5956                mInjector.binderRestoreCallingIdentity(ident);
5957            }
5958
5959            if (isAdb()) {
5960                // Log device owner provisioning was started using adb.
5961                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
5962            }
5963
5964            mOwners.setDeviceOwner(admin, ownerName, userId);
5965            mOwners.writeDeviceOwner();
5966            updateDeviceOwnerLocked();
5967            setDeviceOwnerSystemPropertyLocked();
5968            Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5969
5970            ident = mInjector.binderClearCallingIdentity();
5971            try {
5972                // TODO Send to system too?
5973                mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5974            } finally {
5975                mInjector.binderRestoreCallingIdentity(ident);
5976            }
5977            Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5978            return true;
5979        }
5980    }
5981
5982    @Override
5983    public boolean hasDeviceOwner() {
5984        enforceDeviceOwnerOrManageUsers();
5985        return mOwners.hasDeviceOwner();
5986    }
5987
5988    boolean isDeviceOwner(ActiveAdmin admin) {
5989        return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
5990    }
5991
5992    public boolean isDeviceOwner(ComponentName who, int userId) {
5993        synchronized (this) {
5994            return mOwners.hasDeviceOwner()
5995                    && mOwners.getDeviceOwnerUserId() == userId
5996                    && mOwners.getDeviceOwnerComponent().equals(who);
5997        }
5998    }
5999
6000    public boolean isProfileOwner(ComponentName who, int userId) {
6001        final ComponentName profileOwner = getProfileOwner(userId);
6002        return who != null && who.equals(profileOwner);
6003    }
6004
6005    @Override
6006    public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
6007        if (!mHasFeature) {
6008            return null;
6009        }
6010        if (!callingUserOnly) {
6011            enforceManageUsers();
6012        }
6013        synchronized (this) {
6014            if (!mOwners.hasDeviceOwner()) {
6015                return null;
6016            }
6017            if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
6018                    mOwners.getDeviceOwnerUserId()) {
6019                return null;
6020            }
6021            return mOwners.getDeviceOwnerComponent();
6022        }
6023    }
6024
6025    @Override
6026    public int getDeviceOwnerUserId() {
6027        if (!mHasFeature) {
6028            return UserHandle.USER_NULL;
6029        }
6030        enforceManageUsers();
6031        synchronized (this) {
6032            return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
6033        }
6034    }
6035
6036    /**
6037     * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
6038     * MANAGE_USERS.
6039     */
6040    @Override
6041    public String getDeviceOwnerName() {
6042        if (!mHasFeature) {
6043            return null;
6044        }
6045        enforceManageUsers();
6046        synchronized (this) {
6047            if (!mOwners.hasDeviceOwner()) {
6048                return null;
6049            }
6050            // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
6051            // Should setDeviceOwner/ProfileOwner still take a name?
6052            String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
6053            return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
6054        }
6055    }
6056
6057    // Returns the active device owner or null if there is no device owner.
6058    @VisibleForTesting
6059    ActiveAdmin getDeviceOwnerAdminLocked() {
6060        ComponentName component = mOwners.getDeviceOwnerComponent();
6061        if (component == null) {
6062            return null;
6063        }
6064
6065        DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
6066        final int n = policy.mAdminList.size();
6067        for (int i = 0; i < n; i++) {
6068            ActiveAdmin admin = policy.mAdminList.get(i);
6069            if (component.equals(admin.info.getComponent())) {
6070                return admin;
6071            }
6072        }
6073        Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6074        return null;
6075    }
6076
6077    @Override
6078    public void clearDeviceOwner(String packageName) {
6079        Preconditions.checkNotNull(packageName, "packageName is null");
6080        final int callingUid = mInjector.binderGetCallingUid();
6081        try {
6082            int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
6083                    UserHandle.getUserId(callingUid));
6084            if (uid != callingUid) {
6085                throw new SecurityException("Invalid packageName");
6086            }
6087        } catch (NameNotFoundException e) {
6088            throw new SecurityException(e);
6089        }
6090        synchronized (this) {
6091            final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6092            final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6093            if (!mOwners.hasDeviceOwner()
6094                    || !deviceOwnerComponent.getPackageName().equals(packageName)
6095                    || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6096                throw new SecurityException(
6097                        "clearDeviceOwner can only be called by the device owner");
6098            }
6099            enforceUserUnlocked(deviceOwnerUserId);
6100
6101            final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6102            long ident = mInjector.binderClearCallingIdentity();
6103            try {
6104                clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6105                removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6106                Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
6107                mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId));
6108            } finally {
6109                mInjector.binderRestoreCallingIdentity(ident);
6110            }
6111            Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6112        }
6113    }
6114
6115    private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6116        if (admin != null) {
6117            admin.disableCamera = false;
6118            admin.userRestrictions = null;
6119            admin.forceEphemeralUsers = false;
6120            mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6121            final DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6122            policyData.mLastSecurityLogRetrievalTime = -1;
6123            policyData.mLastBugReportRequestTime = -1;
6124            policyData.mLastNetworkLogsRetrievalTime = -1;
6125            saveSettingsLocked(UserHandle.USER_SYSTEM);
6126        }
6127        clearUserPoliciesLocked(userId);
6128
6129        mOwners.clearDeviceOwner();
6130        mOwners.writeDeviceOwner();
6131        updateDeviceOwnerLocked();
6132        disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
6133        try {
6134            if (mInjector.getIBackupManager() != null) {
6135                // Reactivate backup service.
6136                mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6137            }
6138        } catch (RemoteException e) {
6139            throw new IllegalStateException("Failed reactivating backup service.", e);
6140        }
6141    }
6142
6143    @Override
6144    public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6145        if (!mHasFeature) {
6146            return false;
6147        }
6148        if (who == null
6149                || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6150            throw new IllegalArgumentException("Component " + who
6151                    + " not installed for userId:" + userHandle);
6152        }
6153        synchronized (this) {
6154            enforceCanSetProfileOwnerLocked(who, userHandle);
6155
6156            if (getActiveAdminUncheckedLocked(who, userHandle) == null
6157                    || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6158                throw new IllegalArgumentException("Not active admin: " + who);
6159            }
6160
6161            if (isAdb()) {
6162                // Log profile owner provisioning was started using adb.
6163                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
6164            }
6165
6166            mOwners.setProfileOwner(who, ownerName, userHandle);
6167            mOwners.writeProfileOwner(userHandle);
6168            Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6169            return true;
6170        }
6171    }
6172
6173    @Override
6174    public void clearProfileOwner(ComponentName who) {
6175        if (!mHasFeature) {
6176            return;
6177        }
6178        final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6179        final int userId = callingUser.getIdentifier();
6180        enforceNotManagedProfile(userId, "clear profile owner");
6181        enforceUserUnlocked(userId);
6182        // Check if this is the profile owner who is calling
6183        final ActiveAdmin admin =
6184                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6185        synchronized (this) {
6186            final long ident = mInjector.binderClearCallingIdentity();
6187            try {
6188                clearProfileOwnerLocked(admin, userId);
6189                removeActiveAdminLocked(who, userId);
6190            } finally {
6191                mInjector.binderRestoreCallingIdentity(ident);
6192            }
6193            Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6194        }
6195    }
6196
6197    public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6198        if (admin != null) {
6199            admin.disableCamera = false;
6200            admin.userRestrictions = null;
6201        }
6202        clearUserPoliciesLocked(userId);
6203        mOwners.removeProfileOwner(userId);
6204        mOwners.writeProfileOwner(userId);
6205    }
6206
6207    @Override
6208    public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6209        Preconditions.checkNotNull(who, "ComponentName is null");
6210        if (!mHasFeature) {
6211            return;
6212        }
6213
6214        synchronized (this) {
6215            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6216            long token = mInjector.binderClearCallingIdentity();
6217            try {
6218                mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6219            } finally {
6220                mInjector.binderRestoreCallingIdentity(token);
6221            }
6222        }
6223    }
6224
6225    @Override
6226    public CharSequence getDeviceOwnerLockScreenInfo() {
6227        return mLockPatternUtils.getDeviceOwnerInfo();
6228    }
6229
6230    private void clearUserPoliciesLocked(int userId) {
6231        // Reset some of the user-specific policies
6232        DevicePolicyData policy = getUserData(userId);
6233        policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6234        policy.mDelegatedCertInstallerPackage = null;
6235        policy.mApplicationRestrictionsManagingPackage = null;
6236        policy.mStatusBarDisabled = false;
6237        policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6238        saveSettingsLocked(userId);
6239
6240        try {
6241            mIPackageManager.updatePermissionFlagsForAllApps(
6242                    PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6243                    0  /* flagValues */, userId);
6244            pushUserRestrictions(userId);
6245        } catch (RemoteException re) {
6246            // Shouldn't happen.
6247        }
6248    }
6249
6250    @Override
6251    public boolean hasUserSetupCompleted() {
6252        return hasUserSetupCompleted(UserHandle.getCallingUserId());
6253    }
6254
6255    // This checks only if the Setup Wizard has run.  Since Wear devices pair before
6256    // completing Setup Wizard, and pairing involves transferring user data, calling
6257    // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6258    private boolean hasUserSetupCompleted(int userHandle) {
6259        if (!mHasFeature) {
6260            return true;
6261        }
6262        return getUserData(userHandle).mUserSetupComplete;
6263    }
6264
6265    private boolean hasPaired(int userHandle) {
6266        if (!mHasFeature) {
6267            return true;
6268        }
6269        return getUserData(userHandle).mPaired;
6270    }
6271
6272    @Override
6273    public int getUserProvisioningState() {
6274        if (!mHasFeature) {
6275            return DevicePolicyManager.STATE_USER_UNMANAGED;
6276        }
6277        int userHandle = mInjector.userHandleGetCallingUserId();
6278        return getUserProvisioningState(userHandle);
6279    }
6280
6281    private int getUserProvisioningState(int userHandle) {
6282        return getUserData(userHandle).mUserProvisioningState;
6283    }
6284
6285    @Override
6286    public void setUserProvisioningState(int newState, int userHandle) {
6287        if (!mHasFeature) {
6288            return;
6289        }
6290
6291        if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6292                && getManagedUserId(userHandle) == -1) {
6293            // No managed device, user or profile, so setting provisioning state makes no sense.
6294            throw new IllegalStateException("Not allowed to change provisioning state unless a "
6295                      + "device or profile owner is set.");
6296        }
6297
6298        synchronized (this) {
6299            boolean transitionCheckNeeded = true;
6300
6301            // Calling identity/permission checks.
6302            if (isAdb()) {
6303                // ADB shell can only move directly from un-managed to finalized as part of directly
6304                // setting profile-owner or device-owner.
6305                if (getUserProvisioningState(userHandle) !=
6306                        DevicePolicyManager.STATE_USER_UNMANAGED
6307                        || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6308                    throw new IllegalStateException("Not allowed to change provisioning state "
6309                            + "unless current provisioning state is unmanaged, and new state is "
6310                            + "finalized.");
6311                }
6312                transitionCheckNeeded = false;
6313            } else {
6314                // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6315                enforceCanManageProfileAndDeviceOwners();
6316            }
6317
6318            final DevicePolicyData policyData = getUserData(userHandle);
6319            if (transitionCheckNeeded) {
6320                // Optional state transition check for non-ADB case.
6321                checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6322            }
6323            policyData.mUserProvisioningState = newState;
6324            saveSettingsLocked(userHandle);
6325        }
6326    }
6327
6328    private void checkUserProvisioningStateTransition(int currentState, int newState) {
6329        // Valid transitions for normal use-cases.
6330        switch (currentState) {
6331            case DevicePolicyManager.STATE_USER_UNMANAGED:
6332                // Can move to any state from unmanaged (except itself as an edge case)..
6333                if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6334                    return;
6335                }
6336                break;
6337            case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6338            case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6339                // Can only move to finalized from these states.
6340                if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6341                    return;
6342                }
6343                break;
6344            case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6345                // Current user has a managed-profile, but current user is not managed, so
6346                // rather than moving to finalized state, go back to unmanaged once
6347                // profile provisioning is complete.
6348                if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6349                    return;
6350                }
6351                break;
6352            case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6353                // Cannot transition out of finalized.
6354                break;
6355        }
6356
6357        // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6358        throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6359                + "from state [" + currentState + "]");
6360    }
6361
6362    @Override
6363    public void setProfileEnabled(ComponentName who) {
6364        if (!mHasFeature) {
6365            return;
6366        }
6367        Preconditions.checkNotNull(who, "ComponentName is null");
6368        synchronized (this) {
6369            // Check if this is the profile owner who is calling
6370            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6371            final int userId = UserHandle.getCallingUserId();
6372            enforceManagedProfile(userId, "enable the profile");
6373            // Check if the profile is already enabled.
6374            UserInfo managedProfile = getUserInfo(userId);
6375            if (managedProfile.isEnabled()) {
6376                Slog.e(LOG_TAG,
6377                        "setProfileEnabled is called when the profile is already enabled");
6378                return;
6379            }
6380            long id = mInjector.binderClearCallingIdentity();
6381            try {
6382                mUserManager.setUserEnabled(userId);
6383                UserInfo parent = mUserManager.getProfileParent(userId);
6384                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6385                intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6386                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6387                        Intent.FLAG_RECEIVER_FOREGROUND);
6388                mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6389            } finally {
6390                mInjector.binderRestoreCallingIdentity(id);
6391            }
6392        }
6393    }
6394
6395    @Override
6396    public void setProfileName(ComponentName who, String profileName) {
6397        Preconditions.checkNotNull(who, "ComponentName is null");
6398        int userId = UserHandle.getCallingUserId();
6399        // Check if this is the profile owner (includes device owner).
6400        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6401
6402        long id = mInjector.binderClearCallingIdentity();
6403        try {
6404            mUserManager.setUserName(userId, profileName);
6405        } finally {
6406            mInjector.binderRestoreCallingIdentity(id);
6407        }
6408    }
6409
6410    @Override
6411    public ComponentName getProfileOwner(int userHandle) {
6412        if (!mHasFeature) {
6413            return null;
6414        }
6415
6416        synchronized (this) {
6417            return mOwners.getProfileOwnerComponent(userHandle);
6418        }
6419    }
6420
6421    // Returns the active profile owner for this user or null if the current user has no
6422    // profile owner.
6423    @VisibleForTesting
6424    ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6425        ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6426        if (profileOwner == null) {
6427            return null;
6428        }
6429        DevicePolicyData policy = getUserData(userHandle);
6430        final int n = policy.mAdminList.size();
6431        for (int i = 0; i < n; i++) {
6432            ActiveAdmin admin = policy.mAdminList.get(i);
6433            if (profileOwner.equals(admin.info.getComponent())) {
6434                return admin;
6435            }
6436        }
6437        return null;
6438    }
6439
6440    @Override
6441    public String getProfileOwnerName(int userHandle) {
6442        if (!mHasFeature) {
6443            return null;
6444        }
6445        enforceManageUsers();
6446        ComponentName profileOwner = getProfileOwner(userHandle);
6447        if (profileOwner == null) {
6448            return null;
6449        }
6450        return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6451    }
6452
6453    /**
6454     * Canonical name for a given package.
6455     */
6456    private String getApplicationLabel(String packageName, int userHandle) {
6457        long token = mInjector.binderClearCallingIdentity();
6458        try {
6459            final Context userContext;
6460            try {
6461                UserHandle handle = new UserHandle(userHandle);
6462                userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6463            } catch (PackageManager.NameNotFoundException nnfe) {
6464                Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6465                return null;
6466            }
6467            ApplicationInfo appInfo = userContext.getApplicationInfo();
6468            CharSequence result = null;
6469            if (appInfo != null) {
6470                PackageManager pm = userContext.getPackageManager();
6471                result = pm.getApplicationLabel(appInfo);
6472            }
6473            return result != null ? result.toString() : null;
6474        } finally {
6475            mInjector.binderRestoreCallingIdentity(token);
6476        }
6477    }
6478
6479    /**
6480     * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6481     * permission.
6482     * The profile owner can only be set before the user setup phase has completed,
6483     * except for:
6484     * - SYSTEM_UID
6485     * - adb if there are no accounts. (But see {@link #hasIncompatibleAccountsLocked})
6486     */
6487    private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle) {
6488        UserInfo info = getUserInfo(userHandle);
6489        if (info == null) {
6490            // User doesn't exist.
6491            throw new IllegalArgumentException(
6492                    "Attempted to set profile owner for invalid userId: " + userHandle);
6493        }
6494        if (info.isGuest()) {
6495            throw new IllegalStateException("Cannot set a profile owner on a guest");
6496        }
6497        if (mOwners.hasProfileOwner(userHandle)) {
6498            throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6499                    + "is already set.");
6500        }
6501        if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6502            throw new IllegalStateException("Trying to set the profile owner, but the user "
6503                    + "already has a device owner.");
6504        }
6505        if (isAdb()) {
6506            if ((mIsWatch || hasUserSetupCompleted(userHandle))
6507                    && hasIncompatibleAccountsLocked(userHandle, owner)) {
6508                throw new IllegalStateException("Not allowed to set the profile owner because "
6509                        + "there are already some accounts on the profile");
6510            }
6511            return;
6512        }
6513        enforceCanManageProfileAndDeviceOwners();
6514        if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
6515            throw new IllegalStateException("Cannot set the profile owner on a user which is "
6516                    + "already set-up");
6517        }
6518    }
6519
6520    /**
6521     * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6522     * permission.
6523     */
6524    private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId) {
6525        if (!isAdb()) {
6526            enforceCanManageProfileAndDeviceOwners();
6527        }
6528
6529        final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb());
6530        switch (code) {
6531            case CODE_OK:
6532                return;
6533            case CODE_HAS_DEVICE_OWNER:
6534                throw new IllegalStateException(
6535                        "Trying to set the device owner, but device owner is already set.");
6536            case CODE_USER_HAS_PROFILE_OWNER:
6537                throw new IllegalStateException("Trying to set the device owner, but the user "
6538                        + "already has a profile owner.");
6539            case CODE_USER_NOT_RUNNING:
6540                throw new IllegalStateException("User not running: " + userId);
6541            case CODE_NOT_SYSTEM_USER:
6542                throw new IllegalStateException("User is not system user");
6543            case CODE_USER_SETUP_COMPLETED:
6544                throw new IllegalStateException(
6545                        "Cannot set the device owner if the device is already set-up");
6546            case CODE_NONSYSTEM_USER_EXISTS:
6547                throw new IllegalStateException("Not allowed to set the device owner because there "
6548                        + "are already several users on the device");
6549            case CODE_ACCOUNTS_NOT_EMPTY:
6550                throw new IllegalStateException("Not allowed to set the device owner because there "
6551                        + "are already some accounts on the device");
6552            case CODE_HAS_PAIRED:
6553                throw new IllegalStateException("Not allowed to set the device owner because this "
6554                        + "device has already paired");
6555            default:
6556                throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6557        }
6558    }
6559
6560    private void enforceUserUnlocked(int userId) {
6561        // Since we're doing this operation on behalf of an app, we only
6562        // want to use the actual "unlocked" state.
6563        Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6564                "User must be running and unlocked");
6565    }
6566
6567    private void enforceManageUsers() {
6568        final int callingUid = mInjector.binderGetCallingUid();
6569        if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6570            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6571        }
6572    }
6573
6574    private void enforceFullCrossUsersPermission(int userHandle) {
6575        enforceSystemUserOrPermission(userHandle,
6576                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6577    }
6578
6579    private void enforceCrossUsersPermission(int userHandle) {
6580        enforceSystemUserOrPermission(userHandle,
6581                android.Manifest.permission.INTERACT_ACROSS_USERS);
6582    }
6583
6584    private void enforceSystemUserOrPermission(int userHandle, String permission) {
6585        if (userHandle < 0) {
6586            throw new IllegalArgumentException("Invalid userId " + userHandle);
6587        }
6588        final int callingUid = mInjector.binderGetCallingUid();
6589        if (userHandle == UserHandle.getUserId(callingUid)) {
6590            return;
6591        }
6592        if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6593            mContext.enforceCallingOrSelfPermission(permission,
6594                    "Must be system or have " + permission + " permission");
6595        }
6596    }
6597
6598    private void enforceManagedProfile(int userHandle, String message) {
6599        if(!isManagedProfile(userHandle)) {
6600            throw new SecurityException("You can not " + message + " outside a managed profile.");
6601        }
6602    }
6603
6604    private void enforceNotManagedProfile(int userHandle, String message) {
6605        if(isManagedProfile(userHandle)) {
6606            throw new SecurityException("You can not " + message + " for a managed profile.");
6607        }
6608    }
6609
6610    private void enforceDeviceOwnerOrManageUsers() {
6611        synchronized (this) {
6612            if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
6613                    mInjector.binderGetCallingUid()) != null) {
6614                return;
6615            }
6616        }
6617        enforceManageUsers();
6618    }
6619
6620    private void ensureCallerPackage(@Nullable String packageName) {
6621        if (packageName == null) {
6622            Preconditions.checkState(isCallerWithSystemUid(),
6623                    "Only caller can omit package name");
6624        } else {
6625            final int callingUid = mInjector.binderGetCallingUid();
6626            final int userId = mInjector.userHandleGetCallingUserId();
6627            try {
6628                final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6629                        packageName, 0, userId);
6630                Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6631            } catch (RemoteException e) {
6632                // Shouldn't happen
6633            }
6634        }
6635    }
6636
6637    private boolean isCallerWithSystemUid() {
6638        return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6639    }
6640
6641    private int getProfileParentId(int userHandle) {
6642        final long ident = mInjector.binderClearCallingIdentity();
6643        try {
6644            UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6645            return parentUser != null ? parentUser.id : userHandle;
6646        } finally {
6647            mInjector.binderRestoreCallingIdentity(ident);
6648        }
6649    }
6650
6651    private int getCredentialOwner(int userHandle, boolean parent) {
6652        final long ident = mInjector.binderClearCallingIdentity();
6653        try {
6654            if (parent) {
6655                UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6656                if (parentProfile != null) {
6657                    userHandle = parentProfile.id;
6658                }
6659            }
6660            return mUserManager.getCredentialOwnerProfile(userHandle);
6661        } finally {
6662            mInjector.binderRestoreCallingIdentity(ident);
6663        }
6664    }
6665
6666    private boolean isManagedProfile(int userHandle) {
6667        final UserInfo user = getUserInfo(userHandle);
6668        return user != null && user.isManagedProfile();
6669    }
6670
6671    private void enableIfNecessary(String packageName, int userId) {
6672        try {
6673            ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6674                    PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6675                    userId);
6676            if (ai.enabledSetting
6677                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6678                mIPackageManager.setApplicationEnabledSetting(packageName,
6679                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6680                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6681            }
6682        } catch (RemoteException e) {
6683        }
6684    }
6685
6686    @Override
6687    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6688        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6689                != PackageManager.PERMISSION_GRANTED) {
6690
6691            pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6692                    + mInjector.binderGetCallingPid()
6693                    + ", uid=" + mInjector.binderGetCallingUid());
6694            return;
6695        }
6696
6697        synchronized (this) {
6698            pw.println("Current Device Policy Manager state:");
6699            mOwners.dump("  ", pw);
6700            int userCount = mUserData.size();
6701            for (int u = 0; u < userCount; u++) {
6702                DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6703                pw.println();
6704                pw.println("  Enabled Device Admins (User " + policy.mUserHandle
6705                        + ", provisioningState: " + policy.mUserProvisioningState + "):");
6706                final int N = policy.mAdminList.size();
6707                for (int i=0; i<N; i++) {
6708                    ActiveAdmin ap = policy.mAdminList.get(i);
6709                    if (ap != null) {
6710                        pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
6711                                pw.println(":");
6712                        ap.dump("      ", pw);
6713                    }
6714                }
6715                if (!policy.mRemovingAdmins.isEmpty()) {
6716                    pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
6717                            + policy.mRemovingAdmins);
6718                }
6719
6720                pw.println(" ");
6721                pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
6722            }
6723            pw.println();
6724            pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6725        }
6726    }
6727
6728    private String getEncryptionStatusName(int encryptionStatus) {
6729        switch (encryptionStatus) {
6730            case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6731                return "inactive";
6732            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6733                return "block default key";
6734            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6735                return "block";
6736            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6737                return "per-user";
6738            case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6739                return "unsupported";
6740            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6741                return "activating";
6742            default:
6743                return "unknown";
6744        }
6745    }
6746
6747    @Override
6748    public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6749            ComponentName activity) {
6750        Preconditions.checkNotNull(who, "ComponentName is null");
6751        final int userHandle = UserHandle.getCallingUserId();
6752        synchronized (this) {
6753            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6754
6755            long id = mInjector.binderClearCallingIdentity();
6756            try {
6757                mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6758            } catch (RemoteException re) {
6759                // Shouldn't happen
6760            } finally {
6761                mInjector.binderRestoreCallingIdentity(id);
6762            }
6763        }
6764    }
6765
6766    @Override
6767    public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6768        Preconditions.checkNotNull(who, "ComponentName is null");
6769        final int userHandle = UserHandle.getCallingUserId();
6770        synchronized (this) {
6771            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6772
6773            long id = mInjector.binderClearCallingIdentity();
6774            try {
6775                mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6776            } catch (RemoteException re) {
6777                // Shouldn't happen
6778            } finally {
6779                mInjector.binderRestoreCallingIdentity(id);
6780            }
6781        }
6782    }
6783
6784    @Override
6785    public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6786            String packageName) {
6787        Preconditions.checkNotNull(admin, "ComponentName is null");
6788
6789        final int userHandle = mInjector.userHandleGetCallingUserId();
6790        synchronized (this) {
6791            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6792            if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6793                return false;
6794            }
6795            DevicePolicyData policy = getUserData(userHandle);
6796            policy.mApplicationRestrictionsManagingPackage = packageName;
6797            saveSettingsLocked(userHandle);
6798            return true;
6799        }
6800    }
6801
6802    @Override
6803    public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6804        Preconditions.checkNotNull(admin, "ComponentName is null");
6805
6806        final int userHandle = mInjector.userHandleGetCallingUserId();
6807        synchronized (this) {
6808            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6809            DevicePolicyData policy = getUserData(userHandle);
6810            return policy.mApplicationRestrictionsManagingPackage;
6811        }
6812    }
6813
6814    @Override
6815    public boolean isCallerApplicationRestrictionsManagingPackage() {
6816        final int callingUid = mInjector.binderGetCallingUid();
6817        final int userHandle = UserHandle.getUserId(callingUid);
6818        synchronized (this) {
6819            final DevicePolicyData policy = getUserData(userHandle);
6820            if (policy.mApplicationRestrictionsManagingPackage == null) {
6821                return false;
6822            }
6823
6824            try {
6825                int uid = mContext.getPackageManager().getPackageUidAsUser(
6826                        policy.mApplicationRestrictionsManagingPackage, userHandle);
6827                return uid == callingUid;
6828            } catch (NameNotFoundException e) {
6829                return false;
6830            }
6831        }
6832    }
6833
6834    private void enforceCanManageApplicationRestrictions(ComponentName who) {
6835        if (who != null) {
6836            synchronized (this) {
6837                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6838            }
6839        } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6840            throw new SecurityException(
6841                    "No admin component given, and caller cannot manage application restrictions "
6842                    + "for other apps.");
6843        }
6844    }
6845
6846    @Override
6847    public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6848        enforceCanManageApplicationRestrictions(who);
6849
6850        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6851        final long id = mInjector.binderClearCallingIdentity();
6852        try {
6853            mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6854        } finally {
6855            mInjector.binderRestoreCallingIdentity(id);
6856        }
6857    }
6858
6859    @Override
6860    public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6861            PersistableBundle args, boolean parent) {
6862        if (!mHasFeature) {
6863            return;
6864        }
6865        Preconditions.checkNotNull(admin, "admin is null");
6866        Preconditions.checkNotNull(agent, "agent is null");
6867        final int userHandle = UserHandle.getCallingUserId();
6868        synchronized (this) {
6869            ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6870                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6871            ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6872            saveSettingsLocked(userHandle);
6873        }
6874    }
6875
6876    @Override
6877    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6878            ComponentName agent, int userHandle, boolean parent) {
6879        if (!mHasFeature) {
6880            return null;
6881        }
6882        Preconditions.checkNotNull(agent, "agent null");
6883        enforceFullCrossUsersPermission(userHandle);
6884
6885        synchronized (this) {
6886            final String componentName = agent.flattenToString();
6887            if (admin != null) {
6888                final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6889                if (ap == null) return null;
6890                TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6891                if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6892                List<PersistableBundle> result = new ArrayList<>();
6893                result.add(trustAgentInfo.options);
6894                return result;
6895            }
6896
6897            // Return strictest policy for this user and profiles that are visible from this user.
6898            List<PersistableBundle> result = null;
6899            // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6900            // of the options. If any admin doesn't have options, discard options for the rest
6901            // and return null.
6902            List<ActiveAdmin> admins =
6903                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6904            boolean allAdminsHaveOptions = true;
6905            final int N = admins.size();
6906            for (int i = 0; i < N; i++) {
6907                final ActiveAdmin active = admins.get(i);
6908
6909                final boolean disablesTrust = (active.disabledKeyguardFeatures
6910                        & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6911                final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6912                if (info != null && info.options != null && !info.options.isEmpty()) {
6913                    if (disablesTrust) {
6914                        if (result == null) {
6915                            result = new ArrayList<>();
6916                        }
6917                        result.add(info.options);
6918                    } else {
6919                        Log.w(LOG_TAG, "Ignoring admin " + active.info
6920                                + " because it has trust options but doesn't declare "
6921                                + "KEYGUARD_DISABLE_TRUST_AGENTS");
6922                    }
6923                } else if (disablesTrust) {
6924                    allAdminsHaveOptions = false;
6925                    break;
6926                }
6927            }
6928            return allAdminsHaveOptions ? result : null;
6929        }
6930    }
6931
6932    @Override
6933    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6934        Preconditions.checkNotNull(who, "ComponentName is null");
6935        synchronized (this) {
6936            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6937
6938            int userHandle = UserHandle.getCallingUserId();
6939            DevicePolicyData userData = getUserData(userHandle);
6940            userData.mRestrictionsProvider = permissionProvider;
6941            saveSettingsLocked(userHandle);
6942        }
6943    }
6944
6945    @Override
6946    public ComponentName getRestrictionsProvider(int userHandle) {
6947        synchronized (this) {
6948            if (!isCallerWithSystemUid()) {
6949                throw new SecurityException("Only the system can query the permission provider");
6950            }
6951            DevicePolicyData userData = getUserData(userHandle);
6952            return userData != null ? userData.mRestrictionsProvider : null;
6953        }
6954    }
6955
6956    @Override
6957    public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6958        Preconditions.checkNotNull(who, "ComponentName is null");
6959        int callingUserId = UserHandle.getCallingUserId();
6960        synchronized (this) {
6961            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6962
6963            long id = mInjector.binderClearCallingIdentity();
6964            try {
6965                UserInfo parent = mUserManager.getProfileParent(callingUserId);
6966                if (parent == null) {
6967                    Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6968                            + "parent");
6969                    return;
6970                }
6971                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6972                    mIPackageManager.addCrossProfileIntentFilter(
6973                            filter, who.getPackageName(), callingUserId, parent.id, 0);
6974                }
6975                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6976                    mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6977                            parent.id, callingUserId, 0);
6978                }
6979            } catch (RemoteException re) {
6980                // Shouldn't happen
6981            } finally {
6982                mInjector.binderRestoreCallingIdentity(id);
6983            }
6984        }
6985    }
6986
6987    @Override
6988    public void clearCrossProfileIntentFilters(ComponentName who) {
6989        Preconditions.checkNotNull(who, "ComponentName is null");
6990        int callingUserId = UserHandle.getCallingUserId();
6991        synchronized (this) {
6992            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6993            long id = mInjector.binderClearCallingIdentity();
6994            try {
6995                UserInfo parent = mUserManager.getProfileParent(callingUserId);
6996                if (parent == null) {
6997                    Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6998                            + "parent");
6999                    return;
7000                }
7001                // Removing those that go from the managed profile to the parent.
7002                mIPackageManager.clearCrossProfileIntentFilters(
7003                        callingUserId, who.getPackageName());
7004                // And those that go from the parent to the managed profile.
7005                // If we want to support multiple managed profiles, we will have to only remove
7006                // those that have callingUserId as their target.
7007                mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
7008            } catch (RemoteException re) {
7009                // Shouldn't happen
7010            } finally {
7011                mInjector.binderRestoreCallingIdentity(id);
7012            }
7013        }
7014    }
7015
7016    /**
7017     * @return true if all packages in enabledPackages are either in the list
7018     * permittedList or are a system app.
7019     */
7020    private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
7021            List<String> permittedList, int userIdToCheck) {
7022        long id = mInjector.binderClearCallingIdentity();
7023        try {
7024            // If we have an enabled packages list for a managed profile the packages
7025            // we should check are installed for the parent user.
7026            UserInfo user = getUserInfo(userIdToCheck);
7027            if (user.isManagedProfile()) {
7028                userIdToCheck = user.profileGroupId;
7029            }
7030
7031            for (String enabledPackage : enabledPackages) {
7032                boolean systemService = false;
7033                try {
7034                    ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7035                            enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
7036                    systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7037                } catch (RemoteException e) {
7038                    Log.i(LOG_TAG, "Can't talk to package managed", e);
7039                }
7040                if (!systemService && !permittedList.contains(enabledPackage)) {
7041                    return false;
7042                }
7043            }
7044        } finally {
7045            mInjector.binderRestoreCallingIdentity(id);
7046        }
7047        return true;
7048    }
7049
7050    private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7051        // Not using AccessibilityManager.getInstance because that guesses
7052        // at the user you require based on callingUid and caches for a given
7053        // process.
7054        IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7055        IAccessibilityManager service = iBinder == null
7056                ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7057        return new AccessibilityManager(mContext, service, userId);
7058    }
7059
7060    @Override
7061    public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7062        if (!mHasFeature) {
7063            return false;
7064        }
7065        Preconditions.checkNotNull(who, "ComponentName is null");
7066
7067        if (packageList != null) {
7068            int userId = UserHandle.getCallingUserId();
7069            List<AccessibilityServiceInfo> enabledServices = null;
7070            long id = mInjector.binderClearCallingIdentity();
7071            try {
7072                UserInfo user = getUserInfo(userId);
7073                if (user.isManagedProfile()) {
7074                    userId = user.profileGroupId;
7075                }
7076                AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7077                enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7078                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7079            } finally {
7080                mInjector.binderRestoreCallingIdentity(id);
7081            }
7082
7083            if (enabledServices != null) {
7084                List<String> enabledPackages = new ArrayList<String>();
7085                for (AccessibilityServiceInfo service : enabledServices) {
7086                    enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7087                }
7088                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7089                        userId)) {
7090                    Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7091                            + "because it contains already enabled accesibility services.");
7092                    return false;
7093                }
7094            }
7095        }
7096
7097        synchronized (this) {
7098            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7099                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7100            admin.permittedAccessiblityServices = packageList;
7101            saveSettingsLocked(UserHandle.getCallingUserId());
7102        }
7103        return true;
7104    }
7105
7106    @Override
7107    public List getPermittedAccessibilityServices(ComponentName who) {
7108        if (!mHasFeature) {
7109            return null;
7110        }
7111        Preconditions.checkNotNull(who, "ComponentName is null");
7112
7113        synchronized (this) {
7114            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7115                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7116            return admin.permittedAccessiblityServices;
7117        }
7118    }
7119
7120    @Override
7121    public List getPermittedAccessibilityServicesForUser(int userId) {
7122        if (!mHasFeature) {
7123            return null;
7124        }
7125        synchronized (this) {
7126            List<String> result = null;
7127            // If we have multiple profiles we return the intersection of the
7128            // permitted lists. This can happen in cases where we have a device
7129            // and profile owner.
7130            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7131            for (int profileId : profileIds) {
7132                // Just loop though all admins, only device or profiles
7133                // owners can have permitted lists set.
7134                DevicePolicyData policy = getUserDataUnchecked(profileId);
7135                final int N = policy.mAdminList.size();
7136                for (int j = 0; j < N; j++) {
7137                    ActiveAdmin admin = policy.mAdminList.get(j);
7138                    List<String> fromAdmin = admin.permittedAccessiblityServices;
7139                    if (fromAdmin != null) {
7140                        if (result == null) {
7141                            result = new ArrayList<>(fromAdmin);
7142                        } else {
7143                            result.retainAll(fromAdmin);
7144                        }
7145                    }
7146                }
7147            }
7148
7149            // If we have a permitted list add all system accessibility services.
7150            if (result != null) {
7151                long id = mInjector.binderClearCallingIdentity();
7152                try {
7153                    UserInfo user = getUserInfo(userId);
7154                    if (user.isManagedProfile()) {
7155                        userId = user.profileGroupId;
7156                    }
7157                    AccessibilityManager accessibilityManager =
7158                            getAccessibilityManagerForUser(userId);
7159                    List<AccessibilityServiceInfo> installedServices =
7160                            accessibilityManager.getInstalledAccessibilityServiceList();
7161
7162                    if (installedServices != null) {
7163                        for (AccessibilityServiceInfo service : installedServices) {
7164                            ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7165                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7166                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7167                                result.add(serviceInfo.packageName);
7168                            }
7169                        }
7170                    }
7171                } finally {
7172                    mInjector.binderRestoreCallingIdentity(id);
7173                }
7174            }
7175
7176            return result;
7177        }
7178    }
7179
7180    @Override
7181    public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7182            int userHandle) {
7183        if (!mHasFeature) {
7184            return true;
7185        }
7186        Preconditions.checkNotNull(who, "ComponentName is null");
7187        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7188        if (!isCallerWithSystemUid()){
7189            throw new SecurityException(
7190                    "Only the system can query if an accessibility service is disabled by admin");
7191        }
7192        synchronized (this) {
7193            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7194            if (admin == null) {
7195                return false;
7196            }
7197            if (admin.permittedAccessiblityServices == null) {
7198                return true;
7199            }
7200            return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7201                    admin.permittedAccessiblityServices, userHandle);
7202        }
7203    }
7204
7205    private boolean checkCallerIsCurrentUserOrProfile() {
7206        int callingUserId = UserHandle.getCallingUserId();
7207        long token = mInjector.binderClearCallingIdentity();
7208        try {
7209            UserInfo currentUser;
7210            UserInfo callingUser = getUserInfo(callingUserId);
7211            try {
7212                currentUser = mInjector.getIActivityManager().getCurrentUser();
7213            } catch (RemoteException e) {
7214                Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7215                return false;
7216            }
7217
7218            if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7219                Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7220                        + "of a user that isn't the foreground user.");
7221                return false;
7222            }
7223            if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7224                Slog.e(LOG_TAG, "Cannot set permitted input methods "
7225                        + "of a user that isn't the foreground user.");
7226                return false;
7227            }
7228        } finally {
7229            mInjector.binderRestoreCallingIdentity(token);
7230        }
7231        return true;
7232    }
7233
7234    @Override
7235    public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7236        if (!mHasFeature) {
7237            return false;
7238        }
7239        Preconditions.checkNotNull(who, "ComponentName is null");
7240
7241        // TODO When InputMethodManager supports per user calls remove
7242        //      this restriction.
7243        if (!checkCallerIsCurrentUserOrProfile()) {
7244            return false;
7245        }
7246
7247        if (packageList != null) {
7248            // InputMethodManager fetches input methods for current user.
7249            // So this can only be set when calling user is the current user
7250            // or parent is current user in case of managed profiles.
7251            InputMethodManager inputMethodManager =
7252                    mContext.getSystemService(InputMethodManager.class);
7253            List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7254
7255            if (enabledImes != null) {
7256                List<String> enabledPackages = new ArrayList<String>();
7257                for (InputMethodInfo ime : enabledImes) {
7258                    enabledPackages.add(ime.getPackageName());
7259                }
7260                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7261                        mInjector.binderGetCallingUserHandle().getIdentifier())) {
7262                    Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7263                            + "because it contains already enabled input method.");
7264                    return false;
7265                }
7266            }
7267        }
7268
7269        synchronized (this) {
7270            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7271                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7272            admin.permittedInputMethods = packageList;
7273            saveSettingsLocked(UserHandle.getCallingUserId());
7274        }
7275        return true;
7276    }
7277
7278    @Override
7279    public List getPermittedInputMethods(ComponentName who) {
7280        if (!mHasFeature) {
7281            return null;
7282        }
7283        Preconditions.checkNotNull(who, "ComponentName is null");
7284
7285        synchronized (this) {
7286            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7287                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7288            return admin.permittedInputMethods;
7289        }
7290    }
7291
7292    @Override
7293    public List getPermittedInputMethodsForCurrentUser() {
7294        UserInfo currentUser;
7295        try {
7296            currentUser = mInjector.getIActivityManager().getCurrentUser();
7297        } catch (RemoteException e) {
7298            Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7299            // Activity managed is dead, just allow all IMEs
7300            return null;
7301        }
7302
7303        int userId = currentUser.id;
7304        synchronized (this) {
7305            List<String> result = null;
7306            // If we have multiple profiles we return the intersection of the
7307            // permitted lists. This can happen in cases where we have a device
7308            // and profile owner.
7309            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7310            for (int profileId : profileIds) {
7311                // Just loop though all admins, only device or profiles
7312                // owners can have permitted lists set.
7313                DevicePolicyData policy = getUserDataUnchecked(profileId);
7314                final int N = policy.mAdminList.size();
7315                for (int j = 0; j < N; j++) {
7316                    ActiveAdmin admin = policy.mAdminList.get(j);
7317                    List<String> fromAdmin = admin.permittedInputMethods;
7318                    if (fromAdmin != null) {
7319                        if (result == null) {
7320                            result = new ArrayList<String>(fromAdmin);
7321                        } else {
7322                            result.retainAll(fromAdmin);
7323                        }
7324                    }
7325                }
7326            }
7327
7328            // If we have a permitted list add all system input methods.
7329            if (result != null) {
7330                InputMethodManager inputMethodManager =
7331                        mContext.getSystemService(InputMethodManager.class);
7332                List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7333                long id = mInjector.binderClearCallingIdentity();
7334                try {
7335                    if (imes != null) {
7336                        for (InputMethodInfo ime : imes) {
7337                            ServiceInfo serviceInfo = ime.getServiceInfo();
7338                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7339                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7340                                result.add(serviceInfo.packageName);
7341                            }
7342                        }
7343                    }
7344                } finally {
7345                    mInjector.binderRestoreCallingIdentity(id);
7346                }
7347            }
7348            return result;
7349        }
7350    }
7351
7352    @Override
7353    public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7354            int userHandle) {
7355        if (!mHasFeature) {
7356            return true;
7357        }
7358        Preconditions.checkNotNull(who, "ComponentName is null");
7359        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7360        if (!isCallerWithSystemUid()) {
7361            throw new SecurityException(
7362                    "Only the system can query if an input method is disabled by admin");
7363        }
7364        synchronized (this) {
7365            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7366            if (admin == null) {
7367                return false;
7368            }
7369            if (admin.permittedInputMethods == null) {
7370                return true;
7371            }
7372            return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7373                    admin.permittedInputMethods, userHandle);
7374        }
7375    }
7376
7377    private void sendAdminEnabledBroadcastLocked(int userHandle) {
7378        DevicePolicyData policyData = getUserData(userHandle);
7379        if (policyData.mAdminBroadcastPending) {
7380            // Send the initialization data to profile owner and delete the data
7381            ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7382            if (admin != null) {
7383                PersistableBundle initBundle = policyData.mInitBundle;
7384                sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7385                        initBundle == null ? null : new Bundle(initBundle), null);
7386            }
7387            policyData.mInitBundle = null;
7388            policyData.mAdminBroadcastPending = false;
7389            saveSettingsLocked(userHandle);
7390        }
7391    }
7392
7393    @Override
7394    public UserHandle createAndManageUser(ComponentName admin, String name,
7395            ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7396        Preconditions.checkNotNull(admin, "admin is null");
7397        Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7398        if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7399            throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7400                    + admin + " are not in the same package");
7401        }
7402        // Only allow the system user to use this method
7403        if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7404            throw new SecurityException("createAndManageUser was called from non-system user");
7405        }
7406        if (!mInjector.userManagerIsSplitSystemUser()
7407                && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7408            throw new IllegalArgumentException(
7409                    "Ephemeral users are only supported on systems with a split system user.");
7410        }
7411        // Create user.
7412        UserHandle user = null;
7413        synchronized (this) {
7414            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7415
7416            final long id = mInjector.binderClearCallingIdentity();
7417            try {
7418                int userInfoFlags = 0;
7419                if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7420                    userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7421                }
7422                UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7423                        userInfoFlags);
7424                if (userInfo != null) {
7425                    user = userInfo.getUserHandle();
7426                }
7427            } finally {
7428                mInjector.binderRestoreCallingIdentity(id);
7429            }
7430        }
7431        if (user == null) {
7432            return null;
7433        }
7434        // Set admin.
7435        final long id = mInjector.binderClearCallingIdentity();
7436        try {
7437            final String adminPkg = admin.getPackageName();
7438
7439            final int userHandle = user.getIdentifier();
7440            try {
7441                // Install the profile owner if not present.
7442                if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7443                    mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7444                }
7445            } catch (RemoteException e) {
7446                Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7447                        + "removing created user", e);
7448                mUserManager.removeUser(user.getIdentifier());
7449                return null;
7450            }
7451
7452            setActiveAdmin(profileOwner, true, userHandle);
7453            // User is not started yet, the broadcast by setActiveAdmin will not be received.
7454            // So we store adminExtras for broadcasting when the user starts for first time.
7455            synchronized(this) {
7456                DevicePolicyData policyData = getUserData(userHandle);
7457                policyData.mInitBundle = adminExtras;
7458                policyData.mAdminBroadcastPending = true;
7459                saveSettingsLocked(userHandle);
7460            }
7461            final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7462            setProfileOwner(profileOwner, ownerName, userHandle);
7463
7464            if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7465                Settings.Secure.putIntForUser(mContext.getContentResolver(),
7466                        Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7467            }
7468
7469            return user;
7470        } finally {
7471            mInjector.binderRestoreCallingIdentity(id);
7472        }
7473    }
7474
7475    @Override
7476    public boolean removeUser(ComponentName who, UserHandle userHandle) {
7477        Preconditions.checkNotNull(who, "ComponentName is null");
7478        UserHandle callingUserHandle = mInjector.binderGetCallingUserHandle();
7479        synchronized (this) {
7480            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7481        }
7482        final long id = mInjector.binderClearCallingIdentity();
7483        try {
7484            int restrictionSource = mUserManager.getUserRestrictionSource(
7485                    UserManager.DISALLOW_REMOVE_USER, callingUserHandle);
7486            if (restrictionSource != UserManager.RESTRICTION_NOT_SET
7487                    && restrictionSource != UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) {
7488                Log.w(LOG_TAG, "The device owner cannot remove a user because "
7489                        + "DISALLOW_REMOVE_USER is enabled, and was not set by the device "
7490                        + "owner");
7491                return false;
7492            }
7493            return mUserManagerInternal.removeUserEvenWhenDisallowed(
7494                    userHandle.getIdentifier());
7495        } finally {
7496            mInjector.binderRestoreCallingIdentity(id);
7497        }
7498    }
7499
7500    @Override
7501    public boolean switchUser(ComponentName who, UserHandle userHandle) {
7502        Preconditions.checkNotNull(who, "ComponentName is null");
7503        synchronized (this) {
7504            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7505
7506            long id = mInjector.binderClearCallingIdentity();
7507            try {
7508                int userId = UserHandle.USER_SYSTEM;
7509                if (userHandle != null) {
7510                    userId = userHandle.getIdentifier();
7511                }
7512                return mInjector.getIActivityManager().switchUser(userId);
7513            } catch (RemoteException e) {
7514                Log.e(LOG_TAG, "Couldn't switch user", e);
7515                return false;
7516            } finally {
7517                mInjector.binderRestoreCallingIdentity(id);
7518            }
7519        }
7520    }
7521
7522    @Override
7523    public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7524        enforceCanManageApplicationRestrictions(who);
7525
7526        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7527        final long id = mInjector.binderClearCallingIdentity();
7528        try {
7529           Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7530           // if no restrictions were saved, mUserManager.getApplicationRestrictions
7531           // returns null, but DPM method should return an empty Bundle as per JavaDoc
7532           return bundle != null ? bundle : Bundle.EMPTY;
7533        } finally {
7534            mInjector.binderRestoreCallingIdentity(id);
7535        }
7536    }
7537
7538    @Override
7539    public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7540            boolean suspended) {
7541        Preconditions.checkNotNull(who, "ComponentName is null");
7542        int callingUserId = UserHandle.getCallingUserId();
7543        synchronized (this) {
7544            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7545
7546            long id = mInjector.binderClearCallingIdentity();
7547            try {
7548                return mIPackageManager.setPackagesSuspendedAsUser(
7549                        packageNames, suspended, callingUserId);
7550            } catch (RemoteException re) {
7551                // Shouldn't happen.
7552                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7553            } finally {
7554                mInjector.binderRestoreCallingIdentity(id);
7555            }
7556            return packageNames;
7557        }
7558    }
7559
7560    @Override
7561    public boolean isPackageSuspended(ComponentName who, String packageName) {
7562        Preconditions.checkNotNull(who, "ComponentName is null");
7563        int callingUserId = UserHandle.getCallingUserId();
7564        synchronized (this) {
7565            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7566
7567            long id = mInjector.binderClearCallingIdentity();
7568            try {
7569                return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7570            } catch (RemoteException re) {
7571                // Shouldn't happen.
7572                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7573            } finally {
7574                mInjector.binderRestoreCallingIdentity(id);
7575            }
7576            return false;
7577        }
7578    }
7579
7580    @Override
7581    public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7582        Preconditions.checkNotNull(who, "ComponentName is null");
7583        if (!UserRestrictionsUtils.isValidRestriction(key)) {
7584            return;
7585        }
7586
7587        final int userHandle = mInjector.userHandleGetCallingUserId();
7588        synchronized (this) {
7589            ActiveAdmin activeAdmin =
7590                    getActiveAdminForCallerLocked(who,
7591                            DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7592            final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7593            if (isDeviceOwner) {
7594                if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7595                    throw new SecurityException("Device owner cannot set user restriction " + key);
7596                }
7597            } else { // profile owner
7598                if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7599                    throw new SecurityException("Profile owner cannot set user restriction " + key);
7600                }
7601            }
7602
7603            // Save the restriction to ActiveAdmin.
7604            activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7605            saveSettingsLocked(userHandle);
7606
7607            pushUserRestrictions(userHandle);
7608
7609            sendChangedNotification(userHandle);
7610        }
7611    }
7612
7613    private void pushUserRestrictions(int userId) {
7614        synchronized (this) {
7615            final Bundle global;
7616            final Bundle local = new Bundle();
7617            if (mOwners.isDeviceOwnerUserId(userId)) {
7618                global = new Bundle();
7619
7620                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7621                if (deviceOwner == null) {
7622                    return; // Shouldn't happen.
7623                }
7624
7625                UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7626                        global, local);
7627                // DO can disable camera globally.
7628                if (deviceOwner.disableCamera) {
7629                    global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7630                }
7631            } else {
7632                global = null;
7633
7634                ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7635                if (profileOwner != null) {
7636                    UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7637                }
7638            }
7639            // Also merge in *local* camera restriction.
7640            if (getCameraDisabled(/* who= */ null,
7641                    userId, /* mergeDeviceOwnerRestriction= */ false)) {
7642                local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7643            }
7644            mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7645        }
7646    }
7647
7648    @Override
7649    public Bundle getUserRestrictions(ComponentName who) {
7650        if (!mHasFeature) {
7651            return null;
7652        }
7653        Preconditions.checkNotNull(who, "ComponentName is null");
7654        synchronized (this) {
7655            final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7656                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7657            return activeAdmin.userRestrictions;
7658        }
7659    }
7660
7661    @Override
7662    public boolean setApplicationHidden(ComponentName who, String packageName,
7663            boolean hidden) {
7664        Preconditions.checkNotNull(who, "ComponentName is null");
7665        int callingUserId = UserHandle.getCallingUserId();
7666        synchronized (this) {
7667            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7668
7669            long id = mInjector.binderClearCallingIdentity();
7670            try {
7671                return mIPackageManager.setApplicationHiddenSettingAsUser(
7672                        packageName, hidden, callingUserId);
7673            } catch (RemoteException re) {
7674                // shouldn't happen
7675                Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7676            } finally {
7677                mInjector.binderRestoreCallingIdentity(id);
7678            }
7679            return false;
7680        }
7681    }
7682
7683    @Override
7684    public boolean isApplicationHidden(ComponentName who, String packageName) {
7685        Preconditions.checkNotNull(who, "ComponentName is null");
7686        int callingUserId = UserHandle.getCallingUserId();
7687        synchronized (this) {
7688            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7689
7690            long id = mInjector.binderClearCallingIdentity();
7691            try {
7692                return mIPackageManager.getApplicationHiddenSettingAsUser(
7693                        packageName, callingUserId);
7694            } catch (RemoteException re) {
7695                // shouldn't happen
7696                Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7697            } finally {
7698                mInjector.binderRestoreCallingIdentity(id);
7699            }
7700            return false;
7701        }
7702    }
7703
7704    @Override
7705    public void enableSystemApp(ComponentName who, String packageName) {
7706        Preconditions.checkNotNull(who, "ComponentName is null");
7707        synchronized (this) {
7708            // This API can only be called by an active device admin,
7709            // so try to retrieve it to check that the caller is one.
7710            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7711
7712            int userId = UserHandle.getCallingUserId();
7713            long id = mInjector.binderClearCallingIdentity();
7714
7715            try {
7716                if (VERBOSE_LOG) {
7717                    Slog.v(LOG_TAG, "installing " + packageName + " for "
7718                            + userId);
7719                }
7720
7721                int parentUserId = getProfileParentId(userId);
7722                if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7723                    throw new IllegalArgumentException("Only system apps can be enabled this way.");
7724                }
7725
7726                // Install the app.
7727                mIPackageManager.installExistingPackageAsUser(packageName, userId);
7728
7729            } catch (RemoteException re) {
7730                // shouldn't happen
7731                Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7732            } finally {
7733                mInjector.binderRestoreCallingIdentity(id);
7734            }
7735        }
7736    }
7737
7738    @Override
7739    public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7740        Preconditions.checkNotNull(who, "ComponentName is null");
7741        synchronized (this) {
7742            // This API can only be called by an active device admin,
7743            // so try to retrieve it to check that the caller is one.
7744            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7745
7746            int userId = UserHandle.getCallingUserId();
7747            long id = mInjector.binderClearCallingIdentity();
7748
7749            try {
7750                int parentUserId = getProfileParentId(userId);
7751                List<ResolveInfo> activitiesToEnable = mIPackageManager
7752                        .queryIntentActivities(intent,
7753                                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7754                                PackageManager.MATCH_DIRECT_BOOT_AWARE
7755                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7756                                parentUserId)
7757                        .getList();
7758
7759                if (VERBOSE_LOG) {
7760                    Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7761                }
7762                int numberOfAppsInstalled = 0;
7763                if (activitiesToEnable != null) {
7764                    for (ResolveInfo info : activitiesToEnable) {
7765                        if (info.activityInfo != null) {
7766                            String packageName = info.activityInfo.packageName;
7767                            if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7768                                numberOfAppsInstalled++;
7769                                mIPackageManager.installExistingPackageAsUser(packageName, userId);
7770                            } else {
7771                                Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7772                                        + " system app");
7773                            }
7774                        }
7775                    }
7776                }
7777                return numberOfAppsInstalled;
7778            } catch (RemoteException e) {
7779                // shouldn't happen
7780                Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7781                return 0;
7782            } finally {
7783                mInjector.binderRestoreCallingIdentity(id);
7784            }
7785        }
7786    }
7787
7788    private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7789            throws RemoteException {
7790        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7791                userId);
7792        if (appInfo == null) {
7793            throw new IllegalArgumentException("The application " + packageName +
7794                    " is not present on this device");
7795        }
7796        return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7797    }
7798
7799    @Override
7800    public void setAccountManagementDisabled(ComponentName who, String accountType,
7801            boolean disabled) {
7802        if (!mHasFeature) {
7803            return;
7804        }
7805        Preconditions.checkNotNull(who, "ComponentName is null");
7806        synchronized (this) {
7807            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7808                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7809            if (disabled) {
7810                ap.accountTypesWithManagementDisabled.add(accountType);
7811            } else {
7812                ap.accountTypesWithManagementDisabled.remove(accountType);
7813            }
7814            saveSettingsLocked(UserHandle.getCallingUserId());
7815        }
7816    }
7817
7818    @Override
7819    public String[] getAccountTypesWithManagementDisabled() {
7820        return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7821    }
7822
7823    @Override
7824    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7825        enforceFullCrossUsersPermission(userId);
7826        if (!mHasFeature) {
7827            return null;
7828        }
7829        synchronized (this) {
7830            DevicePolicyData policy = getUserData(userId);
7831            final int N = policy.mAdminList.size();
7832            ArraySet<String> resultSet = new ArraySet<>();
7833            for (int i = 0; i < N; i++) {
7834                ActiveAdmin admin = policy.mAdminList.get(i);
7835                resultSet.addAll(admin.accountTypesWithManagementDisabled);
7836            }
7837            return resultSet.toArray(new String[resultSet.size()]);
7838        }
7839    }
7840
7841    @Override
7842    public void setUninstallBlocked(ComponentName who, String packageName,
7843            boolean uninstallBlocked) {
7844        Preconditions.checkNotNull(who, "ComponentName is null");
7845        final int userId = UserHandle.getCallingUserId();
7846        synchronized (this) {
7847            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7848
7849            long id = mInjector.binderClearCallingIdentity();
7850            try {
7851                mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7852            } catch (RemoteException re) {
7853                // Shouldn't happen.
7854                Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7855            } finally {
7856                mInjector.binderRestoreCallingIdentity(id);
7857            }
7858        }
7859    }
7860
7861    @Override
7862    public boolean isUninstallBlocked(ComponentName who, String packageName) {
7863        // This function should return true if and only if the package is blocked by
7864        // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7865        // when the package is a system app, or when it is an active device admin.
7866        final int userId = UserHandle.getCallingUserId();
7867
7868        synchronized (this) {
7869            if (who != null) {
7870                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7871            }
7872
7873            long id = mInjector.binderClearCallingIdentity();
7874            try {
7875                return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7876            } catch (RemoteException re) {
7877                // Shouldn't happen.
7878                Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7879            } finally {
7880                mInjector.binderRestoreCallingIdentity(id);
7881            }
7882        }
7883        return false;
7884    }
7885
7886    @Override
7887    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7888        if (!mHasFeature) {
7889            return;
7890        }
7891        Preconditions.checkNotNull(who, "ComponentName is null");
7892        synchronized (this) {
7893            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7894                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7895            if (admin.disableCallerId != disabled) {
7896                admin.disableCallerId = disabled;
7897                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7898            }
7899        }
7900    }
7901
7902    @Override
7903    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7904        if (!mHasFeature) {
7905            return false;
7906        }
7907        Preconditions.checkNotNull(who, "ComponentName is null");
7908        synchronized (this) {
7909            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7910                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7911            return admin.disableCallerId;
7912        }
7913    }
7914
7915    @Override
7916    public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7917        enforceCrossUsersPermission(userId);
7918        synchronized (this) {
7919            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7920            return (admin != null) ? admin.disableCallerId : false;
7921        }
7922    }
7923
7924    @Override
7925    public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7926        if (!mHasFeature) {
7927            return;
7928        }
7929        Preconditions.checkNotNull(who, "ComponentName is null");
7930        synchronized (this) {
7931            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7932                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7933            if (admin.disableContactsSearch != disabled) {
7934                admin.disableContactsSearch = disabled;
7935                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7936            }
7937        }
7938    }
7939
7940    @Override
7941    public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7942        if (!mHasFeature) {
7943            return false;
7944        }
7945        Preconditions.checkNotNull(who, "ComponentName is null");
7946        synchronized (this) {
7947            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7948                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7949            return admin.disableContactsSearch;
7950        }
7951    }
7952
7953    @Override
7954    public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7955        enforceCrossUsersPermission(userId);
7956        synchronized (this) {
7957            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7958            return (admin != null) ? admin.disableContactsSearch : false;
7959        }
7960    }
7961
7962    @Override
7963    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7964            boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7965        final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7966                actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7967        final int callingUserId = UserHandle.getCallingUserId();
7968
7969        final long ident = mInjector.binderClearCallingIdentity();
7970        try {
7971            synchronized (this) {
7972                final int managedUserId = getManagedUserId(callingUserId);
7973                if (managedUserId < 0) {
7974                    return;
7975                }
7976                if (isCrossProfileQuickContactDisabled(managedUserId)) {
7977                    if (VERBOSE_LOG) {
7978                        Log.v(LOG_TAG,
7979                                "Cross-profile contacts access disabled for user " + managedUserId);
7980                    }
7981                    return;
7982                }
7983                ContactsInternal.startQuickContactWithErrorToastForUser(
7984                        mContext, intent, new UserHandle(managedUserId));
7985            }
7986        } finally {
7987            mInjector.binderRestoreCallingIdentity(ident);
7988        }
7989    }
7990
7991    /**
7992     * @return true if cross-profile QuickContact is disabled
7993     */
7994    private boolean isCrossProfileQuickContactDisabled(int userId) {
7995        return getCrossProfileCallerIdDisabledForUser(userId)
7996                && getCrossProfileContactsSearchDisabledForUser(userId);
7997    }
7998
7999    /**
8000     * @return the user ID of the managed user that is linked to the current user, if any.
8001     * Otherwise -1.
8002     */
8003    public int getManagedUserId(int callingUserId) {
8004        if (VERBOSE_LOG) {
8005            Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
8006        }
8007
8008        for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
8009            if (ui.id == callingUserId || !ui.isManagedProfile()) {
8010                continue; // Caller user self, or not a managed profile.  Skip.
8011            }
8012            if (VERBOSE_LOG) {
8013                Log.v(LOG_TAG, "Managed user=" + ui.id);
8014            }
8015            return ui.id;
8016        }
8017        if (VERBOSE_LOG) {
8018            Log.v(LOG_TAG, "Managed user not found.");
8019        }
8020        return -1;
8021    }
8022
8023    @Override
8024    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
8025        if (!mHasFeature) {
8026            return;
8027        }
8028        Preconditions.checkNotNull(who, "ComponentName is null");
8029        synchronized (this) {
8030            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8031                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8032            if (admin.disableBluetoothContactSharing != disabled) {
8033                admin.disableBluetoothContactSharing = disabled;
8034                saveSettingsLocked(UserHandle.getCallingUserId());
8035            }
8036        }
8037    }
8038
8039    @Override
8040    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
8041        if (!mHasFeature) {
8042            return false;
8043        }
8044        Preconditions.checkNotNull(who, "ComponentName is null");
8045        synchronized (this) {
8046            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8047                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8048            return admin.disableBluetoothContactSharing;
8049        }
8050    }
8051
8052    @Override
8053    public boolean getBluetoothContactSharingDisabledForUser(int userId) {
8054        // TODO: Should there be a check to make sure this relationship is
8055        // within a profile group?
8056        // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
8057        synchronized (this) {
8058            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8059            return (admin != null) ? admin.disableBluetoothContactSharing : false;
8060        }
8061    }
8062
8063    /**
8064     * Sets which packages may enter lock task mode.
8065     *
8066     * <p>This function can only be called by the device owner or alternatively by the profile owner
8067     * in case the user is affiliated.
8068     *
8069     * @param packages The list of packages allowed to enter lock task mode.
8070     */
8071    @Override
8072    public void setLockTaskPackages(ComponentName who, String[] packages)
8073            throws SecurityException {
8074        Preconditions.checkNotNull(who, "ComponentName is null");
8075
8076        synchronized (this) {
8077            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8078            final int userHandle = mInjector.userHandleGetCallingUserId();
8079            if (isUserAffiliatedWithDevice(userHandle)) {
8080                setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
8081            } else {
8082                throw new SecurityException("Admin " + who +
8083                    " is neither the device owner or affiliated user's profile owner.");
8084            }
8085        }
8086    }
8087
8088    private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
8089        DevicePolicyData policy = getUserData(userHandle);
8090        policy.mLockTaskPackages = packages;
8091
8092        // Store the settings persistently.
8093        saveSettingsLocked(userHandle);
8094        updateLockTaskPackagesLocked(packages, userHandle);
8095    }
8096
8097    /**
8098     * This function returns the list of components allowed to start the task lock mode.
8099     */
8100    @Override
8101    public String[] getLockTaskPackages(ComponentName who) {
8102        Preconditions.checkNotNull(who, "ComponentName is null");
8103        synchronized (this) {
8104            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8105            int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8106            final List<String> packages = getLockTaskPackagesLocked(userHandle);
8107            return packages.toArray(new String[packages.size()]);
8108        }
8109    }
8110
8111    private List<String> getLockTaskPackagesLocked(int userHandle) {
8112        final DevicePolicyData policy = getUserData(userHandle);
8113        return policy.mLockTaskPackages;
8114    }
8115
8116    /**
8117     * This function lets the caller know whether the given package is allowed to start the
8118     * lock task mode.
8119     * @param pkg The package to check
8120     */
8121    @Override
8122    public boolean isLockTaskPermitted(String pkg) {
8123        // Get current user's devicepolicy
8124        int uid = mInjector.binderGetCallingUid();
8125        int userHandle = UserHandle.getUserId(uid);
8126        DevicePolicyData policy = getUserData(userHandle);
8127        synchronized (this) {
8128            for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8129                String lockTaskPackage = policy.mLockTaskPackages.get(i);
8130
8131                // If the given package equals one of the packages stored our list,
8132                // we allow this package to start lock task mode.
8133                if (lockTaskPackage.equals(pkg)) {
8134                    return true;
8135                }
8136            }
8137        }
8138        return false;
8139    }
8140
8141    @Override
8142    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8143        if (!isCallerWithSystemUid()) {
8144            throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8145        }
8146        synchronized (this) {
8147            final DevicePolicyData policy = getUserData(userHandle);
8148            Bundle adminExtras = new Bundle();
8149            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8150            for (ActiveAdmin admin : policy.mAdminList) {
8151                final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8152                final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8153                if (ownsDevice || ownsProfile) {
8154                    if (isEnabled) {
8155                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8156                                adminExtras, null);
8157                    } else {
8158                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8159                    }
8160                }
8161            }
8162        }
8163    }
8164
8165    @Override
8166    public void setGlobalSetting(ComponentName who, String setting, String value) {
8167        Preconditions.checkNotNull(who, "ComponentName is null");
8168
8169        synchronized (this) {
8170            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8171
8172            // Some settings are no supported any more. However we do not want to throw a
8173            // SecurityException to avoid breaking apps.
8174            if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8175                Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8176                return;
8177            }
8178
8179            if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8180                throw new SecurityException(String.format(
8181                        "Permission denial: device owners cannot update %1$s", setting));
8182            }
8183
8184            if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8185                // ignore if it contradicts an existing policy
8186                long timeMs = getMaximumTimeToLock(
8187                        who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8188                if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8189                    return;
8190                }
8191            }
8192
8193            long id = mInjector.binderClearCallingIdentity();
8194            try {
8195                mInjector.settingsGlobalPutString(setting, value);
8196            } finally {
8197                mInjector.binderRestoreCallingIdentity(id);
8198            }
8199        }
8200    }
8201
8202    @Override
8203    public void setSecureSetting(ComponentName who, String setting, String value) {
8204        Preconditions.checkNotNull(who, "ComponentName is null");
8205        int callingUserId = mInjector.userHandleGetCallingUserId();
8206
8207        synchronized (this) {
8208            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8209
8210            if (isDeviceOwner(who, callingUserId)) {
8211                if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8212                    throw new SecurityException(String.format(
8213                            "Permission denial: Device owners cannot update %1$s", setting));
8214                }
8215            } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8216                throw new SecurityException(String.format(
8217                        "Permission denial: Profile owners cannot update %1$s", setting));
8218            }
8219
8220            long id = mInjector.binderClearCallingIdentity();
8221            try {
8222                mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8223            } finally {
8224                mInjector.binderRestoreCallingIdentity(id);
8225            }
8226        }
8227    }
8228
8229    @Override
8230    public void setMasterVolumeMuted(ComponentName who, boolean on) {
8231        Preconditions.checkNotNull(who, "ComponentName is null");
8232        synchronized (this) {
8233            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8234            setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8235        }
8236    }
8237
8238    @Override
8239    public boolean isMasterVolumeMuted(ComponentName who) {
8240        Preconditions.checkNotNull(who, "ComponentName is null");
8241        synchronized (this) {
8242            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8243
8244            AudioManager audioManager =
8245                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8246            return audioManager.isMasterMute();
8247        }
8248    }
8249
8250    @Override
8251    public void setUserIcon(ComponentName who, Bitmap icon) {
8252        synchronized (this) {
8253            Preconditions.checkNotNull(who, "ComponentName is null");
8254            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8255
8256            int userId = UserHandle.getCallingUserId();
8257            long id = mInjector.binderClearCallingIdentity();
8258            try {
8259                mUserManagerInternal.setUserIcon(userId, icon);
8260            } finally {
8261                mInjector.binderRestoreCallingIdentity(id);
8262            }
8263        }
8264    }
8265
8266    @Override
8267    public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8268        Preconditions.checkNotNull(who, "ComponentName is null");
8269        synchronized (this) {
8270            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8271        }
8272        final int userId = UserHandle.getCallingUserId();
8273
8274        long ident = mInjector.binderClearCallingIdentity();
8275        try {
8276            // disallow disabling the keyguard if a password is currently set
8277            if (disabled && mLockPatternUtils.isSecure(userId)) {
8278                return false;
8279            }
8280            mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8281        } finally {
8282            mInjector.binderRestoreCallingIdentity(ident);
8283        }
8284        return true;
8285    }
8286
8287    @Override
8288    public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8289        int userId = UserHandle.getCallingUserId();
8290        synchronized (this) {
8291            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8292            DevicePolicyData policy = getUserData(userId);
8293            if (policy.mStatusBarDisabled != disabled) {
8294                if (!setStatusBarDisabledInternal(disabled, userId)) {
8295                    return false;
8296                }
8297                policy.mStatusBarDisabled = disabled;
8298                saveSettingsLocked(userId);
8299            }
8300        }
8301        return true;
8302    }
8303
8304    private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8305        long ident = mInjector.binderClearCallingIdentity();
8306        try {
8307            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8308                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8309            if (statusBarService != null) {
8310                int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8311                int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8312                statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8313                statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8314                return true;
8315            }
8316        } catch (RemoteException e) {
8317            Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8318        } finally {
8319            mInjector.binderRestoreCallingIdentity(ident);
8320        }
8321        return false;
8322    }
8323
8324    /**
8325     * We need to update the internal state of whether a user has completed setup or a
8326     * device has paired once. After that, we ignore any changes that reset the
8327     * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
8328     * as we don't trust any apps that might try to reset them.
8329     * <p>
8330     * Unfortunately, we don't know which user's setup state was changed, so we write all of
8331     * them.
8332     */
8333    void updateUserSetupCompleteAndPaired() {
8334        List<UserInfo> users = mUserManager.getUsers(true);
8335        final int N = users.size();
8336        for (int i = 0; i < N; i++) {
8337            int userHandle = users.get(i).id;
8338            if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8339                    userHandle) != 0) {
8340                DevicePolicyData policy = getUserData(userHandle);
8341                if (!policy.mUserSetupComplete) {
8342                    policy.mUserSetupComplete = true;
8343                    synchronized (this) {
8344                        saveSettingsLocked(userHandle);
8345                    }
8346                }
8347            }
8348            if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
8349                    userHandle) != 0) {
8350                DevicePolicyData policy = getUserData(userHandle);
8351                if (!policy.mPaired) {
8352                    policy.mPaired = true;
8353                    synchronized (this) {
8354                        saveSettingsLocked(userHandle);
8355                    }
8356                }
8357            }
8358        }
8359    }
8360
8361    private class SetupContentObserver extends ContentObserver {
8362
8363        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8364                Settings.Secure.USER_SETUP_COMPLETE);
8365        private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8366                Settings.Global.DEVICE_PROVISIONED);
8367        private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
8368
8369        public SetupContentObserver(Handler handler) {
8370            super(handler);
8371        }
8372
8373        void register() {
8374            mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8375            mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8376            if (mIsWatch) {
8377                mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
8378            }
8379        }
8380
8381        @Override
8382        public void onChange(boolean selfChange, Uri uri) {
8383            if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
8384                updateUserSetupCompleteAndPaired();
8385            } else if (mDeviceProvisioned.equals(uri)) {
8386                synchronized (DevicePolicyManagerService.this) {
8387                    // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8388                    // is delayed until device is marked as provisioned.
8389                    setDeviceOwnerSystemPropertyLocked();
8390                }
8391            }
8392        }
8393    }
8394
8395    @VisibleForTesting
8396    final class LocalService extends DevicePolicyManagerInternal {
8397        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8398
8399        @Override
8400        public List<String> getCrossProfileWidgetProviders(int profileId) {
8401            synchronized (DevicePolicyManagerService.this) {
8402                if (mOwners == null) {
8403                    return Collections.emptyList();
8404                }
8405                ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8406                if (ownerComponent == null) {
8407                    return Collections.emptyList();
8408                }
8409
8410                DevicePolicyData policy = getUserDataUnchecked(profileId);
8411                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8412
8413                if (admin == null || admin.crossProfileWidgetProviders == null
8414                        || admin.crossProfileWidgetProviders.isEmpty()) {
8415                    return Collections.emptyList();
8416                }
8417
8418                return admin.crossProfileWidgetProviders;
8419            }
8420        }
8421
8422        @Override
8423        public void addOnCrossProfileWidgetProvidersChangeListener(
8424                OnCrossProfileWidgetProvidersChangeListener listener) {
8425            synchronized (DevicePolicyManagerService.this) {
8426                if (mWidgetProviderListeners == null) {
8427                    mWidgetProviderListeners = new ArrayList<>();
8428                }
8429                if (!mWidgetProviderListeners.contains(listener)) {
8430                    mWidgetProviderListeners.add(listener);
8431                }
8432            }
8433        }
8434
8435        @Override
8436        public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8437            synchronized(DevicePolicyManagerService.this) {
8438                return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8439            }
8440        }
8441
8442        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8443            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8444            synchronized (DevicePolicyManagerService.this) {
8445                listeners = new ArrayList<>(mWidgetProviderListeners);
8446            }
8447            final int listenerCount = listeners.size();
8448            for (int i = 0; i < listenerCount; i++) {
8449                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8450                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8451            }
8452        }
8453
8454        @Override
8455        public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
8456            // This method is called from AM with its lock held, so don't take the DPMS lock.
8457            // b/29242568
8458
8459            ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8460            if (profileOwner != null) {
8461                return createShowAdminSupportIntent(profileOwner, userId);
8462            }
8463
8464            final Pair<Integer, ComponentName> deviceOwner =
8465                    mOwners.getDeviceOwnerUserIdAndComponent();
8466            if (deviceOwner != null && deviceOwner.first == userId) {
8467                return createShowAdminSupportIntent(deviceOwner.second, userId);
8468            }
8469
8470            // We're not specifying the device admin because there isn't one.
8471            if (useDefaultIfNoAdmin) {
8472                return createShowAdminSupportIntent(null, userId);
8473            }
8474            return null;
8475        }
8476
8477        @Override
8478        public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
8479            int source;
8480            long ident = mInjector.binderClearCallingIdentity();
8481            try {
8482                source = mUserManager.getUserRestrictionSource(userRestriction,
8483                        UserHandle.of(userId));
8484            } finally {
8485                mInjector.binderRestoreCallingIdentity(ident);
8486            }
8487            if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
8488                /*
8489                 * In this case, the user restriction is enforced by the system.
8490                 * So we won't show an admin support intent, even if it is also
8491                 * enforced by a profile/device owner.
8492                 */
8493                return null;
8494            }
8495            boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
8496            boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
8497            if (enforcedByDo && enforcedByPo) {
8498                // In this case, we'll show an admin support dialog that does not
8499                // specify the admin.
8500                return createShowAdminSupportIntent(null, userId);
8501            } else if (enforcedByPo) {
8502                final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8503                if (profileOwner != null) {
8504                    return createShowAdminSupportIntent(profileOwner, userId);
8505                }
8506                // This could happen if another thread has changed the profile owner since we called
8507                // getUserRestrictionSource
8508                return null;
8509            } else if (enforcedByDo) {
8510                final Pair<Integer, ComponentName> deviceOwner
8511                        = mOwners.getDeviceOwnerUserIdAndComponent();
8512                if (deviceOwner != null) {
8513                    return createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
8514                }
8515                // This could happen if another thread has changed the device owner since we called
8516                // getUserRestrictionSource
8517                return null;
8518            }
8519            return null;
8520        }
8521
8522        private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
8523            // This method is called with AMS lock held, so don't take DPMS lock
8524            final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8525            intent.putExtra(Intent.EXTRA_USER_ID, userId);
8526            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
8527            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8528            return intent;
8529        }
8530    }
8531
8532    /**
8533     * Returns true if specified admin is allowed to limit passwords and has a
8534     * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
8535     */
8536    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8537        if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
8538            return false;
8539        }
8540        return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8541    }
8542
8543    @Override
8544    public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8545        if (policy != null && !policy.isValid()) {
8546            throw new IllegalArgumentException("Invalid system update policy.");
8547        }
8548        synchronized (this) {
8549            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8550            if (policy == null) {
8551                mOwners.clearSystemUpdatePolicy();
8552            } else {
8553                mOwners.setSystemUpdatePolicy(policy);
8554            }
8555            mOwners.writeDeviceOwner();
8556        }
8557        mContext.sendBroadcastAsUser(
8558                new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8559                UserHandle.SYSTEM);
8560    }
8561
8562    @Override
8563    public SystemUpdatePolicy getSystemUpdatePolicy() {
8564        if (UserManager.isDeviceInDemoMode(mContext)) {
8565            // Pretending to have an automatic update policy when the device is in retail demo
8566            // mode. This will allow the device to download and install an ota without
8567            // any user interaction.
8568            return SystemUpdatePolicy.createAutomaticInstallPolicy();
8569        }
8570        synchronized (this) {
8571            SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
8572            if (policy != null && !policy.isValid()) {
8573                Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8574                return null;
8575            }
8576            return policy;
8577        }
8578    }
8579
8580    /**
8581     * Checks if the caller of the method is the device owner app.
8582     *
8583     * @param callerUid UID of the caller.
8584     * @return true if the caller is the device owner app
8585     */
8586    @VisibleForTesting
8587    boolean isCallerDeviceOwner(int callerUid) {
8588        synchronized (this) {
8589            if (!mOwners.hasDeviceOwner()) {
8590                return false;
8591            }
8592            if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8593                return false;
8594            }
8595            final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8596                    .getPackageName();
8597            final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8598
8599            for (String pkg : pkgs) {
8600                if (deviceOwnerPackageName.equals(pkg)) {
8601                    return true;
8602                }
8603            }
8604        }
8605
8606        return false;
8607    }
8608
8609    @Override
8610    public void notifyPendingSystemUpdate(long updateReceivedTime) {
8611        mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8612                "Only the system update service can broadcast update information");
8613
8614        if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8615            Slog.w(LOG_TAG, "Only the system update service in the system user " +
8616                    "can broadcast update information.");
8617            return;
8618        }
8619        Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8620        intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8621                updateReceivedTime);
8622
8623        synchronized (this) {
8624            final String deviceOwnerPackage =
8625                    mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8626                            : null;
8627            if (deviceOwnerPackage == null) {
8628                return;
8629            }
8630            final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8631
8632            ActivityInfo[] receivers = null;
8633            try {
8634                receivers  = mContext.getPackageManager().getPackageInfo(
8635                        deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8636            } catch (NameNotFoundException e) {
8637                Log.e(LOG_TAG, "Cannot find device owner package", e);
8638            }
8639            if (receivers != null) {
8640                long ident = mInjector.binderClearCallingIdentity();
8641                try {
8642                    for (int i = 0; i < receivers.length; i++) {
8643                        if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8644                            intent.setComponent(new ComponentName(deviceOwnerPackage,
8645                                    receivers[i].name));
8646                            mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8647                        }
8648                    }
8649                } finally {
8650                    mInjector.binderRestoreCallingIdentity(ident);
8651                }
8652            }
8653        }
8654    }
8655
8656    @Override
8657    public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8658        int userId = UserHandle.getCallingUserId();
8659        synchronized (this) {
8660            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8661            DevicePolicyData userPolicy = getUserData(userId);
8662            if (userPolicy.mPermissionPolicy != policy) {
8663                userPolicy.mPermissionPolicy = policy;
8664                saveSettingsLocked(userId);
8665            }
8666        }
8667    }
8668
8669    @Override
8670    public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8671        int userId = UserHandle.getCallingUserId();
8672        synchronized (this) {
8673            DevicePolicyData userPolicy = getUserData(userId);
8674            return userPolicy.mPermissionPolicy;
8675        }
8676    }
8677
8678    @Override
8679    public boolean setPermissionGrantState(ComponentName admin, String packageName,
8680            String permission, int grantState) throws RemoteException {
8681        UserHandle user = mInjector.binderGetCallingUserHandle();
8682        synchronized (this) {
8683            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8684            long ident = mInjector.binderClearCallingIdentity();
8685            try {
8686                if (getTargetSdk(packageName, user.getIdentifier())
8687                        < android.os.Build.VERSION_CODES.M) {
8688                    return false;
8689                }
8690                final PackageManager packageManager = mContext.getPackageManager();
8691                switch (grantState) {
8692                    case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8693                        mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
8694                                permission, user.getIdentifier(), true /* override policy */);
8695                        packageManager.updatePermissionFlags(permission, packageName,
8696                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8697                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8698                    } break;
8699
8700                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8701                        mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
8702                                permission, user.getIdentifier(), true /* override policy */);
8703                        packageManager.updatePermissionFlags(permission, packageName,
8704                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8705                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8706                    } break;
8707
8708                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8709                        packageManager.updatePermissionFlags(permission, packageName,
8710                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8711                    } break;
8712                }
8713                return true;
8714            } catch (SecurityException se) {
8715                return false;
8716            } finally {
8717                mInjector.binderRestoreCallingIdentity(ident);
8718            }
8719        }
8720    }
8721
8722    @Override
8723    public int getPermissionGrantState(ComponentName admin, String packageName,
8724            String permission) throws RemoteException {
8725        PackageManager packageManager = mContext.getPackageManager();
8726
8727        UserHandle user = mInjector.binderGetCallingUserHandle();
8728        synchronized (this) {
8729            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8730            long ident = mInjector.binderClearCallingIdentity();
8731            try {
8732                int granted = mIPackageManager.checkPermission(permission,
8733                        packageName, user.getIdentifier());
8734                int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8735                if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8736                        != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8737                    // Not controlled by policy
8738                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8739                } else {
8740                    // Policy controlled so return result based on permission grant state
8741                    return granted == PackageManager.PERMISSION_GRANTED
8742                            ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8743                            : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8744                }
8745            } finally {
8746                mInjector.binderRestoreCallingIdentity(ident);
8747            }
8748        }
8749    }
8750
8751    boolean isPackageInstalledForUser(String packageName, int userHandle) {
8752        try {
8753            PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8754                    userHandle);
8755            return (pi != null) && (pi.applicationInfo.flags != 0);
8756        } catch (RemoteException re) {
8757            throw new RuntimeException("Package manager has died", re);
8758        }
8759    }
8760
8761    @Override
8762    public boolean isProvisioningAllowed(String action) {
8763        if (!mHasFeature) {
8764            return false;
8765        }
8766
8767        final int callingUserId = mInjector.userHandleGetCallingUserId();
8768        if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8769            if (!hasFeatureManagedUsers()) {
8770                return false;
8771            }
8772            synchronized (this) {
8773                if (mOwners.hasDeviceOwner()) {
8774                    // STOPSHIP Only allow creating a managed profile if allowed by the device
8775                    // owner. http://b/31952368
8776                    if (mInjector.userManagerIsSplitSystemUser()) {
8777                        if (callingUserId == UserHandle.USER_SYSTEM) {
8778                            // Managed-profiles cannot be setup on the system user.
8779                            return false;
8780                        }
8781                    }
8782                }
8783            }
8784            if (getProfileOwner(callingUserId) != null) {
8785                // Managed user cannot have a managed profile.
8786                return false;
8787            }
8788            boolean canRemoveProfile
8789                    = !mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_USER);
8790            final long ident = mInjector.binderClearCallingIdentity();
8791            try {
8792                if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
8793                    return false;
8794                }
8795            } finally {
8796                mInjector.binderRestoreCallingIdentity(ident);
8797            }
8798            return true;
8799        } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8800            return isDeviceOwnerProvisioningAllowed(callingUserId);
8801        } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8802            if (!hasFeatureManagedUsers()) {
8803                return false;
8804            }
8805            if (!mInjector.userManagerIsSplitSystemUser()) {
8806                // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8807                return false;
8808            }
8809            if (callingUserId == UserHandle.USER_SYSTEM) {
8810                // System user cannot be a managed user.
8811                return false;
8812            }
8813            if (hasUserSetupCompleted(callingUserId)) {
8814                return false;
8815            }
8816            if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8817                return false;
8818            }
8819            return true;
8820        } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8821            if (!mInjector.userManagerIsSplitSystemUser()) {
8822                // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8823                return false;
8824            }
8825            return isDeviceOwnerProvisioningAllowed(callingUserId);
8826        }
8827        throw new IllegalArgumentException("Unknown provisioning action " + action);
8828    }
8829
8830    /*
8831     * The device owner can only be set before the setup phase of the primary user has completed,
8832     * except for adb command if no accounts or additional users are present on the device.
8833     */
8834    private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8835            @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb) {
8836        if (mOwners.hasDeviceOwner()) {
8837            return CODE_HAS_DEVICE_OWNER;
8838        }
8839        if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8840            return CODE_USER_HAS_PROFILE_OWNER;
8841        }
8842        if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8843            return CODE_USER_NOT_RUNNING;
8844        }
8845        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8846            return CODE_HAS_PAIRED;
8847        }
8848        if (isAdb) {
8849            // if shell command runs after user setup completed check device status. Otherwise, OK.
8850            if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8851                if (!mInjector.userManagerIsSplitSystemUser()) {
8852                    if (mUserManager.getUserCount() > 1) {
8853                        return CODE_NONSYSTEM_USER_EXISTS;
8854                    }
8855                    if (hasIncompatibleAccountsLocked(UserHandle.USER_SYSTEM, owner)) {
8856                        return CODE_ACCOUNTS_NOT_EMPTY;
8857                    }
8858                } else {
8859                    // STOPSHIP Do proper check in split user mode
8860                }
8861            }
8862            return CODE_OK;
8863        } else {
8864            if (!mInjector.userManagerIsSplitSystemUser()) {
8865                // In non-split user mode, DO has to be user 0
8866                if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8867                    return CODE_NOT_SYSTEM_USER;
8868                }
8869                // In non-split user mode, only provision DO before setup wizard completes
8870                if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8871                    return CODE_USER_SETUP_COMPLETED;
8872                }
8873            } else {
8874                // STOPSHIP Do proper check in split user mode
8875            }
8876            return CODE_OK;
8877        }
8878    }
8879
8880    private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8881        synchronized (this) {
8882            return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8883                    /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false);
8884        }
8885    }
8886
8887    private boolean hasFeatureManagedUsers() {
8888        try {
8889            return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8890        } catch (RemoteException e) {
8891            return false;
8892        }
8893    }
8894
8895    @Override
8896    public String getWifiMacAddress(ComponentName admin) {
8897        // Make sure caller has DO.
8898        synchronized (this) {
8899            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8900        }
8901
8902        final long ident = mInjector.binderClearCallingIdentity();
8903        try {
8904            final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8905            if (wifiInfo == null) {
8906                return null;
8907            }
8908            return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8909        } finally {
8910            mInjector.binderRestoreCallingIdentity(ident);
8911        }
8912    }
8913
8914    /**
8915     * Returns the target sdk version number that the given packageName was built for
8916     * in the given user.
8917     */
8918    private int getTargetSdk(String packageName, int userId) {
8919        final ApplicationInfo ai;
8920        try {
8921            ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8922            final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8923            return targetSdkVersion;
8924        } catch (RemoteException e) {
8925            // Shouldn't happen
8926            return 0;
8927        }
8928    }
8929
8930    @Override
8931    public boolean isManagedProfile(ComponentName admin) {
8932        synchronized (this) {
8933            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8934        }
8935        return isManagedProfile(mInjector.userHandleGetCallingUserId());
8936    }
8937
8938    @Override
8939    public boolean isSystemOnlyUser(ComponentName admin) {
8940        synchronized (this) {
8941            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8942        }
8943        final int callingUserId = mInjector.userHandleGetCallingUserId();
8944        return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8945    }
8946
8947    @Override
8948    public void reboot(ComponentName admin) {
8949        Preconditions.checkNotNull(admin);
8950        // Make sure caller has DO.
8951        synchronized (this) {
8952            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8953        }
8954        long ident = mInjector.binderClearCallingIdentity();
8955        try {
8956            // Make sure there are no ongoing calls on the device.
8957            if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8958                throw new IllegalStateException("Cannot be called with ongoing call on the device");
8959            }
8960            mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8961        } finally {
8962            mInjector.binderRestoreCallingIdentity(ident);
8963        }
8964    }
8965
8966    @Override
8967    public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8968        if (!mHasFeature) {
8969            return;
8970        }
8971        Preconditions.checkNotNull(who, "ComponentName is null");
8972        final int userHandle = mInjector.userHandleGetCallingUserId();
8973        synchronized (this) {
8974            ActiveAdmin admin = getActiveAdminForUidLocked(who,
8975                    mInjector.binderGetCallingUid());
8976            if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8977                admin.shortSupportMessage = message;
8978                saveSettingsLocked(userHandle);
8979            }
8980        }
8981    }
8982
8983    @Override
8984    public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8985        if (!mHasFeature) {
8986            return null;
8987        }
8988        Preconditions.checkNotNull(who, "ComponentName is null");
8989        synchronized (this) {
8990            ActiveAdmin admin = getActiveAdminForUidLocked(who,
8991                    mInjector.binderGetCallingUid());
8992            return admin.shortSupportMessage;
8993        }
8994    }
8995
8996    @Override
8997    public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8998        if (!mHasFeature) {
8999            return;
9000        }
9001        Preconditions.checkNotNull(who, "ComponentName is null");
9002        final int userHandle = mInjector.userHandleGetCallingUserId();
9003        synchronized (this) {
9004            ActiveAdmin admin = getActiveAdminForUidLocked(who,
9005                    mInjector.binderGetCallingUid());
9006            if (!TextUtils.equals(admin.longSupportMessage, message)) {
9007                admin.longSupportMessage = message;
9008                saveSettingsLocked(userHandle);
9009            }
9010        }
9011    }
9012
9013    @Override
9014    public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
9015        if (!mHasFeature) {
9016            return null;
9017        }
9018        Preconditions.checkNotNull(who, "ComponentName is null");
9019        synchronized (this) {
9020            ActiveAdmin admin = getActiveAdminForUidLocked(who,
9021                    mInjector.binderGetCallingUid());
9022            return admin.longSupportMessage;
9023        }
9024    }
9025
9026    @Override
9027    public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
9028        if (!mHasFeature) {
9029            return null;
9030        }
9031        Preconditions.checkNotNull(who, "ComponentName is null");
9032        if (!isCallerWithSystemUid()) {
9033            throw new SecurityException("Only the system can query support message for user");
9034        }
9035        synchronized (this) {
9036            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9037            if (admin != null) {
9038                return admin.shortSupportMessage;
9039            }
9040        }
9041        return null;
9042    }
9043
9044    @Override
9045    public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
9046        if (!mHasFeature) {
9047            return null;
9048        }
9049        Preconditions.checkNotNull(who, "ComponentName is null");
9050        if (!isCallerWithSystemUid()) {
9051            throw new SecurityException("Only the system can query support message for user");
9052        }
9053        synchronized (this) {
9054            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9055            if (admin != null) {
9056                return admin.longSupportMessage;
9057            }
9058        }
9059        return null;
9060    }
9061
9062    @Override
9063    public void setOrganizationColor(@NonNull ComponentName who, int color) {
9064        if (!mHasFeature) {
9065            return;
9066        }
9067        Preconditions.checkNotNull(who, "ComponentName is null");
9068        final int userHandle = mInjector.userHandleGetCallingUserId();
9069        enforceManagedProfile(userHandle, "set organization color");
9070        synchronized (this) {
9071            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9072                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9073            admin.organizationColor = color;
9074            saveSettingsLocked(userHandle);
9075        }
9076    }
9077
9078    @Override
9079    public void setOrganizationColorForUser(int color, int userId) {
9080        if (!mHasFeature) {
9081            return;
9082        }
9083        enforceFullCrossUsersPermission(userId);
9084        enforceManageUsers();
9085        enforceManagedProfile(userId, "set organization color");
9086        synchronized (this) {
9087            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9088            admin.organizationColor = color;
9089            saveSettingsLocked(userId);
9090        }
9091    }
9092
9093    @Override
9094    public int getOrganizationColor(@NonNull ComponentName who) {
9095        if (!mHasFeature) {
9096            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9097        }
9098        Preconditions.checkNotNull(who, "ComponentName is null");
9099        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
9100        synchronized (this) {
9101            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9102                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9103            return admin.organizationColor;
9104        }
9105    }
9106
9107    @Override
9108    public int getOrganizationColorForUser(int userHandle) {
9109        if (!mHasFeature) {
9110            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9111        }
9112        enforceFullCrossUsersPermission(userHandle);
9113        enforceManagedProfile(userHandle, "get organization color");
9114        synchronized (this) {
9115            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9116            return (profileOwner != null)
9117                    ? profileOwner.organizationColor
9118                    : ActiveAdmin.DEF_ORGANIZATION_COLOR;
9119        }
9120    }
9121
9122    @Override
9123    public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
9124        if (!mHasFeature) {
9125            return;
9126        }
9127        Preconditions.checkNotNull(who, "ComponentName is null");
9128        final int userHandle = mInjector.userHandleGetCallingUserId();
9129
9130        synchronized (this) {
9131            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9132                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9133            if (!TextUtils.equals(admin.organizationName, text)) {
9134                admin.organizationName = (text == null || text.length() == 0)
9135                        ? null : text.toString();
9136                saveSettingsLocked(userHandle);
9137            }
9138        }
9139    }
9140
9141    @Override
9142    public CharSequence getOrganizationName(@NonNull ComponentName who) {
9143        if (!mHasFeature) {
9144            return null;
9145        }
9146        Preconditions.checkNotNull(who, "ComponentName is null");
9147        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
9148        synchronized(this) {
9149            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9150                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9151            return admin.organizationName;
9152        }
9153    }
9154
9155    @Override
9156    public CharSequence getDeviceOwnerOrganizationName() {
9157        if (!mHasFeature) {
9158            return null;
9159        }
9160        enforceDeviceOwnerOrManageUsers();
9161        synchronized(this) {
9162            final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
9163            return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
9164        }
9165    }
9166
9167    @Override
9168    public CharSequence getOrganizationNameForUser(int userHandle) {
9169        if (!mHasFeature) {
9170            return null;
9171        }
9172        enforceFullCrossUsersPermission(userHandle);
9173        enforceManagedProfile(userHandle, "get organization name");
9174        synchronized (this) {
9175            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9176            return (profileOwner != null)
9177                    ? profileOwner.organizationName
9178                    : null;
9179        }
9180    }
9181
9182    @Override
9183    public void setAffiliationIds(ComponentName admin, List<String> ids) {
9184        if (!mHasFeature) {
9185            return;
9186        }
9187
9188        Preconditions.checkNotNull(admin);
9189        Preconditions.checkCollectionElementsNotNull(ids, "ids");
9190
9191        final Set<String> affiliationIds = new ArraySet<String>(ids);
9192        Preconditions.checkArgument(
9193                !affiliationIds.contains(""), "ids must not contain empty strings");
9194
9195        final int callingUserId = mInjector.userHandleGetCallingUserId();
9196        synchronized (this) {
9197            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9198            getUserData(callingUserId).mAffiliationIds = affiliationIds;
9199            saveSettingsLocked(callingUserId);
9200            if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
9201                // Affiliation ids specified by the device owner are additionally stored in
9202                // UserHandle.USER_SYSTEM's DevicePolicyData.
9203                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
9204                saveSettingsLocked(UserHandle.USER_SYSTEM);
9205            }
9206        }
9207    }
9208
9209    @Override
9210    public List<String> getAffiliationIds(ComponentName admin) {
9211        if (!mHasFeature) {
9212            return Collections.emptyList();
9213        }
9214
9215        Preconditions.checkNotNull(admin);
9216        synchronized (this) {
9217            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9218            return new ArrayList<String>(
9219                    getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
9220        }
9221    }
9222
9223    @Override
9224    public boolean isAffiliatedUser() {
9225        return isUserAffiliatedWithDevice(mInjector.userHandleGetCallingUserId());
9226    }
9227
9228    private boolean isUserAffiliatedWithDevice(int userId) {
9229        synchronized (this) {
9230            if (!mOwners.hasDeviceOwner()) {
9231                return false;
9232            }
9233            if (userId == mOwners.getDeviceOwnerUserId()) {
9234                // The user that the DO is installed on is always affiliated with the device.
9235                return true;
9236            }
9237            if (userId == UserHandle.USER_SYSTEM) {
9238                // The system user is always affiliated in a DO device, even if the DO is set on a
9239                // different user. This could be the case if the DO is set in the primary user
9240                // of a split user device.
9241                return true;
9242            }
9243            final ComponentName profileOwner = getProfileOwner(userId);
9244            if (profileOwner == null) {
9245                return false;
9246            }
9247            final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
9248            final Set<String> deviceAffiliationIds =
9249                    getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9250            for (String id : userAffiliationIds) {
9251                if (deviceAffiliationIds.contains(id)) {
9252                    return true;
9253                }
9254            }
9255        }
9256        return false;
9257    }
9258
9259    private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
9260        final boolean isSingleUserManagedDevice = isDeviceOwnerManagedSingleUserDevice();
9261
9262        // disable security logging if needed
9263        if (!isSingleUserManagedDevice) {
9264            mInjector.securityLogSetLoggingEnabledProperty(false);
9265            Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user managed"
9266                    + " device.");
9267        }
9268
9269        // disable backup service if needed
9270        // note: when clearing DO, the backup service shouldn't be disabled if it was enabled by
9271        // the device owner
9272        if (mOwners.hasDeviceOwner() && !isSingleUserManagedDevice) {
9273            setBackupServiceEnabledInternal(false);
9274            Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
9275        }
9276
9277        // disable network logging if needed
9278        if (!isSingleUserManagedDevice) {
9279            setNetworkLoggingActiveInternal(false);
9280            Slog.w(LOG_TAG, "Network logging turned off as it's no longer a single user managed"
9281                    + " device.");
9282            // if there still is a device owner, disable logging policy, otherwise the admin
9283            // has been nuked
9284            if (mOwners.hasDeviceOwner()) {
9285                getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = false;
9286                saveSettingsLocked(mOwners.getDeviceOwnerUserId());
9287            }
9288        }
9289    }
9290
9291    @Override
9292    public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9293        Preconditions.checkNotNull(admin);
9294        ensureDeviceOwnerManagingSingleUser(admin);
9295
9296        synchronized (this) {
9297            if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9298                return;
9299            }
9300            mInjector.securityLogSetLoggingEnabledProperty(enabled);
9301            if (enabled) {
9302                mSecurityLogMonitor.start();
9303            } else {
9304                mSecurityLogMonitor.stop();
9305            }
9306        }
9307    }
9308
9309    @Override
9310    public boolean isSecurityLoggingEnabled(ComponentName admin) {
9311        Preconditions.checkNotNull(admin);
9312        synchronized (this) {
9313            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9314            return mInjector.securityLogGetLoggingEnabledProperty();
9315        }
9316    }
9317
9318    private synchronized void recordSecurityLogRetrievalTime() {
9319        final long currentTime = System.currentTimeMillis();
9320        DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
9321        if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
9322            policyData.mLastSecurityLogRetrievalTime = currentTime;
9323            saveSettingsLocked(UserHandle.USER_SYSTEM);
9324        }
9325    }
9326
9327    @Override
9328    public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9329        Preconditions.checkNotNull(admin);
9330        ensureDeviceOwnerManagingSingleUser(admin);
9331
9332        if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
9333            return null;
9334        }
9335
9336        recordSecurityLogRetrievalTime();
9337
9338        ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9339        try {
9340            SecurityLog.readPreviousEvents(output);
9341            return new ParceledListSlice<SecurityEvent>(output);
9342        } catch (IOException e) {
9343            Slog.w(LOG_TAG, "Fail to read previous events" , e);
9344            return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9345        }
9346    }
9347
9348    @Override
9349    public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9350        Preconditions.checkNotNull(admin);
9351        ensureDeviceOwnerManagingSingleUser(admin);
9352
9353        recordSecurityLogRetrievalTime();
9354
9355        List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
9356        return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
9357    }
9358
9359    private void enforceCanManageDeviceAdmin() {
9360        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
9361                null);
9362    }
9363
9364    private void enforceCanManageProfileAndDeviceOwners() {
9365        mContext.enforceCallingOrSelfPermission(
9366                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
9367    }
9368
9369    private void enforceCallerSystemUserHandle() {
9370        final int callingUid = mInjector.binderGetCallingUid();
9371        final int userId = UserHandle.getUserId(callingUid);
9372        if (userId != UserHandle.USER_SYSTEM) {
9373            throw new SecurityException("Caller has to be in user 0");
9374        }
9375    }
9376
9377    @Override
9378    public boolean isUninstallInQueue(final String packageName) {
9379        enforceCanManageDeviceAdmin();
9380        final int userId = mInjector.userHandleGetCallingUserId();
9381        Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9382        synchronized (this) {
9383            return mPackagesToRemove.contains(packageUserPair);
9384        }
9385    }
9386
9387    @Override
9388    public void uninstallPackageWithActiveAdmins(final String packageName) {
9389        enforceCanManageDeviceAdmin();
9390        Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
9391
9392        final int userId = mInjector.userHandleGetCallingUserId();
9393
9394        enforceUserUnlocked(userId);
9395
9396        final ComponentName profileOwner = getProfileOwner(userId);
9397        if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9398            throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9399        }
9400
9401        final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9402        if (getDeviceOwnerUserId() == userId && deviceOwner != null
9403                && packageName.equals(deviceOwner.getPackageName())) {
9404            throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9405        }
9406
9407        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9408        synchronized (this) {
9409            mPackagesToRemove.add(packageUserPair);
9410        }
9411
9412        // All active admins on the user.
9413        final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9414
9415        // Active admins in the target package.
9416        final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9417        if (allActiveAdmins != null) {
9418            for (ComponentName activeAdmin : allActiveAdmins) {
9419                if (packageName.equals(activeAdmin.getPackageName())) {
9420                    packageActiveAdmins.add(activeAdmin);
9421                    removeActiveAdmin(activeAdmin, userId);
9422                }
9423            }
9424        }
9425        if (packageActiveAdmins.size() == 0) {
9426            startUninstallIntent(packageName, userId);
9427        } else {
9428            mHandler.postDelayed(new Runnable() {
9429                @Override
9430                public void run() {
9431                    for (ComponentName activeAdmin : packageActiveAdmins) {
9432                        removeAdminArtifacts(activeAdmin, userId);
9433                    }
9434                    startUninstallIntent(packageName, userId);
9435                }
9436            }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9437        }
9438    }
9439
9440    @Override
9441    public boolean isDeviceProvisioned() {
9442        return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9443    }
9444
9445    private void removePackageIfRequired(final String packageName, final int userId) {
9446        if (!packageHasActiveAdmins(packageName, userId)) {
9447            // Will not do anything if uninstall was not requested or was already started.
9448            startUninstallIntent(packageName, userId);
9449        }
9450    }
9451
9452    private void startUninstallIntent(final String packageName, final int userId) {
9453        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9454        synchronized (this) {
9455            if (!mPackagesToRemove.contains(packageUserPair)) {
9456                // Do nothing if uninstall was not requested or was already started.
9457                return;
9458            }
9459            mPackagesToRemove.remove(packageUserPair);
9460        }
9461        try {
9462            if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9463                // Package does not exist. Nothing to do.
9464                return;
9465            }
9466        } catch (RemoteException re) {
9467            Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9468        }
9469
9470        try { // force stop the package before uninstalling
9471            mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9472        } catch (RemoteException re) {
9473            Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9474        }
9475        final Uri packageURI = Uri.parse("package:" + packageName);
9476        final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9477        uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9478        mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9479    }
9480
9481    /**
9482     * Removes the admin from the policy. Ideally called after the admin's
9483     * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9484     *
9485     * @param adminReceiver The admin to remove
9486     * @param userHandle The user for which this admin has to be removed.
9487     */
9488    private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9489        synchronized (this) {
9490            final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9491            if (admin == null) {
9492                return;
9493            }
9494            final DevicePolicyData policy = getUserData(userHandle);
9495            final boolean doProxyCleanup = admin.info.usesPolicy(
9496                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9497            policy.mAdminList.remove(admin);
9498            policy.mAdminMap.remove(adminReceiver);
9499            validatePasswordOwnerLocked(policy);
9500            if (doProxyCleanup) {
9501                resetGlobalProxyLocked(policy);
9502            }
9503            saveSettingsLocked(userHandle);
9504            updateMaximumTimeToLockLocked(userHandle);
9505            policy.mRemovingAdmins.remove(adminReceiver);
9506
9507            Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9508        }
9509        // The removed admin might have disabled camera, so update user
9510        // restrictions.
9511        pushUserRestrictions(userHandle);
9512    }
9513
9514    @Override
9515    public void setDeviceProvisioningConfigApplied() {
9516        enforceManageUsers();
9517        synchronized (this) {
9518            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9519            policy.mDeviceProvisioningConfigApplied = true;
9520            saveSettingsLocked(UserHandle.USER_SYSTEM);
9521        }
9522    }
9523
9524    @Override
9525    public boolean isDeviceProvisioningConfigApplied() {
9526        enforceManageUsers();
9527        synchronized (this) {
9528            final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9529            return policy.mDeviceProvisioningConfigApplied;
9530        }
9531    }
9532
9533    /**
9534     * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
9535     *
9536     * It's added for testing only. Please use this API carefully if it's used by other system app
9537     * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
9538     * apps.
9539     */
9540    @Override
9541    public void forceUpdateUserSetupComplete() {
9542        enforceCanManageProfileAndDeviceOwners();
9543        enforceCallerSystemUserHandle();
9544        // no effect if it's called from user build
9545        if (!mInjector.isBuildDebuggable()) {
9546            return;
9547        }
9548        final int userId = UserHandle.USER_SYSTEM;
9549        boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
9550                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
9551        DevicePolicyData policy = getUserData(userId);
9552        policy.mUserSetupComplete = isUserCompleted;
9553        synchronized (this) {
9554            saveSettingsLocked(userId);
9555        }
9556    }
9557
9558    @Override
9559    public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
9560        Preconditions.checkNotNull(admin);
9561        if (!mHasFeature) {
9562            return;
9563        }
9564        ensureDeviceOwnerManagingSingleUser(admin);
9565        setBackupServiceEnabledInternal(enabled);
9566    }
9567
9568    private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
9569        long ident = mInjector.binderClearCallingIdentity();
9570        try {
9571            IBackupManager ibm = mInjector.getIBackupManager();
9572            if (ibm != null) {
9573                ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
9574            }
9575        } catch (RemoteException e) {
9576            throw new IllegalStateException(
9577                "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
9578        } finally {
9579            mInjector.binderRestoreCallingIdentity(ident);
9580        }
9581    }
9582
9583    @Override
9584    public boolean isBackupServiceEnabled(ComponentName admin) {
9585        Preconditions.checkNotNull(admin);
9586        if (!mHasFeature) {
9587            return true;
9588        }
9589        synchronized (this) {
9590            try {
9591                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9592                IBackupManager ibm = mInjector.getIBackupManager();
9593                return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
9594            } catch (RemoteException e) {
9595                throw new IllegalStateException("Failed requesting backup service state.", e);
9596            }
9597        }
9598    }
9599
9600    @Override
9601    public boolean bindDeviceAdminServiceAsUser(
9602            @NonNull ComponentName admin, @NonNull IApplicationThread caller,
9603            @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
9604            @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
9605        if (!mHasFeature) {
9606            return false;
9607        }
9608        Preconditions.checkNotNull(admin);
9609        Preconditions.checkNotNull(caller);
9610        Preconditions.checkNotNull(serviceIntent);
9611        Preconditions.checkArgument(
9612                serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
9613                "Service intent must be explicit (with a package name or component): "
9614                        + serviceIntent);
9615        Preconditions.checkNotNull(connection);
9616        Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
9617                "target user id must be different from the calling user id");
9618
9619        if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
9620            throw new SecurityException("Not allowed to bind to target user id");
9621        }
9622
9623        final String targetPackage;
9624        synchronized (this) {
9625            targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
9626        }
9627
9628        final long callingIdentity = mInjector.binderClearCallingIdentity();
9629        try {
9630            // Validate and sanitize the incoming service intent.
9631            final Intent sanitizedIntent =
9632                    createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
9633            if (sanitizedIntent == null) {
9634                // Fail, cannot lookup the target service.
9635                return false;
9636            }
9637            // Ask ActivityManager to bind it. Notice that we are binding the service with the
9638            // caller app instead of DevicePolicyManagerService.
9639            return mInjector.getIActivityManager().bindService(
9640                    caller, activtiyToken, serviceIntent,
9641                    serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
9642                    connection, flags, mContext.getOpPackageName(),
9643                    targetUserId) != 0;
9644        } catch (RemoteException ex) {
9645            // Same process, should not happen.
9646        } finally {
9647            mInjector.binderRestoreCallingIdentity(callingIdentity);
9648        }
9649
9650        // Failed to bind.
9651        return false;
9652    }
9653
9654    @Override
9655    public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
9656        if (!mHasFeature) {
9657            return Collections.emptyList();
9658        }
9659        Preconditions.checkNotNull(admin);
9660        ArrayList<UserHandle> targetUsers = new ArrayList<>();
9661
9662        synchronized (this) {
9663            ActiveAdmin callingOwner = getActiveAdminForCallerLocked(
9664                    admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9665
9666            final int callingUserId = mInjector.userHandleGetCallingUserId();
9667            final boolean isCallerDeviceOwner = isDeviceOwner(callingOwner);
9668            final boolean isCallerManagedProfile = isManagedProfile(callingUserId);
9669            if (!isCallerDeviceOwner && !isCallerManagedProfile
9670                    /* STOPSHIP(b/32326223) Reinstate when setAffiliationIds is public
9671                    ||   !isAffiliatedUser(callingUserId) */) {
9672                return targetUsers;
9673            }
9674
9675            final long callingIdentity = mInjector.binderClearCallingIdentity();
9676            try {
9677                String callingOwnerPackage = callingOwner.info.getComponent().getPackageName();
9678                for (int userId : mUserManager.getProfileIdsWithDisabled(callingUserId)) {
9679                    if (userId == callingUserId) {
9680                        continue;
9681                    }
9682
9683                    // We only allow the device owner and a managed profile owner to bind to each
9684                    // other.
9685                    if ((isCallerManagedProfile && userId == mOwners.getDeviceOwnerUserId())
9686                            || (isCallerDeviceOwner && isManagedProfile(userId))) {
9687                        String targetOwnerPackage = getOwnerPackageNameForUserLocked(userId);
9688
9689                        // Both must be the same package and be affiliated in order to bind.
9690                        if (callingOwnerPackage.equals(targetOwnerPackage)
9691                            /* STOPSHIP(b/32326223) Reinstate when setAffiliationIds is public
9692                               && isAffiliatedUser(userId)*/) {
9693                            targetUsers.add(UserHandle.of(userId));
9694                        }
9695                    }
9696                }
9697            } finally {
9698                mInjector.binderRestoreCallingIdentity(callingIdentity);
9699            }
9700        }
9701
9702        return targetUsers;
9703    }
9704
9705    /**
9706     * Return true if a given user has any accounts that'll prevent installing a device or profile
9707     * owner {@code owner}.
9708     * - If the user has no accounts, then return false.
9709     * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9710     * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9711     *   ..._DISALLOWED, return true.
9712     * - Otherwise return false.
9713     */
9714    private boolean hasIncompatibleAccountsLocked(int userId, @Nullable ComponentName owner) {
9715        final long token = mInjector.binderClearCallingIdentity();
9716        try {
9717            final AccountManager am = AccountManager.get(mContext);
9718            final Account accounts[] = am.getAccountsAsUser(userId);
9719            if (accounts.length == 0) {
9720                return false;
9721            }
9722            final String[] feature_allow =
9723                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9724            final String[] feature_disallow =
9725                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9726
9727            // Even if we find incompatible accounts along the way, we still check all accounts
9728            // for logging.
9729            boolean compatible = true;
9730            for (Account account : accounts) {
9731                if (hasAccountFeatures(am, account, feature_disallow)) {
9732                    Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9733                    compatible = false;
9734                }
9735                if (!hasAccountFeatures(am, account, feature_allow)) {
9736                    Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9737                    compatible = false;
9738                }
9739            }
9740            if (compatible) {
9741                Log.w(LOG_TAG, "All accounts are compatible");
9742            } else {
9743                Log.e(LOG_TAG, "Found incompatible accounts");
9744            }
9745
9746            // Then check if the owner is test-only.
9747            String log;
9748            if (owner == null) {
9749                // Owner is unknown.  Suppose it's not test-only
9750                compatible = false;
9751                log = "Only test-only device/profile owner can be installed with accounts";
9752            } else if (isAdminTestOnlyLocked(owner, userId)) {
9753                if (compatible) {
9754                    log = "Installing test-only owner " + owner;
9755                } else {
9756                    log = "Can't install test-only owner " + owner + " with incompatible accounts";
9757                }
9758            } else {
9759                compatible = false;
9760                log = "Can't install non test-only owner " + owner + " with accounts";
9761            }
9762            if (compatible) {
9763                Log.w(LOG_TAG, log);
9764            } else {
9765                Log.e(LOG_TAG, log);
9766            }
9767            return !compatible;
9768        } finally {
9769            mInjector.binderRestoreCallingIdentity(token);
9770        }
9771    }
9772
9773    private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9774        try {
9775            return am.hasFeatures(account, features, null, null).getResult();
9776        } catch (Exception e) {
9777            Log.w(LOG_TAG, "Failed to get account feature", e);
9778            return false;
9779        }
9780    }
9781
9782    private boolean isAdb() {
9783        final int callingUid = mInjector.binderGetCallingUid();
9784        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
9785    }
9786
9787    @Override
9788    public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
9789        if (!mHasFeature) {
9790            return;
9791        }
9792        Preconditions.checkNotNull(admin);
9793        ensureDeviceOwnerManagingSingleUser(admin);
9794
9795        if (enabled == isNetworkLoggingEnabledInternalLocked()) {
9796            // already in the requested state
9797            return;
9798        }
9799        getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = enabled;
9800        saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9801
9802        setNetworkLoggingActiveInternal(enabled);
9803    }
9804
9805    private synchronized void setNetworkLoggingActiveInternal(boolean active) {
9806        final long callingIdentity = mInjector.binderClearCallingIdentity();
9807        try {
9808            if (active) {
9809                mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
9810                if (!mNetworkLogger.startNetworkLogging()) {
9811                    mNetworkLogger = null;
9812                    Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
9813                            + " service not being available yet.");
9814                }
9815            } else {
9816                if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
9817                    mNetworkLogger = null;
9818                    Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
9819                            + " service not being available yet.");
9820                }
9821                mNetworkLogger = null;
9822            }
9823        } finally {
9824            mInjector.binderRestoreCallingIdentity(callingIdentity);
9825        }
9826    }
9827
9828    @Override
9829    public boolean isNetworkLoggingEnabled(ComponentName admin) {
9830        if (!mHasFeature) {
9831            return false;
9832        }
9833        Preconditions.checkNotNull(admin);
9834        synchronized (this) {
9835            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9836            return isNetworkLoggingEnabledInternalLocked();
9837        }
9838    }
9839
9840    private boolean isNetworkLoggingEnabledInternalLocked() {
9841        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9842        return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
9843    }
9844
9845    /*
9846     * A maximum of 1200 events are returned, and the total marshalled size is in the order of
9847     * 100kB, so returning a List instead of ParceledListSlice is acceptable.
9848     * Ideally this would be done with ParceledList, however it only supports homogeneous types.
9849     *
9850     * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
9851     */
9852    @Override
9853    public synchronized List<NetworkEvent> retrieveNetworkLogs(ComponentName admin,
9854            long batchToken) {
9855        if (!mHasFeature) {
9856            return null;
9857        }
9858        Preconditions.checkNotNull(admin);
9859        ensureDeviceOwnerManagingSingleUser(admin);
9860
9861        if (mNetworkLogger == null) {
9862            return null;
9863        }
9864
9865        if (!isNetworkLoggingEnabledInternalLocked()) {
9866            return null;
9867        }
9868
9869        final long currentTime = System.currentTimeMillis();
9870        synchronized (this) {
9871            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
9872            if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
9873                policyData.mLastNetworkLogsRetrievalTime = currentTime;
9874                saveSettingsLocked(UserHandle.USER_SYSTEM);
9875            }
9876        }
9877
9878        return mNetworkLogger.retrieveLogs(batchToken);
9879    }
9880
9881    /**
9882     * Return the package name of owner in a given user.
9883     */
9884    private String getOwnerPackageNameForUserLocked(int userId) {
9885        return mOwners.getDeviceOwnerUserId() == userId
9886                ? mOwners.getDeviceOwnerPackageName()
9887                : mOwners.getProfileOwnerPackage(userId);
9888    }
9889
9890    /**
9891     * @param rawIntent Original service intent specified by caller. It must be explicit.
9892     * @param expectedPackageName The expected package name of the resolved service.
9893     * @return Intent that have component explicitly set. {@code null} if no service is resolved
9894     *     with the given intent.
9895     * @throws SecurityException if the intent is resolved to an invalid service.
9896     */
9897    private Intent createCrossUserServiceIntent(
9898            @NonNull Intent rawIntent, @NonNull String expectedPackageName,
9899            @UserIdInt int targetUserId) throws RemoteException, SecurityException {
9900        ResolveInfo info = mIPackageManager.resolveService(
9901                rawIntent,
9902                rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
9903                0,  // flags
9904                targetUserId);
9905        if (info == null || info.serviceInfo == null) {
9906            Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
9907                    + " or user " + targetUserId + " is not running");
9908            return null;
9909        }
9910        if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
9911            throw new SecurityException("Only allow to bind service in " + expectedPackageName);
9912        }
9913        if (info.serviceInfo.exported) {
9914            throw new SecurityException("The service must be unexported");
9915        }
9916        // It is the system server to bind the service, it would be extremely dangerous if it
9917        // can be exploited to bind any service. Set the component explicitly to make sure we
9918        // do not bind anything accidentally.
9919        rawIntent.setComponent(info.serviceInfo.getComponentName());
9920        return rawIntent;
9921    }
9922
9923    @Override
9924    public long getLastSecurityLogRetrievalTime() {
9925        enforceDeviceOwnerOrManageUsers();
9926        return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
9927     }
9928
9929    @Override
9930    public long getLastBugReportRequestTime() {
9931        enforceDeviceOwnerOrManageUsers();
9932        return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
9933     }
9934
9935    @Override
9936    public long getLastNetworkLogRetrievalTime() {
9937        enforceDeviceOwnerOrManageUsers();
9938        return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
9939    }
9940}
9941