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