DevicePolicyManagerService.java revision 08be96ec870d01ec7f7fa26f810777c60af666d4
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        }
6101        clearUserPoliciesLocked(userId);
6102
6103        mOwners.clearDeviceOwner();
6104        mOwners.writeDeviceOwner();
6105        updateDeviceOwnerLocked();
6106        disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
6107        try {
6108            if (mInjector.getIBackupManager() != null) {
6109                // Reactivate backup service.
6110                mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6111            }
6112        } catch (RemoteException e) {
6113            throw new IllegalStateException("Failed reactivating backup service.", e);
6114        }
6115    }
6116
6117    @Override
6118    public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6119        if (!mHasFeature) {
6120            return false;
6121        }
6122        if (who == null
6123                || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6124            throw new IllegalArgumentException("Component " + who
6125                    + " not installed for userId:" + userHandle);
6126        }
6127        synchronized (this) {
6128            enforceCanSetProfileOwnerLocked(who, userHandle);
6129
6130            if (getActiveAdminUncheckedLocked(who, userHandle) == null
6131                    || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6132                throw new IllegalArgumentException("Not active admin: " + who);
6133            }
6134
6135            if (isAdb()) {
6136                // Log profile owner provisioning was started using adb.
6137                MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
6138            }
6139
6140            mOwners.setProfileOwner(who, ownerName, userHandle);
6141            mOwners.writeProfileOwner(userHandle);
6142            Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6143            return true;
6144        }
6145    }
6146
6147    @Override
6148    public void clearProfileOwner(ComponentName who) {
6149        if (!mHasFeature) {
6150            return;
6151        }
6152        final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6153        final int userId = callingUser.getIdentifier();
6154        enforceNotManagedProfile(userId, "clear profile owner");
6155        enforceUserUnlocked(userId);
6156        // Check if this is the profile owner who is calling
6157        final ActiveAdmin admin =
6158                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6159        synchronized (this) {
6160            final long ident = mInjector.binderClearCallingIdentity();
6161            try {
6162                clearProfileOwnerLocked(admin, userId);
6163                removeActiveAdminLocked(who, userId);
6164            } finally {
6165                mInjector.binderRestoreCallingIdentity(ident);
6166            }
6167            Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6168        }
6169    }
6170
6171    public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6172        if (admin != null) {
6173            admin.disableCamera = false;
6174            admin.userRestrictions = null;
6175        }
6176        clearUserPoliciesLocked(userId);
6177        mOwners.removeProfileOwner(userId);
6178        mOwners.writeProfileOwner(userId);
6179    }
6180
6181    @Override
6182    public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6183        Preconditions.checkNotNull(who, "ComponentName is null");
6184        if (!mHasFeature) {
6185            return;
6186        }
6187
6188        synchronized (this) {
6189            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6190            long token = mInjector.binderClearCallingIdentity();
6191            try {
6192                mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6193            } finally {
6194                mInjector.binderRestoreCallingIdentity(token);
6195            }
6196        }
6197    }
6198
6199    @Override
6200    public CharSequence getDeviceOwnerLockScreenInfo() {
6201        return mLockPatternUtils.getDeviceOwnerInfo();
6202    }
6203
6204    private void clearUserPoliciesLocked(int userId) {
6205        // Reset some of the user-specific policies
6206        DevicePolicyData policy = getUserData(userId);
6207        policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6208        policy.mDelegatedCertInstallerPackage = null;
6209        policy.mApplicationRestrictionsManagingPackage = null;
6210        policy.mStatusBarDisabled = false;
6211        policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6212        saveSettingsLocked(userId);
6213
6214        try {
6215            mIPackageManager.updatePermissionFlagsForAllApps(
6216                    PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6217                    0  /* flagValues */, userId);
6218            pushUserRestrictions(userId);
6219        } catch (RemoteException re) {
6220            // Shouldn't happen.
6221        }
6222    }
6223
6224    @Override
6225    public boolean hasUserSetupCompleted() {
6226        return hasUserSetupCompleted(UserHandle.getCallingUserId());
6227    }
6228
6229    // This checks only if the Setup Wizard has run.  Since Wear devices pair before
6230    // completing Setup Wizard, and pairing involves transferring user data, calling
6231    // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6232    private boolean hasUserSetupCompleted(int userHandle) {
6233        if (!mHasFeature) {
6234            return true;
6235        }
6236        return getUserData(userHandle).mUserSetupComplete;
6237    }
6238
6239    private boolean hasPaired(int userHandle) {
6240        if (!mHasFeature) {
6241            return true;
6242        }
6243        return getUserData(userHandle).mPaired;
6244    }
6245
6246    @Override
6247    public int getUserProvisioningState() {
6248        if (!mHasFeature) {
6249            return DevicePolicyManager.STATE_USER_UNMANAGED;
6250        }
6251        int userHandle = mInjector.userHandleGetCallingUserId();
6252        return getUserProvisioningState(userHandle);
6253    }
6254
6255    private int getUserProvisioningState(int userHandle) {
6256        return getUserData(userHandle).mUserProvisioningState;
6257    }
6258
6259    @Override
6260    public void setUserProvisioningState(int newState, int userHandle) {
6261        if (!mHasFeature) {
6262            return;
6263        }
6264
6265        if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6266                && getManagedUserId(userHandle) == -1) {
6267            // No managed device, user or profile, so setting provisioning state makes no sense.
6268            throw new IllegalStateException("Not allowed to change provisioning state unless a "
6269                      + "device or profile owner is set.");
6270        }
6271
6272        synchronized (this) {
6273            boolean transitionCheckNeeded = true;
6274
6275            // Calling identity/permission checks.
6276            if (isAdb()) {
6277                // ADB shell can only move directly from un-managed to finalized as part of directly
6278                // setting profile-owner or device-owner.
6279                if (getUserProvisioningState(userHandle) !=
6280                        DevicePolicyManager.STATE_USER_UNMANAGED
6281                        || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6282                    throw new IllegalStateException("Not allowed to change provisioning state "
6283                            + "unless current provisioning state is unmanaged, and new state is "
6284                            + "finalized.");
6285                }
6286                transitionCheckNeeded = false;
6287            } else {
6288                // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6289                enforceCanManageProfileAndDeviceOwners();
6290            }
6291
6292            final DevicePolicyData policyData = getUserData(userHandle);
6293            if (transitionCheckNeeded) {
6294                // Optional state transition check for non-ADB case.
6295                checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6296            }
6297            policyData.mUserProvisioningState = newState;
6298            saveSettingsLocked(userHandle);
6299        }
6300    }
6301
6302    private void checkUserProvisioningStateTransition(int currentState, int newState) {
6303        // Valid transitions for normal use-cases.
6304        switch (currentState) {
6305            case DevicePolicyManager.STATE_USER_UNMANAGED:
6306                // Can move to any state from unmanaged (except itself as an edge case)..
6307                if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6308                    return;
6309                }
6310                break;
6311            case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6312            case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6313                // Can only move to finalized from these states.
6314                if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6315                    return;
6316                }
6317                break;
6318            case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6319                // Current user has a managed-profile, but current user is not managed, so
6320                // rather than moving to finalized state, go back to unmanaged once
6321                // profile provisioning is complete.
6322                if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6323                    return;
6324                }
6325                break;
6326            case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6327                // Cannot transition out of finalized.
6328                break;
6329        }
6330
6331        // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6332        throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6333                + "from state [" + currentState + "]");
6334    }
6335
6336    @Override
6337    public void setProfileEnabled(ComponentName who) {
6338        if (!mHasFeature) {
6339            return;
6340        }
6341        Preconditions.checkNotNull(who, "ComponentName is null");
6342        synchronized (this) {
6343            // Check if this is the profile owner who is calling
6344            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6345            final int userId = UserHandle.getCallingUserId();
6346            enforceManagedProfile(userId, "enable the profile");
6347            // Check if the profile is already enabled.
6348            UserInfo managedProfile = getUserInfo(userId);
6349            if (managedProfile.isEnabled()) {
6350                Slog.e(LOG_TAG,
6351                        "setProfileEnabled is called when the profile is already enabled");
6352                return;
6353            }
6354            long id = mInjector.binderClearCallingIdentity();
6355            try {
6356                mUserManager.setUserEnabled(userId);
6357                UserInfo parent = mUserManager.getProfileParent(userId);
6358                Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6359                intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6360                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6361                        Intent.FLAG_RECEIVER_FOREGROUND);
6362                mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6363            } finally {
6364                mInjector.binderRestoreCallingIdentity(id);
6365            }
6366        }
6367    }
6368
6369    @Override
6370    public void setProfileName(ComponentName who, String profileName) {
6371        Preconditions.checkNotNull(who, "ComponentName is null");
6372        int userId = UserHandle.getCallingUserId();
6373        // Check if this is the profile owner (includes device owner).
6374        getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6375
6376        long id = mInjector.binderClearCallingIdentity();
6377        try {
6378            mUserManager.setUserName(userId, profileName);
6379        } finally {
6380            mInjector.binderRestoreCallingIdentity(id);
6381        }
6382    }
6383
6384    @Override
6385    public ComponentName getProfileOwner(int userHandle) {
6386        if (!mHasFeature) {
6387            return null;
6388        }
6389
6390        synchronized (this) {
6391            return mOwners.getProfileOwnerComponent(userHandle);
6392        }
6393    }
6394
6395    // Returns the active profile owner for this user or null if the current user has no
6396    // profile owner.
6397    @VisibleForTesting
6398    ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6399        ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6400        if (profileOwner == null) {
6401            return null;
6402        }
6403        DevicePolicyData policy = getUserData(userHandle);
6404        final int n = policy.mAdminList.size();
6405        for (int i = 0; i < n; i++) {
6406            ActiveAdmin admin = policy.mAdminList.get(i);
6407            if (profileOwner.equals(admin.info.getComponent())) {
6408                return admin;
6409            }
6410        }
6411        return null;
6412    }
6413
6414    @Override
6415    public String getProfileOwnerName(int userHandle) {
6416        if (!mHasFeature) {
6417            return null;
6418        }
6419        enforceManageUsers();
6420        ComponentName profileOwner = getProfileOwner(userHandle);
6421        if (profileOwner == null) {
6422            return null;
6423        }
6424        return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6425    }
6426
6427    /**
6428     * Canonical name for a given package.
6429     */
6430    private String getApplicationLabel(String packageName, int userHandle) {
6431        long token = mInjector.binderClearCallingIdentity();
6432        try {
6433            final Context userContext;
6434            try {
6435                UserHandle handle = new UserHandle(userHandle);
6436                userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6437            } catch (PackageManager.NameNotFoundException nnfe) {
6438                Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6439                return null;
6440            }
6441            ApplicationInfo appInfo = userContext.getApplicationInfo();
6442            CharSequence result = null;
6443            if (appInfo != null) {
6444                PackageManager pm = userContext.getPackageManager();
6445                result = pm.getApplicationLabel(appInfo);
6446            }
6447            return result != null ? result.toString() : null;
6448        } finally {
6449            mInjector.binderRestoreCallingIdentity(token);
6450        }
6451    }
6452
6453    /**
6454     * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6455     * permission.
6456     * The profile owner can only be set before the user setup phase has completed,
6457     * except for:
6458     * - SYSTEM_UID
6459     * - adb if there are no accounts. (But see {@link #hasIncompatibleAccountsLocked})
6460     */
6461    private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle) {
6462        UserInfo info = getUserInfo(userHandle);
6463        if (info == null) {
6464            // User doesn't exist.
6465            throw new IllegalArgumentException(
6466                    "Attempted to set profile owner for invalid userId: " + userHandle);
6467        }
6468        if (info.isGuest()) {
6469            throw new IllegalStateException("Cannot set a profile owner on a guest");
6470        }
6471        if (mOwners.hasProfileOwner(userHandle)) {
6472            throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6473                    + "is already set.");
6474        }
6475        if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6476            throw new IllegalStateException("Trying to set the profile owner, but the user "
6477                    + "already has a device owner.");
6478        }
6479        if (isAdb()) {
6480            if ((mIsWatch || hasUserSetupCompleted(userHandle))
6481                    && hasIncompatibleAccountsLocked(userHandle, owner)) {
6482                throw new IllegalStateException("Not allowed to set the profile owner because "
6483                        + "there are already some accounts on the profile");
6484            }
6485            return;
6486        }
6487        enforceCanManageProfileAndDeviceOwners();
6488        if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
6489            throw new IllegalStateException("Cannot set the profile owner on a user which is "
6490                    + "already set-up");
6491        }
6492    }
6493
6494    /**
6495     * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6496     * permission.
6497     */
6498    private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId) {
6499        if (!isAdb()) {
6500            enforceCanManageProfileAndDeviceOwners();
6501        }
6502
6503        final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb());
6504        switch (code) {
6505            case CODE_OK:
6506                return;
6507            case CODE_HAS_DEVICE_OWNER:
6508                throw new IllegalStateException(
6509                        "Trying to set the device owner, but device owner is already set.");
6510            case CODE_USER_HAS_PROFILE_OWNER:
6511                throw new IllegalStateException("Trying to set the device owner, but the user "
6512                        + "already has a profile owner.");
6513            case CODE_USER_NOT_RUNNING:
6514                throw new IllegalStateException("User not running: " + userId);
6515            case CODE_NOT_SYSTEM_USER:
6516                throw new IllegalStateException("User is not system user");
6517            case CODE_USER_SETUP_COMPLETED:
6518                throw new IllegalStateException(
6519                        "Cannot set the device owner if the device is already set-up");
6520            case CODE_NONSYSTEM_USER_EXISTS:
6521                throw new IllegalStateException("Not allowed to set the device owner because there "
6522                        + "are already several users on the device");
6523            case CODE_ACCOUNTS_NOT_EMPTY:
6524                throw new IllegalStateException("Not allowed to set the device owner because there "
6525                        + "are already some accounts on the device");
6526            case CODE_HAS_PAIRED:
6527                throw new IllegalStateException("Not allowed to set the device owner because this "
6528                        + "device has already paired");
6529            default:
6530                throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6531        }
6532    }
6533
6534    private void enforceUserUnlocked(int userId) {
6535        // Since we're doing this operation on behalf of an app, we only
6536        // want to use the actual "unlocked" state.
6537        Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6538                "User must be running and unlocked");
6539    }
6540
6541    private void enforceManageUsers() {
6542        final int callingUid = mInjector.binderGetCallingUid();
6543        if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6544            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6545        }
6546    }
6547
6548    private void enforceFullCrossUsersPermission(int userHandle) {
6549        enforceSystemUserOrPermission(userHandle,
6550                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6551    }
6552
6553    private void enforceCrossUsersPermission(int userHandle) {
6554        enforceSystemUserOrPermission(userHandle,
6555                android.Manifest.permission.INTERACT_ACROSS_USERS);
6556    }
6557
6558    private void enforceSystemUserOrPermission(int userHandle, String permission) {
6559        if (userHandle < 0) {
6560            throw new IllegalArgumentException("Invalid userId " + userHandle);
6561        }
6562        final int callingUid = mInjector.binderGetCallingUid();
6563        if (userHandle == UserHandle.getUserId(callingUid)) {
6564            return;
6565        }
6566        if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6567            mContext.enforceCallingOrSelfPermission(permission,
6568                    "Must be system or have " + permission + " permission");
6569        }
6570    }
6571
6572    private void enforceManagedProfile(int userHandle, String message) {
6573        if(!isManagedProfile(userHandle)) {
6574            throw new SecurityException("You can not " + message + " outside a managed profile.");
6575        }
6576    }
6577
6578    private void enforceNotManagedProfile(int userHandle, String message) {
6579        if(isManagedProfile(userHandle)) {
6580            throw new SecurityException("You can not " + message + " for a managed profile.");
6581        }
6582    }
6583
6584    private void enforceSystemUid() {
6585        if (!isCallerWithSystemUid()) {
6586            throw new SecurityException("Only the system can call this method.");
6587        }
6588    }
6589
6590    private void ensureCallerPackage(@Nullable String packageName) {
6591        if (packageName == null) {
6592            Preconditions.checkState(isCallerWithSystemUid(),
6593                    "Only caller can omit package name");
6594        } else {
6595            final int callingUid = mInjector.binderGetCallingUid();
6596            final int userId = mInjector.userHandleGetCallingUserId();
6597            try {
6598                final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6599                        packageName, 0, userId);
6600                Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6601            } catch (RemoteException e) {
6602                // Shouldn't happen
6603            }
6604        }
6605    }
6606
6607    private boolean isCallerWithSystemUid() {
6608        return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6609    }
6610
6611    private int getProfileParentId(int userHandle) {
6612        final long ident = mInjector.binderClearCallingIdentity();
6613        try {
6614            UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6615            return parentUser != null ? parentUser.id : userHandle;
6616        } finally {
6617            mInjector.binderRestoreCallingIdentity(ident);
6618        }
6619    }
6620
6621    private int getCredentialOwner(int userHandle, boolean parent) {
6622        final long ident = mInjector.binderClearCallingIdentity();
6623        try {
6624            if (parent) {
6625                UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6626                if (parentProfile != null) {
6627                    userHandle = parentProfile.id;
6628                }
6629            }
6630            return mUserManager.getCredentialOwnerProfile(userHandle);
6631        } finally {
6632            mInjector.binderRestoreCallingIdentity(ident);
6633        }
6634    }
6635
6636    private boolean isManagedProfile(int userHandle) {
6637        return getUserInfo(userHandle).isManagedProfile();
6638    }
6639
6640    private void enableIfNecessary(String packageName, int userId) {
6641        try {
6642            ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6643                    PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6644                    userId);
6645            if (ai.enabledSetting
6646                    == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6647                mIPackageManager.setApplicationEnabledSetting(packageName,
6648                        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6649                        PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6650            }
6651        } catch (RemoteException e) {
6652        }
6653    }
6654
6655    @Override
6656    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6657        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6658                != PackageManager.PERMISSION_GRANTED) {
6659
6660            pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6661                    + mInjector.binderGetCallingPid()
6662                    + ", uid=" + mInjector.binderGetCallingUid());
6663            return;
6664        }
6665
6666        synchronized (this) {
6667            pw.println("Current Device Policy Manager state:");
6668            mOwners.dump("  ", pw);
6669            int userCount = mUserData.size();
6670            for (int u = 0; u < userCount; u++) {
6671                DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6672                pw.println();
6673                pw.println("  Enabled Device Admins (User " + policy.mUserHandle
6674                        + ", provisioningState: " + policy.mUserProvisioningState + "):");
6675                final int N = policy.mAdminList.size();
6676                for (int i=0; i<N; i++) {
6677                    ActiveAdmin ap = policy.mAdminList.get(i);
6678                    if (ap != null) {
6679                        pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
6680                                pw.println(":");
6681                        ap.dump("      ", pw);
6682                    }
6683                }
6684                if (!policy.mRemovingAdmins.isEmpty()) {
6685                    pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
6686                            + policy.mRemovingAdmins);
6687                }
6688
6689                pw.println(" ");
6690                pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
6691            }
6692            pw.println();
6693            pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6694        }
6695    }
6696
6697    private String getEncryptionStatusName(int encryptionStatus) {
6698        switch (encryptionStatus) {
6699            case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6700                return "inactive";
6701            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6702                return "block default key";
6703            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6704                return "block";
6705            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6706                return "per-user";
6707            case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6708                return "unsupported";
6709            case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6710                return "activating";
6711            default:
6712                return "unknown";
6713        }
6714    }
6715
6716    @Override
6717    public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6718            ComponentName activity) {
6719        Preconditions.checkNotNull(who, "ComponentName is null");
6720        final int userHandle = UserHandle.getCallingUserId();
6721        synchronized (this) {
6722            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6723
6724            long id = mInjector.binderClearCallingIdentity();
6725            try {
6726                mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6727            } catch (RemoteException re) {
6728                // Shouldn't happen
6729            } finally {
6730                mInjector.binderRestoreCallingIdentity(id);
6731            }
6732        }
6733    }
6734
6735    @Override
6736    public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6737        Preconditions.checkNotNull(who, "ComponentName is null");
6738        final int userHandle = UserHandle.getCallingUserId();
6739        synchronized (this) {
6740            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6741
6742            long id = mInjector.binderClearCallingIdentity();
6743            try {
6744                mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6745            } catch (RemoteException re) {
6746                // Shouldn't happen
6747            } finally {
6748                mInjector.binderRestoreCallingIdentity(id);
6749            }
6750        }
6751    }
6752
6753    @Override
6754    public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6755            String packageName) {
6756        Preconditions.checkNotNull(admin, "ComponentName is null");
6757
6758        final int userHandle = mInjector.userHandleGetCallingUserId();
6759        synchronized (this) {
6760            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6761            if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6762                return false;
6763            }
6764            DevicePolicyData policy = getUserData(userHandle);
6765            policy.mApplicationRestrictionsManagingPackage = packageName;
6766            saveSettingsLocked(userHandle);
6767            return true;
6768        }
6769    }
6770
6771    @Override
6772    public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6773        Preconditions.checkNotNull(admin, "ComponentName is null");
6774
6775        final int userHandle = mInjector.userHandleGetCallingUserId();
6776        synchronized (this) {
6777            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6778            DevicePolicyData policy = getUserData(userHandle);
6779            return policy.mApplicationRestrictionsManagingPackage;
6780        }
6781    }
6782
6783    @Override
6784    public boolean isCallerApplicationRestrictionsManagingPackage() {
6785        final int callingUid = mInjector.binderGetCallingUid();
6786        final int userHandle = UserHandle.getUserId(callingUid);
6787        synchronized (this) {
6788            final DevicePolicyData policy = getUserData(userHandle);
6789            if (policy.mApplicationRestrictionsManagingPackage == null) {
6790                return false;
6791            }
6792
6793            try {
6794                int uid = mContext.getPackageManager().getPackageUidAsUser(
6795                        policy.mApplicationRestrictionsManagingPackage, userHandle);
6796                return uid == callingUid;
6797            } catch (NameNotFoundException e) {
6798                return false;
6799            }
6800        }
6801    }
6802
6803    private void enforceCanManageApplicationRestrictions(ComponentName who) {
6804        if (who != null) {
6805            synchronized (this) {
6806                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6807            }
6808        } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6809            throw new SecurityException(
6810                    "No admin component given, and caller cannot manage application restrictions "
6811                    + "for other apps.");
6812        }
6813    }
6814
6815    @Override
6816    public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6817        enforceCanManageApplicationRestrictions(who);
6818
6819        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6820        final long id = mInjector.binderClearCallingIdentity();
6821        try {
6822            mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6823        } finally {
6824            mInjector.binderRestoreCallingIdentity(id);
6825        }
6826    }
6827
6828    @Override
6829    public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6830            PersistableBundle args, boolean parent) {
6831        if (!mHasFeature) {
6832            return;
6833        }
6834        Preconditions.checkNotNull(admin, "admin is null");
6835        Preconditions.checkNotNull(agent, "agent is null");
6836        final int userHandle = UserHandle.getCallingUserId();
6837        synchronized (this) {
6838            ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6839                    DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6840            ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6841            saveSettingsLocked(userHandle);
6842        }
6843    }
6844
6845    @Override
6846    public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6847            ComponentName agent, int userHandle, boolean parent) {
6848        if (!mHasFeature) {
6849            return null;
6850        }
6851        Preconditions.checkNotNull(agent, "agent null");
6852        enforceFullCrossUsersPermission(userHandle);
6853
6854        synchronized (this) {
6855            final String componentName = agent.flattenToString();
6856            if (admin != null) {
6857                final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6858                if (ap == null) return null;
6859                TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6860                if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6861                List<PersistableBundle> result = new ArrayList<>();
6862                result.add(trustAgentInfo.options);
6863                return result;
6864            }
6865
6866            // Return strictest policy for this user and profiles that are visible from this user.
6867            List<PersistableBundle> result = null;
6868            // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6869            // of the options. If any admin doesn't have options, discard options for the rest
6870            // and return null.
6871            List<ActiveAdmin> admins =
6872                    getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6873            boolean allAdminsHaveOptions = true;
6874            final int N = admins.size();
6875            for (int i = 0; i < N; i++) {
6876                final ActiveAdmin active = admins.get(i);
6877
6878                final boolean disablesTrust = (active.disabledKeyguardFeatures
6879                        & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6880                final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6881                if (info != null && info.options != null && !info.options.isEmpty()) {
6882                    if (disablesTrust) {
6883                        if (result == null) {
6884                            result = new ArrayList<>();
6885                        }
6886                        result.add(info.options);
6887                    } else {
6888                        Log.w(LOG_TAG, "Ignoring admin " + active.info
6889                                + " because it has trust options but doesn't declare "
6890                                + "KEYGUARD_DISABLE_TRUST_AGENTS");
6891                    }
6892                } else if (disablesTrust) {
6893                    allAdminsHaveOptions = false;
6894                    break;
6895                }
6896            }
6897            return allAdminsHaveOptions ? result : null;
6898        }
6899    }
6900
6901    @Override
6902    public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6903        Preconditions.checkNotNull(who, "ComponentName is null");
6904        synchronized (this) {
6905            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6906
6907            int userHandle = UserHandle.getCallingUserId();
6908            DevicePolicyData userData = getUserData(userHandle);
6909            userData.mRestrictionsProvider = permissionProvider;
6910            saveSettingsLocked(userHandle);
6911        }
6912    }
6913
6914    @Override
6915    public ComponentName getRestrictionsProvider(int userHandle) {
6916        synchronized (this) {
6917            if (!isCallerWithSystemUid()) {
6918                throw new SecurityException("Only the system can query the permission provider");
6919            }
6920            DevicePolicyData userData = getUserData(userHandle);
6921            return userData != null ? userData.mRestrictionsProvider : null;
6922        }
6923    }
6924
6925    @Override
6926    public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6927        Preconditions.checkNotNull(who, "ComponentName is null");
6928        int callingUserId = UserHandle.getCallingUserId();
6929        synchronized (this) {
6930            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6931
6932            long id = mInjector.binderClearCallingIdentity();
6933            try {
6934                UserInfo parent = mUserManager.getProfileParent(callingUserId);
6935                if (parent == null) {
6936                    Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6937                            + "parent");
6938                    return;
6939                }
6940                if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6941                    mIPackageManager.addCrossProfileIntentFilter(
6942                            filter, who.getPackageName(), callingUserId, parent.id, 0);
6943                }
6944                if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6945                    mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6946                            parent.id, callingUserId, 0);
6947                }
6948            } catch (RemoteException re) {
6949                // Shouldn't happen
6950            } finally {
6951                mInjector.binderRestoreCallingIdentity(id);
6952            }
6953        }
6954    }
6955
6956    @Override
6957    public void clearCrossProfileIntentFilters(ComponentName who) {
6958        Preconditions.checkNotNull(who, "ComponentName is null");
6959        int callingUserId = UserHandle.getCallingUserId();
6960        synchronized (this) {
6961            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6962            long id = mInjector.binderClearCallingIdentity();
6963            try {
6964                UserInfo parent = mUserManager.getProfileParent(callingUserId);
6965                if (parent == null) {
6966                    Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6967                            + "parent");
6968                    return;
6969                }
6970                // Removing those that go from the managed profile to the parent.
6971                mIPackageManager.clearCrossProfileIntentFilters(
6972                        callingUserId, who.getPackageName());
6973                // And those that go from the parent to the managed profile.
6974                // If we want to support multiple managed profiles, we will have to only remove
6975                // those that have callingUserId as their target.
6976                mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6977            } catch (RemoteException re) {
6978                // Shouldn't happen
6979            } finally {
6980                mInjector.binderRestoreCallingIdentity(id);
6981            }
6982        }
6983    }
6984
6985    /**
6986     * @return true if all packages in enabledPackages are either in the list
6987     * permittedList or are a system app.
6988     */
6989    private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6990            List<String> permittedList, int userIdToCheck) {
6991        long id = mInjector.binderClearCallingIdentity();
6992        try {
6993            // If we have an enabled packages list for a managed profile the packages
6994            // we should check are installed for the parent user.
6995            UserInfo user = getUserInfo(userIdToCheck);
6996            if (user.isManagedProfile()) {
6997                userIdToCheck = user.profileGroupId;
6998            }
6999
7000            for (String enabledPackage : enabledPackages) {
7001                boolean systemService = false;
7002                try {
7003                    ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
7004                            enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
7005                    systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7006                } catch (RemoteException e) {
7007                    Log.i(LOG_TAG, "Can't talk to package managed", e);
7008                }
7009                if (!systemService && !permittedList.contains(enabledPackage)) {
7010                    return false;
7011                }
7012            }
7013        } finally {
7014            mInjector.binderRestoreCallingIdentity(id);
7015        }
7016        return true;
7017    }
7018
7019    private AccessibilityManager getAccessibilityManagerForUser(int userId) {
7020        // Not using AccessibilityManager.getInstance because that guesses
7021        // at the user you require based on callingUid and caches for a given
7022        // process.
7023        IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
7024        IAccessibilityManager service = iBinder == null
7025                ? null : IAccessibilityManager.Stub.asInterface(iBinder);
7026        return new AccessibilityManager(mContext, service, userId);
7027    }
7028
7029    @Override
7030    public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
7031        if (!mHasFeature) {
7032            return false;
7033        }
7034        Preconditions.checkNotNull(who, "ComponentName is null");
7035
7036        if (packageList != null) {
7037            int userId = UserHandle.getCallingUserId();
7038            List<AccessibilityServiceInfo> enabledServices = null;
7039            long id = mInjector.binderClearCallingIdentity();
7040            try {
7041                UserInfo user = getUserInfo(userId);
7042                if (user.isManagedProfile()) {
7043                    userId = user.profileGroupId;
7044                }
7045                AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
7046                enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
7047                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
7048            } finally {
7049                mInjector.binderRestoreCallingIdentity(id);
7050            }
7051
7052            if (enabledServices != null) {
7053                List<String> enabledPackages = new ArrayList<String>();
7054                for (AccessibilityServiceInfo service : enabledServices) {
7055                    enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
7056                }
7057                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7058                        userId)) {
7059                    Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7060                            + "because it contains already enabled accesibility services.");
7061                    return false;
7062                }
7063            }
7064        }
7065
7066        synchronized (this) {
7067            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7068                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7069            admin.permittedAccessiblityServices = packageList;
7070            saveSettingsLocked(UserHandle.getCallingUserId());
7071        }
7072        return true;
7073    }
7074
7075    @Override
7076    public List getPermittedAccessibilityServices(ComponentName who) {
7077        if (!mHasFeature) {
7078            return null;
7079        }
7080        Preconditions.checkNotNull(who, "ComponentName is null");
7081
7082        synchronized (this) {
7083            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7084                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7085            return admin.permittedAccessiblityServices;
7086        }
7087    }
7088
7089    @Override
7090    public List getPermittedAccessibilityServicesForUser(int userId) {
7091        if (!mHasFeature) {
7092            return null;
7093        }
7094        synchronized (this) {
7095            List<String> result = null;
7096            // If we have multiple profiles we return the intersection of the
7097            // permitted lists. This can happen in cases where we have a device
7098            // and profile owner.
7099            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7100            for (int profileId : profileIds) {
7101                // Just loop though all admins, only device or profiles
7102                // owners can have permitted lists set.
7103                DevicePolicyData policy = getUserDataUnchecked(profileId);
7104                final int N = policy.mAdminList.size();
7105                for (int j = 0; j < N; j++) {
7106                    ActiveAdmin admin = policy.mAdminList.get(j);
7107                    List<String> fromAdmin = admin.permittedAccessiblityServices;
7108                    if (fromAdmin != null) {
7109                        if (result == null) {
7110                            result = new ArrayList<>(fromAdmin);
7111                        } else {
7112                            result.retainAll(fromAdmin);
7113                        }
7114                    }
7115                }
7116            }
7117
7118            // If we have a permitted list add all system accessibility services.
7119            if (result != null) {
7120                long id = mInjector.binderClearCallingIdentity();
7121                try {
7122                    UserInfo user = getUserInfo(userId);
7123                    if (user.isManagedProfile()) {
7124                        userId = user.profileGroupId;
7125                    }
7126                    AccessibilityManager accessibilityManager =
7127                            getAccessibilityManagerForUser(userId);
7128                    List<AccessibilityServiceInfo> installedServices =
7129                            accessibilityManager.getInstalledAccessibilityServiceList();
7130
7131                    if (installedServices != null) {
7132                        for (AccessibilityServiceInfo service : installedServices) {
7133                            ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7134                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7135                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7136                                result.add(serviceInfo.packageName);
7137                            }
7138                        }
7139                    }
7140                } finally {
7141                    mInjector.binderRestoreCallingIdentity(id);
7142                }
7143            }
7144
7145            return result;
7146        }
7147    }
7148
7149    @Override
7150    public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7151            int userHandle) {
7152        if (!mHasFeature) {
7153            return true;
7154        }
7155        Preconditions.checkNotNull(who, "ComponentName is null");
7156        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7157        if (!isCallerWithSystemUid()){
7158            throw new SecurityException(
7159                    "Only the system can query if an accessibility service is disabled by admin");
7160        }
7161        synchronized (this) {
7162            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7163            if (admin == null) {
7164                return false;
7165            }
7166            if (admin.permittedAccessiblityServices == null) {
7167                return true;
7168            }
7169            return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7170                    admin.permittedAccessiblityServices, userHandle);
7171        }
7172    }
7173
7174    private boolean checkCallerIsCurrentUserOrProfile() {
7175        int callingUserId = UserHandle.getCallingUserId();
7176        long token = mInjector.binderClearCallingIdentity();
7177        try {
7178            UserInfo currentUser;
7179            UserInfo callingUser = getUserInfo(callingUserId);
7180            try {
7181                currentUser = mInjector.getIActivityManager().getCurrentUser();
7182            } catch (RemoteException e) {
7183                Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7184                return false;
7185            }
7186
7187            if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7188                Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7189                        + "of a user that isn't the foreground user.");
7190                return false;
7191            }
7192            if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7193                Slog.e(LOG_TAG, "Cannot set permitted input methods "
7194                        + "of a user that isn't the foreground user.");
7195                return false;
7196            }
7197        } finally {
7198            mInjector.binderRestoreCallingIdentity(token);
7199        }
7200        return true;
7201    }
7202
7203    @Override
7204    public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7205        if (!mHasFeature) {
7206            return false;
7207        }
7208        Preconditions.checkNotNull(who, "ComponentName is null");
7209
7210        // TODO When InputMethodManager supports per user calls remove
7211        //      this restriction.
7212        if (!checkCallerIsCurrentUserOrProfile()) {
7213            return false;
7214        }
7215
7216        if (packageList != null) {
7217            // InputMethodManager fetches input methods for current user.
7218            // So this can only be set when calling user is the current user
7219            // or parent is current user in case of managed profiles.
7220            InputMethodManager inputMethodManager =
7221                    mContext.getSystemService(InputMethodManager.class);
7222            List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7223
7224            if (enabledImes != null) {
7225                List<String> enabledPackages = new ArrayList<String>();
7226                for (InputMethodInfo ime : enabledImes) {
7227                    enabledPackages.add(ime.getPackageName());
7228                }
7229                if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7230                        mInjector.binderGetCallingUserHandle().getIdentifier())) {
7231                    Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7232                            + "because it contains already enabled input method.");
7233                    return false;
7234                }
7235            }
7236        }
7237
7238        synchronized (this) {
7239            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7240                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7241            admin.permittedInputMethods = packageList;
7242            saveSettingsLocked(UserHandle.getCallingUserId());
7243        }
7244        return true;
7245    }
7246
7247    @Override
7248    public List getPermittedInputMethods(ComponentName who) {
7249        if (!mHasFeature) {
7250            return null;
7251        }
7252        Preconditions.checkNotNull(who, "ComponentName is null");
7253
7254        synchronized (this) {
7255            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7256                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7257            return admin.permittedInputMethods;
7258        }
7259    }
7260
7261    @Override
7262    public List getPermittedInputMethodsForCurrentUser() {
7263        UserInfo currentUser;
7264        try {
7265            currentUser = mInjector.getIActivityManager().getCurrentUser();
7266        } catch (RemoteException e) {
7267            Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7268            // Activity managed is dead, just allow all IMEs
7269            return null;
7270        }
7271
7272        int userId = currentUser.id;
7273        synchronized (this) {
7274            List<String> result = null;
7275            // If we have multiple profiles we return the intersection of the
7276            // permitted lists. This can happen in cases where we have a device
7277            // and profile owner.
7278            int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7279            for (int profileId : profileIds) {
7280                // Just loop though all admins, only device or profiles
7281                // owners can have permitted lists set.
7282                DevicePolicyData policy = getUserDataUnchecked(profileId);
7283                final int N = policy.mAdminList.size();
7284                for (int j = 0; j < N; j++) {
7285                    ActiveAdmin admin = policy.mAdminList.get(j);
7286                    List<String> fromAdmin = admin.permittedInputMethods;
7287                    if (fromAdmin != null) {
7288                        if (result == null) {
7289                            result = new ArrayList<String>(fromAdmin);
7290                        } else {
7291                            result.retainAll(fromAdmin);
7292                        }
7293                    }
7294                }
7295            }
7296
7297            // If we have a permitted list add all system input methods.
7298            if (result != null) {
7299                InputMethodManager inputMethodManager =
7300                        mContext.getSystemService(InputMethodManager.class);
7301                List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7302                long id = mInjector.binderClearCallingIdentity();
7303                try {
7304                    if (imes != null) {
7305                        for (InputMethodInfo ime : imes) {
7306                            ServiceInfo serviceInfo = ime.getServiceInfo();
7307                            ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7308                            if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7309                                result.add(serviceInfo.packageName);
7310                            }
7311                        }
7312                    }
7313                } finally {
7314                    mInjector.binderRestoreCallingIdentity(id);
7315                }
7316            }
7317            return result;
7318        }
7319    }
7320
7321    @Override
7322    public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7323            int userHandle) {
7324        if (!mHasFeature) {
7325            return true;
7326        }
7327        Preconditions.checkNotNull(who, "ComponentName is null");
7328        Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7329        if (!isCallerWithSystemUid()) {
7330            throw new SecurityException(
7331                    "Only the system can query if an input method is disabled by admin");
7332        }
7333        synchronized (this) {
7334            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7335            if (admin == null) {
7336                return false;
7337            }
7338            if (admin.permittedInputMethods == null) {
7339                return true;
7340            }
7341            return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7342                    admin.permittedInputMethods, userHandle);
7343        }
7344    }
7345
7346    private void sendAdminEnabledBroadcastLocked(int userHandle) {
7347        DevicePolicyData policyData = getUserData(userHandle);
7348        if (policyData.mAdminBroadcastPending) {
7349            // Send the initialization data to profile owner and delete the data
7350            ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7351            if (admin != null) {
7352                PersistableBundle initBundle = policyData.mInitBundle;
7353                sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7354                        initBundle == null ? null : new Bundle(initBundle), null);
7355            }
7356            policyData.mInitBundle = null;
7357            policyData.mAdminBroadcastPending = false;
7358            saveSettingsLocked(userHandle);
7359        }
7360    }
7361
7362    @Override
7363    public UserHandle createAndManageUser(ComponentName admin, String name,
7364            ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7365        Preconditions.checkNotNull(admin, "admin is null");
7366        Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7367        if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7368            throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7369                    + admin + " are not in the same package");
7370        }
7371        // Only allow the system user to use this method
7372        if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7373            throw new SecurityException("createAndManageUser was called from non-system user");
7374        }
7375        if (!mInjector.userManagerIsSplitSystemUser()
7376                && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7377            throw new IllegalArgumentException(
7378                    "Ephemeral users are only supported on systems with a split system user.");
7379        }
7380        // Create user.
7381        UserHandle user = null;
7382        synchronized (this) {
7383            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7384
7385            final long id = mInjector.binderClearCallingIdentity();
7386            try {
7387                int userInfoFlags = 0;
7388                if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7389                    userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7390                }
7391                UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7392                        userInfoFlags);
7393                if (userInfo != null) {
7394                    user = userInfo.getUserHandle();
7395                }
7396            } finally {
7397                mInjector.binderRestoreCallingIdentity(id);
7398            }
7399        }
7400        if (user == null) {
7401            return null;
7402        }
7403        // Set admin.
7404        final long id = mInjector.binderClearCallingIdentity();
7405        try {
7406            final String adminPkg = admin.getPackageName();
7407
7408            final int userHandle = user.getIdentifier();
7409            try {
7410                // Install the profile owner if not present.
7411                if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7412                    mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7413                }
7414            } catch (RemoteException e) {
7415                Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7416                        + "removing created user", e);
7417                mUserManager.removeUser(user.getIdentifier());
7418                return null;
7419            }
7420
7421            setActiveAdmin(profileOwner, true, userHandle);
7422            // User is not started yet, the broadcast by setActiveAdmin will not be received.
7423            // So we store adminExtras for broadcasting when the user starts for first time.
7424            synchronized(this) {
7425                DevicePolicyData policyData = getUserData(userHandle);
7426                policyData.mInitBundle = adminExtras;
7427                policyData.mAdminBroadcastPending = true;
7428                saveSettingsLocked(userHandle);
7429            }
7430            final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7431            setProfileOwner(profileOwner, ownerName, userHandle);
7432
7433            if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7434                Settings.Secure.putIntForUser(mContext.getContentResolver(),
7435                        Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7436            }
7437
7438            return user;
7439        } finally {
7440            mInjector.binderRestoreCallingIdentity(id);
7441        }
7442    }
7443
7444    @Override
7445    public boolean removeUser(ComponentName who, UserHandle userHandle) {
7446        Preconditions.checkNotNull(who, "ComponentName is null");
7447        UserHandle callingUserHandle = mInjector.binderGetCallingUserHandle();
7448        synchronized (this) {
7449            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7450        }
7451        final long id = mInjector.binderClearCallingIdentity();
7452        try {
7453            int restrictionSource = mUserManager.getUserRestrictionSource(
7454                    UserManager.DISALLOW_REMOVE_USER, callingUserHandle);
7455            if (restrictionSource != UserManager.RESTRICTION_NOT_SET
7456                    && restrictionSource != UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) {
7457                Log.w(LOG_TAG, "The device owner cannot remove a user because "
7458                        + "DISALLOW_REMOVE_USER is enabled, and was not set by the device "
7459                        + "owner");
7460                return false;
7461            }
7462            return mUserManagerInternal.removeUserEvenWhenDisallowed(
7463                    userHandle.getIdentifier());
7464        } finally {
7465            mInjector.binderRestoreCallingIdentity(id);
7466        }
7467    }
7468
7469    @Override
7470    public boolean switchUser(ComponentName who, UserHandle userHandle) {
7471        Preconditions.checkNotNull(who, "ComponentName is null");
7472        synchronized (this) {
7473            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7474
7475            long id = mInjector.binderClearCallingIdentity();
7476            try {
7477                int userId = UserHandle.USER_SYSTEM;
7478                if (userHandle != null) {
7479                    userId = userHandle.getIdentifier();
7480                }
7481                return mInjector.getIActivityManager().switchUser(userId);
7482            } catch (RemoteException e) {
7483                Log.e(LOG_TAG, "Couldn't switch user", e);
7484                return false;
7485            } finally {
7486                mInjector.binderRestoreCallingIdentity(id);
7487            }
7488        }
7489    }
7490
7491    @Override
7492    public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7493        enforceCanManageApplicationRestrictions(who);
7494
7495        final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7496        final long id = mInjector.binderClearCallingIdentity();
7497        try {
7498           Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7499           // if no restrictions were saved, mUserManager.getApplicationRestrictions
7500           // returns null, but DPM method should return an empty Bundle as per JavaDoc
7501           return bundle != null ? bundle : Bundle.EMPTY;
7502        } finally {
7503            mInjector.binderRestoreCallingIdentity(id);
7504        }
7505    }
7506
7507    @Override
7508    public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7509            boolean suspended) {
7510        Preconditions.checkNotNull(who, "ComponentName is null");
7511        int callingUserId = UserHandle.getCallingUserId();
7512        synchronized (this) {
7513            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7514
7515            long id = mInjector.binderClearCallingIdentity();
7516            try {
7517                return mIPackageManager.setPackagesSuspendedAsUser(
7518                        packageNames, suspended, callingUserId);
7519            } catch (RemoteException re) {
7520                // Shouldn't happen.
7521                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7522            } finally {
7523                mInjector.binderRestoreCallingIdentity(id);
7524            }
7525            return packageNames;
7526        }
7527    }
7528
7529    @Override
7530    public boolean isPackageSuspended(ComponentName who, String packageName) {
7531        Preconditions.checkNotNull(who, "ComponentName is null");
7532        int callingUserId = UserHandle.getCallingUserId();
7533        synchronized (this) {
7534            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7535
7536            long id = mInjector.binderClearCallingIdentity();
7537            try {
7538                return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7539            } catch (RemoteException re) {
7540                // Shouldn't happen.
7541                Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7542            } finally {
7543                mInjector.binderRestoreCallingIdentity(id);
7544            }
7545            return false;
7546        }
7547    }
7548
7549    @Override
7550    public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7551        Preconditions.checkNotNull(who, "ComponentName is null");
7552        if (!UserRestrictionsUtils.isValidRestriction(key)) {
7553            return;
7554        }
7555
7556        final int userHandle = mInjector.userHandleGetCallingUserId();
7557        synchronized (this) {
7558            ActiveAdmin activeAdmin =
7559                    getActiveAdminForCallerLocked(who,
7560                            DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7561            final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7562            if (isDeviceOwner) {
7563                if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7564                    throw new SecurityException("Device owner cannot set user restriction " + key);
7565                }
7566            } else { // profile owner
7567                if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7568                    throw new SecurityException("Profile owner cannot set user restriction " + key);
7569                }
7570            }
7571
7572            // Save the restriction to ActiveAdmin.
7573            activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7574            saveSettingsLocked(userHandle);
7575
7576            pushUserRestrictions(userHandle);
7577
7578            sendChangedNotification(userHandle);
7579        }
7580    }
7581
7582    private void pushUserRestrictions(int userId) {
7583        synchronized (this) {
7584            final Bundle global;
7585            final Bundle local = new Bundle();
7586            if (mOwners.isDeviceOwnerUserId(userId)) {
7587                global = new Bundle();
7588
7589                final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7590                if (deviceOwner == null) {
7591                    return; // Shouldn't happen.
7592                }
7593
7594                UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7595                        global, local);
7596                // DO can disable camera globally.
7597                if (deviceOwner.disableCamera) {
7598                    global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7599                }
7600            } else {
7601                global = null;
7602
7603                ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7604                if (profileOwner != null) {
7605                    UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7606                }
7607            }
7608            // Also merge in *local* camera restriction.
7609            if (getCameraDisabled(/* who= */ null,
7610                    userId, /* mergeDeviceOwnerRestriction= */ false)) {
7611                local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7612            }
7613            mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7614        }
7615    }
7616
7617    @Override
7618    public Bundle getUserRestrictions(ComponentName who) {
7619        if (!mHasFeature) {
7620            return null;
7621        }
7622        Preconditions.checkNotNull(who, "ComponentName is null");
7623        synchronized (this) {
7624            final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7625                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7626            return activeAdmin.userRestrictions;
7627        }
7628    }
7629
7630    @Override
7631    public boolean setApplicationHidden(ComponentName who, String packageName,
7632            boolean hidden) {
7633        Preconditions.checkNotNull(who, "ComponentName is null");
7634        int callingUserId = UserHandle.getCallingUserId();
7635        synchronized (this) {
7636            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7637
7638            long id = mInjector.binderClearCallingIdentity();
7639            try {
7640                return mIPackageManager.setApplicationHiddenSettingAsUser(
7641                        packageName, hidden, callingUserId);
7642            } catch (RemoteException re) {
7643                // shouldn't happen
7644                Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7645            } finally {
7646                mInjector.binderRestoreCallingIdentity(id);
7647            }
7648            return false;
7649        }
7650    }
7651
7652    @Override
7653    public boolean isApplicationHidden(ComponentName who, String packageName) {
7654        Preconditions.checkNotNull(who, "ComponentName is null");
7655        int callingUserId = UserHandle.getCallingUserId();
7656        synchronized (this) {
7657            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7658
7659            long id = mInjector.binderClearCallingIdentity();
7660            try {
7661                return mIPackageManager.getApplicationHiddenSettingAsUser(
7662                        packageName, callingUserId);
7663            } catch (RemoteException re) {
7664                // shouldn't happen
7665                Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7666            } finally {
7667                mInjector.binderRestoreCallingIdentity(id);
7668            }
7669            return false;
7670        }
7671    }
7672
7673    @Override
7674    public void enableSystemApp(ComponentName who, String packageName) {
7675        Preconditions.checkNotNull(who, "ComponentName is null");
7676        synchronized (this) {
7677            // This API can only be called by an active device admin,
7678            // so try to retrieve it to check that the caller is one.
7679            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7680
7681            int userId = UserHandle.getCallingUserId();
7682            long id = mInjector.binderClearCallingIdentity();
7683
7684            try {
7685                if (VERBOSE_LOG) {
7686                    Slog.v(LOG_TAG, "installing " + packageName + " for "
7687                            + userId);
7688                }
7689
7690                int parentUserId = getProfileParentId(userId);
7691                if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7692                    throw new IllegalArgumentException("Only system apps can be enabled this way.");
7693                }
7694
7695                // Install the app.
7696                mIPackageManager.installExistingPackageAsUser(packageName, userId);
7697
7698            } catch (RemoteException re) {
7699                // shouldn't happen
7700                Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7701            } finally {
7702                mInjector.binderRestoreCallingIdentity(id);
7703            }
7704        }
7705    }
7706
7707    @Override
7708    public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7709        Preconditions.checkNotNull(who, "ComponentName is null");
7710        synchronized (this) {
7711            // This API can only be called by an active device admin,
7712            // so try to retrieve it to check that the caller is one.
7713            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7714
7715            int userId = UserHandle.getCallingUserId();
7716            long id = mInjector.binderClearCallingIdentity();
7717
7718            try {
7719                int parentUserId = getProfileParentId(userId);
7720                List<ResolveInfo> activitiesToEnable = mIPackageManager
7721                        .queryIntentActivities(intent,
7722                                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7723                                PackageManager.MATCH_DIRECT_BOOT_AWARE
7724                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7725                                parentUserId)
7726                        .getList();
7727
7728                if (VERBOSE_LOG) {
7729                    Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7730                }
7731                int numberOfAppsInstalled = 0;
7732                if (activitiesToEnable != null) {
7733                    for (ResolveInfo info : activitiesToEnable) {
7734                        if (info.activityInfo != null) {
7735                            String packageName = info.activityInfo.packageName;
7736                            if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7737                                numberOfAppsInstalled++;
7738                                mIPackageManager.installExistingPackageAsUser(packageName, userId);
7739                            } else {
7740                                Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7741                                        + " system app");
7742                            }
7743                        }
7744                    }
7745                }
7746                return numberOfAppsInstalled;
7747            } catch (RemoteException e) {
7748                // shouldn't happen
7749                Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7750                return 0;
7751            } finally {
7752                mInjector.binderRestoreCallingIdentity(id);
7753            }
7754        }
7755    }
7756
7757    private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7758            throws RemoteException {
7759        ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7760                userId);
7761        if (appInfo == null) {
7762            throw new IllegalArgumentException("The application " + packageName +
7763                    " is not present on this device");
7764        }
7765        return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7766    }
7767
7768    @Override
7769    public void setAccountManagementDisabled(ComponentName who, String accountType,
7770            boolean disabled) {
7771        if (!mHasFeature) {
7772            return;
7773        }
7774        Preconditions.checkNotNull(who, "ComponentName is null");
7775        synchronized (this) {
7776            ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7777                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7778            if (disabled) {
7779                ap.accountTypesWithManagementDisabled.add(accountType);
7780            } else {
7781                ap.accountTypesWithManagementDisabled.remove(accountType);
7782            }
7783            saveSettingsLocked(UserHandle.getCallingUserId());
7784        }
7785    }
7786
7787    @Override
7788    public String[] getAccountTypesWithManagementDisabled() {
7789        return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7790    }
7791
7792    @Override
7793    public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7794        enforceFullCrossUsersPermission(userId);
7795        if (!mHasFeature) {
7796            return null;
7797        }
7798        synchronized (this) {
7799            DevicePolicyData policy = getUserData(userId);
7800            final int N = policy.mAdminList.size();
7801            ArraySet<String> resultSet = new ArraySet<>();
7802            for (int i = 0; i < N; i++) {
7803                ActiveAdmin admin = policy.mAdminList.get(i);
7804                resultSet.addAll(admin.accountTypesWithManagementDisabled);
7805            }
7806            return resultSet.toArray(new String[resultSet.size()]);
7807        }
7808    }
7809
7810    @Override
7811    public void setUninstallBlocked(ComponentName who, String packageName,
7812            boolean uninstallBlocked) {
7813        Preconditions.checkNotNull(who, "ComponentName is null");
7814        final int userId = UserHandle.getCallingUserId();
7815        synchronized (this) {
7816            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7817
7818            long id = mInjector.binderClearCallingIdentity();
7819            try {
7820                mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7821            } catch (RemoteException re) {
7822                // Shouldn't happen.
7823                Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7824            } finally {
7825                mInjector.binderRestoreCallingIdentity(id);
7826            }
7827        }
7828    }
7829
7830    @Override
7831    public boolean isUninstallBlocked(ComponentName who, String packageName) {
7832        // This function should return true if and only if the package is blocked by
7833        // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7834        // when the package is a system app, or when it is an active device admin.
7835        final int userId = UserHandle.getCallingUserId();
7836
7837        synchronized (this) {
7838            if (who != null) {
7839                getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7840            }
7841
7842            long id = mInjector.binderClearCallingIdentity();
7843            try {
7844                return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7845            } catch (RemoteException re) {
7846                // Shouldn't happen.
7847                Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7848            } finally {
7849                mInjector.binderRestoreCallingIdentity(id);
7850            }
7851        }
7852        return false;
7853    }
7854
7855    @Override
7856    public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7857        if (!mHasFeature) {
7858            return;
7859        }
7860        Preconditions.checkNotNull(who, "ComponentName is null");
7861        synchronized (this) {
7862            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7863                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7864            if (admin.disableCallerId != disabled) {
7865                admin.disableCallerId = disabled;
7866                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7867            }
7868        }
7869    }
7870
7871    @Override
7872    public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7873        if (!mHasFeature) {
7874            return false;
7875        }
7876        Preconditions.checkNotNull(who, "ComponentName is null");
7877        synchronized (this) {
7878            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7879                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7880            return admin.disableCallerId;
7881        }
7882    }
7883
7884    @Override
7885    public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7886        enforceCrossUsersPermission(userId);
7887        synchronized (this) {
7888            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7889            return (admin != null) ? admin.disableCallerId : false;
7890        }
7891    }
7892
7893    @Override
7894    public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7895        if (!mHasFeature) {
7896            return;
7897        }
7898        Preconditions.checkNotNull(who, "ComponentName is null");
7899        synchronized (this) {
7900            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7901                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7902            if (admin.disableContactsSearch != disabled) {
7903                admin.disableContactsSearch = disabled;
7904                saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7905            }
7906        }
7907    }
7908
7909    @Override
7910    public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7911        if (!mHasFeature) {
7912            return false;
7913        }
7914        Preconditions.checkNotNull(who, "ComponentName is null");
7915        synchronized (this) {
7916            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7917                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7918            return admin.disableContactsSearch;
7919        }
7920    }
7921
7922    @Override
7923    public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7924        enforceCrossUsersPermission(userId);
7925        synchronized (this) {
7926            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7927            return (admin != null) ? admin.disableContactsSearch : false;
7928        }
7929    }
7930
7931    @Override
7932    public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7933            boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7934        final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7935                actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7936        final int callingUserId = UserHandle.getCallingUserId();
7937
7938        final long ident = mInjector.binderClearCallingIdentity();
7939        try {
7940            synchronized (this) {
7941                final int managedUserId = getManagedUserId(callingUserId);
7942                if (managedUserId < 0) {
7943                    return;
7944                }
7945                if (isCrossProfileQuickContactDisabled(managedUserId)) {
7946                    if (VERBOSE_LOG) {
7947                        Log.v(LOG_TAG,
7948                                "Cross-profile contacts access disabled for user " + managedUserId);
7949                    }
7950                    return;
7951                }
7952                ContactsInternal.startQuickContactWithErrorToastForUser(
7953                        mContext, intent, new UserHandle(managedUserId));
7954            }
7955        } finally {
7956            mInjector.binderRestoreCallingIdentity(ident);
7957        }
7958    }
7959
7960    /**
7961     * @return true if cross-profile QuickContact is disabled
7962     */
7963    private boolean isCrossProfileQuickContactDisabled(int userId) {
7964        return getCrossProfileCallerIdDisabledForUser(userId)
7965                && getCrossProfileContactsSearchDisabledForUser(userId);
7966    }
7967
7968    /**
7969     * @return the user ID of the managed user that is linked to the current user, if any.
7970     * Otherwise -1.
7971     */
7972    public int getManagedUserId(int callingUserId) {
7973        if (VERBOSE_LOG) {
7974            Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7975        }
7976
7977        for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7978            if (ui.id == callingUserId || !ui.isManagedProfile()) {
7979                continue; // Caller user self, or not a managed profile.  Skip.
7980            }
7981            if (VERBOSE_LOG) {
7982                Log.v(LOG_TAG, "Managed user=" + ui.id);
7983            }
7984            return ui.id;
7985        }
7986        if (VERBOSE_LOG) {
7987            Log.v(LOG_TAG, "Managed user not found.");
7988        }
7989        return -1;
7990    }
7991
7992    @Override
7993    public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7994        if (!mHasFeature) {
7995            return;
7996        }
7997        Preconditions.checkNotNull(who, "ComponentName is null");
7998        synchronized (this) {
7999            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8000                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8001            if (admin.disableBluetoothContactSharing != disabled) {
8002                admin.disableBluetoothContactSharing = disabled;
8003                saveSettingsLocked(UserHandle.getCallingUserId());
8004            }
8005        }
8006    }
8007
8008    @Override
8009    public boolean getBluetoothContactSharingDisabled(ComponentName who) {
8010        if (!mHasFeature) {
8011            return false;
8012        }
8013        Preconditions.checkNotNull(who, "ComponentName is null");
8014        synchronized (this) {
8015            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8016                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8017            return admin.disableBluetoothContactSharing;
8018        }
8019    }
8020
8021    @Override
8022    public boolean getBluetoothContactSharingDisabledForUser(int userId) {
8023        // TODO: Should there be a check to make sure this relationship is
8024        // within a profile group?
8025        // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
8026        synchronized (this) {
8027            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8028            return (admin != null) ? admin.disableBluetoothContactSharing : false;
8029        }
8030    }
8031
8032    /**
8033     * Sets which packages may enter lock task mode.
8034     *
8035     * <p>This function can only be called by the device owner or alternatively by the profile owner
8036     * in case the user is affiliated.
8037     *
8038     * @param packages The list of packages allowed to enter lock task mode.
8039     */
8040    @Override
8041    public void setLockTaskPackages(ComponentName who, String[] packages)
8042            throws SecurityException {
8043        Preconditions.checkNotNull(who, "ComponentName is null");
8044        synchronized (this) {
8045            ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
8046                who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
8047            ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
8048                who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
8049            if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
8050                int userHandle = mInjector.userHandleGetCallingUserId();
8051                setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
8052            } else {
8053                throw new SecurityException("Admin " + who +
8054                    " is neither the device owner or affiliated user's profile owner.");
8055            }
8056        }
8057    }
8058
8059    private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
8060        DevicePolicyData policy = getUserData(userHandle);
8061        policy.mLockTaskPackages = packages;
8062
8063        // Store the settings persistently.
8064        saveSettingsLocked(userHandle);
8065        updateLockTaskPackagesLocked(packages, userHandle);
8066    }
8067
8068    /**
8069     * This function returns the list of components allowed to start the task lock mode.
8070     */
8071    @Override
8072    public String[] getLockTaskPackages(ComponentName who) {
8073        Preconditions.checkNotNull(who, "ComponentName is null");
8074        synchronized (this) {
8075            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8076            int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8077            final List<String> packages = getLockTaskPackagesLocked(userHandle);
8078            return packages.toArray(new String[packages.size()]);
8079        }
8080    }
8081
8082    private List<String> getLockTaskPackagesLocked(int userHandle) {
8083        final DevicePolicyData policy = getUserData(userHandle);
8084        return policy.mLockTaskPackages;
8085    }
8086
8087    /**
8088     * This function lets the caller know whether the given package is allowed to start the
8089     * lock task mode.
8090     * @param pkg The package to check
8091     */
8092    @Override
8093    public boolean isLockTaskPermitted(String pkg) {
8094        // Get current user's devicepolicy
8095        int uid = mInjector.binderGetCallingUid();
8096        int userHandle = UserHandle.getUserId(uid);
8097        DevicePolicyData policy = getUserData(userHandle);
8098        synchronized (this) {
8099            for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8100                String lockTaskPackage = policy.mLockTaskPackages.get(i);
8101
8102                // If the given package equals one of the packages stored our list,
8103                // we allow this package to start lock task mode.
8104                if (lockTaskPackage.equals(pkg)) {
8105                    return true;
8106                }
8107            }
8108        }
8109        return false;
8110    }
8111
8112    @Override
8113    public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8114        if (!isCallerWithSystemUid()) {
8115            throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8116        }
8117        synchronized (this) {
8118            final DevicePolicyData policy = getUserData(userHandle);
8119            Bundle adminExtras = new Bundle();
8120            adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8121            for (ActiveAdmin admin : policy.mAdminList) {
8122                final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8123                final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8124                if (ownsDevice || ownsProfile) {
8125                    if (isEnabled) {
8126                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8127                                adminExtras, null);
8128                    } else {
8129                        sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8130                    }
8131                }
8132            }
8133        }
8134    }
8135
8136    @Override
8137    public void setGlobalSetting(ComponentName who, String setting, String value) {
8138        Preconditions.checkNotNull(who, "ComponentName is null");
8139
8140        synchronized (this) {
8141            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8142
8143            // Some settings are no supported any more. However we do not want to throw a
8144            // SecurityException to avoid breaking apps.
8145            if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8146                Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8147                return;
8148            }
8149
8150            if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8151                throw new SecurityException(String.format(
8152                        "Permission denial: device owners cannot update %1$s", setting));
8153            }
8154
8155            if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8156                // ignore if it contradicts an existing policy
8157                long timeMs = getMaximumTimeToLock(
8158                        who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8159                if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8160                    return;
8161                }
8162            }
8163
8164            long id = mInjector.binderClearCallingIdentity();
8165            try {
8166                mInjector.settingsGlobalPutString(setting, value);
8167            } finally {
8168                mInjector.binderRestoreCallingIdentity(id);
8169            }
8170        }
8171    }
8172
8173    @Override
8174    public void setSecureSetting(ComponentName who, String setting, String value) {
8175        Preconditions.checkNotNull(who, "ComponentName is null");
8176        int callingUserId = mInjector.userHandleGetCallingUserId();
8177
8178        synchronized (this) {
8179            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8180
8181            if (isDeviceOwner(who, callingUserId)) {
8182                if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8183                    throw new SecurityException(String.format(
8184                            "Permission denial: Device owners cannot update %1$s", setting));
8185                }
8186            } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8187                throw new SecurityException(String.format(
8188                        "Permission denial: Profile owners cannot update %1$s", setting));
8189            }
8190
8191            long id = mInjector.binderClearCallingIdentity();
8192            try {
8193                mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8194            } finally {
8195                mInjector.binderRestoreCallingIdentity(id);
8196            }
8197        }
8198    }
8199
8200    @Override
8201    public void setMasterVolumeMuted(ComponentName who, boolean on) {
8202        Preconditions.checkNotNull(who, "ComponentName is null");
8203        synchronized (this) {
8204            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8205            setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8206        }
8207    }
8208
8209    @Override
8210    public boolean isMasterVolumeMuted(ComponentName who) {
8211        Preconditions.checkNotNull(who, "ComponentName is null");
8212        synchronized (this) {
8213            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8214
8215            AudioManager audioManager =
8216                    (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8217            return audioManager.isMasterMute();
8218        }
8219    }
8220
8221    @Override
8222    public void setUserIcon(ComponentName who, Bitmap icon) {
8223        synchronized (this) {
8224            Preconditions.checkNotNull(who, "ComponentName is null");
8225            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8226
8227            int userId = UserHandle.getCallingUserId();
8228            long id = mInjector.binderClearCallingIdentity();
8229            try {
8230                mUserManagerInternal.setUserIcon(userId, icon);
8231            } finally {
8232                mInjector.binderRestoreCallingIdentity(id);
8233            }
8234        }
8235    }
8236
8237    @Override
8238    public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8239        Preconditions.checkNotNull(who, "ComponentName is null");
8240        synchronized (this) {
8241            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8242        }
8243        final int userId = UserHandle.getCallingUserId();
8244
8245        long ident = mInjector.binderClearCallingIdentity();
8246        try {
8247            // disallow disabling the keyguard if a password is currently set
8248            if (disabled && mLockPatternUtils.isSecure(userId)) {
8249                return false;
8250            }
8251            mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8252        } finally {
8253            mInjector.binderRestoreCallingIdentity(ident);
8254        }
8255        return true;
8256    }
8257
8258    @Override
8259    public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8260        int userId = UserHandle.getCallingUserId();
8261        synchronized (this) {
8262            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8263            DevicePolicyData policy = getUserData(userId);
8264            if (policy.mStatusBarDisabled != disabled) {
8265                if (!setStatusBarDisabledInternal(disabled, userId)) {
8266                    return false;
8267                }
8268                policy.mStatusBarDisabled = disabled;
8269                saveSettingsLocked(userId);
8270            }
8271        }
8272        return true;
8273    }
8274
8275    private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8276        long ident = mInjector.binderClearCallingIdentity();
8277        try {
8278            IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8279                    ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8280            if (statusBarService != null) {
8281                int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8282                int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8283                statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8284                statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8285                return true;
8286            }
8287        } catch (RemoteException e) {
8288            Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8289        } finally {
8290            mInjector.binderRestoreCallingIdentity(ident);
8291        }
8292        return false;
8293    }
8294
8295    /**
8296     * We need to update the internal state of whether a user has completed setup or a
8297     * device has paired once. After that, we ignore any changes that reset the
8298     * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
8299     * as we don't trust any apps that might try to reset them.
8300     * <p>
8301     * Unfortunately, we don't know which user's setup state was changed, so we write all of
8302     * them.
8303     */
8304    void updateUserSetupCompleteAndPaired() {
8305        List<UserInfo> users = mUserManager.getUsers(true);
8306        final int N = users.size();
8307        for (int i = 0; i < N; i++) {
8308            int userHandle = users.get(i).id;
8309            if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8310                    userHandle) != 0) {
8311                DevicePolicyData policy = getUserData(userHandle);
8312                if (!policy.mUserSetupComplete) {
8313                    policy.mUserSetupComplete = true;
8314                    synchronized (this) {
8315                        saveSettingsLocked(userHandle);
8316                    }
8317                }
8318            }
8319            if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
8320                    userHandle) != 0) {
8321                DevicePolicyData policy = getUserData(userHandle);
8322                if (!policy.mPaired) {
8323                    policy.mPaired = true;
8324                    synchronized (this) {
8325                        saveSettingsLocked(userHandle);
8326                    }
8327                }
8328            }
8329        }
8330    }
8331
8332    private class SetupContentObserver extends ContentObserver {
8333
8334        private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8335                Settings.Secure.USER_SETUP_COMPLETE);
8336        private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8337                Settings.Global.DEVICE_PROVISIONED);
8338        private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
8339
8340        public SetupContentObserver(Handler handler) {
8341            super(handler);
8342        }
8343
8344        void register() {
8345            mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8346            mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8347            if (mIsWatch) {
8348                mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
8349            }
8350        }
8351
8352        @Override
8353        public void onChange(boolean selfChange, Uri uri) {
8354            if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
8355                updateUserSetupCompleteAndPaired();
8356            } else if (mDeviceProvisioned.equals(uri)) {
8357                synchronized (DevicePolicyManagerService.this) {
8358                    // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8359                    // is delayed until device is marked as provisioned.
8360                    setDeviceOwnerSystemPropertyLocked();
8361                }
8362            }
8363        }
8364    }
8365
8366    @VisibleForTesting
8367    final class LocalService extends DevicePolicyManagerInternal {
8368        private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8369
8370        @Override
8371        public List<String> getCrossProfileWidgetProviders(int profileId) {
8372            synchronized (DevicePolicyManagerService.this) {
8373                if (mOwners == null) {
8374                    return Collections.emptyList();
8375                }
8376                ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8377                if (ownerComponent == null) {
8378                    return Collections.emptyList();
8379                }
8380
8381                DevicePolicyData policy = getUserDataUnchecked(profileId);
8382                ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8383
8384                if (admin == null || admin.crossProfileWidgetProviders == null
8385                        || admin.crossProfileWidgetProviders.isEmpty()) {
8386                    return Collections.emptyList();
8387                }
8388
8389                return admin.crossProfileWidgetProviders;
8390            }
8391        }
8392
8393        @Override
8394        public void addOnCrossProfileWidgetProvidersChangeListener(
8395                OnCrossProfileWidgetProvidersChangeListener listener) {
8396            synchronized (DevicePolicyManagerService.this) {
8397                if (mWidgetProviderListeners == null) {
8398                    mWidgetProviderListeners = new ArrayList<>();
8399                }
8400                if (!mWidgetProviderListeners.contains(listener)) {
8401                    mWidgetProviderListeners.add(listener);
8402                }
8403            }
8404        }
8405
8406        @Override
8407        public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8408            synchronized(DevicePolicyManagerService.this) {
8409                return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8410            }
8411        }
8412
8413        private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8414            final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8415            synchronized (DevicePolicyManagerService.this) {
8416                listeners = new ArrayList<>(mWidgetProviderListeners);
8417            }
8418            final int listenerCount = listeners.size();
8419            for (int i = 0; i < listenerCount; i++) {
8420                OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8421                listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8422            }
8423        }
8424
8425        @Override
8426        public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
8427            // This method is called from AM with its lock held, so don't take the DPMS lock.
8428            // b/29242568
8429
8430            ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8431            if (profileOwner != null) {
8432                return createShowAdminSupportIntent(profileOwner, userId);
8433            }
8434
8435            final Pair<Integer, ComponentName> deviceOwner =
8436                    mOwners.getDeviceOwnerUserIdAndComponent();
8437            if (deviceOwner != null && deviceOwner.first == userId) {
8438                return createShowAdminSupportIntent(deviceOwner.second, userId);
8439            }
8440
8441            // We're not specifying the device admin because there isn't one.
8442            if (useDefaultIfNoAdmin) {
8443                return createShowAdminSupportIntent(null, userId);
8444            }
8445            return null;
8446        }
8447
8448        @Override
8449        public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
8450            int source;
8451            long ident = mInjector.binderClearCallingIdentity();
8452            try {
8453                source = mUserManager.getUserRestrictionSource(userRestriction,
8454                        UserHandle.of(userId));
8455            } finally {
8456                mInjector.binderRestoreCallingIdentity(ident);
8457            }
8458            if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
8459                /*
8460                 * In this case, the user restriction is enforced by the system.
8461                 * So we won't show an admin support intent, even if it is also
8462                 * enforced by a profile/device owner.
8463                 */
8464                return null;
8465            }
8466            boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
8467            boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
8468            if (enforcedByDo && enforcedByPo) {
8469                // In this case, we'll show an admin support dialog that does not
8470                // specify the admin.
8471                return createShowAdminSupportIntent(null, userId);
8472            } else if (enforcedByPo) {
8473                final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8474                if (profileOwner != null) {
8475                    return createShowAdminSupportIntent(profileOwner, userId);
8476                }
8477                // This could happen if another thread has changed the profile owner since we called
8478                // getUserRestrictionSource
8479                return null;
8480            } else if (enforcedByDo) {
8481                final Pair<Integer, ComponentName> deviceOwner
8482                        = mOwners.getDeviceOwnerUserIdAndComponent();
8483                if (deviceOwner != null) {
8484                    return createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
8485                }
8486                // This could happen if another thread has changed the device owner since we called
8487                // getUserRestrictionSource
8488                return null;
8489            }
8490            return null;
8491        }
8492
8493        private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
8494            // This method is called with AMS lock held, so don't take DPMS lock
8495            final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8496            intent.putExtra(Intent.EXTRA_USER_ID, userId);
8497            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
8498            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8499            return intent;
8500        }
8501    }
8502
8503    /**
8504     * Returns true if specified admin is allowed to limit passwords and has a
8505     * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
8506     */
8507    private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8508        if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
8509            return false;
8510        }
8511        return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8512    }
8513
8514    @Override
8515    public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8516        if (policy != null && !policy.isValid()) {
8517            throw new IllegalArgumentException("Invalid system update policy.");
8518        }
8519        synchronized (this) {
8520            getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8521            if (policy == null) {
8522                mOwners.clearSystemUpdatePolicy();
8523            } else {
8524                mOwners.setSystemUpdatePolicy(policy);
8525            }
8526            mOwners.writeDeviceOwner();
8527        }
8528        mContext.sendBroadcastAsUser(
8529                new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8530                UserHandle.SYSTEM);
8531    }
8532
8533    @Override
8534    public SystemUpdatePolicy getSystemUpdatePolicy() {
8535        if (UserManager.isDeviceInDemoMode(mContext)) {
8536            // Pretending to have an automatic update policy when the device is in retail demo
8537            // mode. This will allow the device to download and install an ota without
8538            // any user interaction.
8539            return SystemUpdatePolicy.createAutomaticInstallPolicy();
8540        }
8541        synchronized (this) {
8542            SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
8543            if (policy != null && !policy.isValid()) {
8544                Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8545                return null;
8546            }
8547            return policy;
8548        }
8549    }
8550
8551    /**
8552     * Checks if the caller of the method is the device owner app.
8553     *
8554     * @param callerUid UID of the caller.
8555     * @return true if the caller is the device owner app
8556     */
8557    @VisibleForTesting
8558    boolean isCallerDeviceOwner(int callerUid) {
8559        synchronized (this) {
8560            if (!mOwners.hasDeviceOwner()) {
8561                return false;
8562            }
8563            if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8564                return false;
8565            }
8566            final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8567                    .getPackageName();
8568            final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8569
8570            for (String pkg : pkgs) {
8571                if (deviceOwnerPackageName.equals(pkg)) {
8572                    return true;
8573                }
8574            }
8575        }
8576
8577        return false;
8578    }
8579
8580    @Override
8581    public void notifyPendingSystemUpdate(long updateReceivedTime) {
8582        mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8583                "Only the system update service can broadcast update information");
8584
8585        if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8586            Slog.w(LOG_TAG, "Only the system update service in the system user " +
8587                    "can broadcast update information.");
8588            return;
8589        }
8590        Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8591        intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8592                updateReceivedTime);
8593
8594        synchronized (this) {
8595            final String deviceOwnerPackage =
8596                    mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8597                            : null;
8598            if (deviceOwnerPackage == null) {
8599                return;
8600            }
8601            final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8602
8603            ActivityInfo[] receivers = null;
8604            try {
8605                receivers  = mContext.getPackageManager().getPackageInfo(
8606                        deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8607            } catch (NameNotFoundException e) {
8608                Log.e(LOG_TAG, "Cannot find device owner package", e);
8609            }
8610            if (receivers != null) {
8611                long ident = mInjector.binderClearCallingIdentity();
8612                try {
8613                    for (int i = 0; i < receivers.length; i++) {
8614                        if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8615                            intent.setComponent(new ComponentName(deviceOwnerPackage,
8616                                    receivers[i].name));
8617                            mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8618                        }
8619                    }
8620                } finally {
8621                    mInjector.binderRestoreCallingIdentity(ident);
8622                }
8623            }
8624        }
8625    }
8626
8627    @Override
8628    public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8629        int userId = UserHandle.getCallingUserId();
8630        synchronized (this) {
8631            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8632            DevicePolicyData userPolicy = getUserData(userId);
8633            if (userPolicy.mPermissionPolicy != policy) {
8634                userPolicy.mPermissionPolicy = policy;
8635                saveSettingsLocked(userId);
8636            }
8637        }
8638    }
8639
8640    @Override
8641    public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8642        int userId = UserHandle.getCallingUserId();
8643        synchronized (this) {
8644            DevicePolicyData userPolicy = getUserData(userId);
8645            return userPolicy.mPermissionPolicy;
8646        }
8647    }
8648
8649    @Override
8650    public boolean setPermissionGrantState(ComponentName admin, String packageName,
8651            String permission, int grantState) throws RemoteException {
8652        UserHandle user = mInjector.binderGetCallingUserHandle();
8653        synchronized (this) {
8654            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8655            long ident = mInjector.binderClearCallingIdentity();
8656            try {
8657                if (getTargetSdk(packageName, user.getIdentifier())
8658                        < android.os.Build.VERSION_CODES.M) {
8659                    return false;
8660                }
8661                final PackageManager packageManager = mContext.getPackageManager();
8662                switch (grantState) {
8663                    case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8664                        mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
8665                                permission, user.getIdentifier(), true /* override policy */);
8666                        packageManager.updatePermissionFlags(permission, packageName,
8667                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8668                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8669                    } break;
8670
8671                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8672                        mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
8673                                permission, user.getIdentifier(), true /* override policy */);
8674                        packageManager.updatePermissionFlags(permission, packageName,
8675                                PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8676                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8677                    } break;
8678
8679                    case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8680                        packageManager.updatePermissionFlags(permission, packageName,
8681                                PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8682                    } break;
8683                }
8684                return true;
8685            } catch (SecurityException se) {
8686                return false;
8687            } finally {
8688                mInjector.binderRestoreCallingIdentity(ident);
8689            }
8690        }
8691    }
8692
8693    @Override
8694    public int getPermissionGrantState(ComponentName admin, String packageName,
8695            String permission) throws RemoteException {
8696        PackageManager packageManager = mContext.getPackageManager();
8697
8698        UserHandle user = mInjector.binderGetCallingUserHandle();
8699        synchronized (this) {
8700            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8701            long ident = mInjector.binderClearCallingIdentity();
8702            try {
8703                int granted = mIPackageManager.checkPermission(permission,
8704                        packageName, user.getIdentifier());
8705                int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8706                if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8707                        != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8708                    // Not controlled by policy
8709                    return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8710                } else {
8711                    // Policy controlled so return result based on permission grant state
8712                    return granted == PackageManager.PERMISSION_GRANTED
8713                            ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8714                            : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8715                }
8716            } finally {
8717                mInjector.binderRestoreCallingIdentity(ident);
8718            }
8719        }
8720    }
8721
8722    boolean isPackageInstalledForUser(String packageName, int userHandle) {
8723        try {
8724            PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8725                    userHandle);
8726            return (pi != null) && (pi.applicationInfo.flags != 0);
8727        } catch (RemoteException re) {
8728            throw new RuntimeException("Package manager has died", re);
8729        }
8730    }
8731
8732    @Override
8733    public boolean isProvisioningAllowed(String action) {
8734        if (!mHasFeature) {
8735            return false;
8736        }
8737
8738        final int callingUserId = mInjector.userHandleGetCallingUserId();
8739        if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8740            if (!hasFeatureManagedUsers()) {
8741                return false;
8742            }
8743            synchronized (this) {
8744                if (mOwners.hasDeviceOwner()) {
8745                    // STOPSHIP Only allow creating a managed profile if allowed by the device
8746                    // owner. http://b/31952368
8747                    if (mInjector.userManagerIsSplitSystemUser()) {
8748                        if (callingUserId == UserHandle.USER_SYSTEM) {
8749                            // Managed-profiles cannot be setup on the system user.
8750                            return false;
8751                        }
8752                    }
8753                }
8754            }
8755            if (getProfileOwner(callingUserId) != null) {
8756                // Managed user cannot have a managed profile.
8757                return false;
8758            }
8759            boolean canRemoveProfile
8760                    = !mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_USER);
8761            final long ident = mInjector.binderClearCallingIdentity();
8762            try {
8763                if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
8764                    return false;
8765                }
8766            } finally {
8767                mInjector.binderRestoreCallingIdentity(ident);
8768            }
8769            return true;
8770        } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8771            return isDeviceOwnerProvisioningAllowed(callingUserId);
8772        } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8773            if (!hasFeatureManagedUsers()) {
8774                return false;
8775            }
8776            if (!mInjector.userManagerIsSplitSystemUser()) {
8777                // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8778                return false;
8779            }
8780            if (callingUserId == UserHandle.USER_SYSTEM) {
8781                // System user cannot be a managed user.
8782                return false;
8783            }
8784            if (hasUserSetupCompleted(callingUserId)) {
8785                return false;
8786            }
8787            if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8788                return false;
8789            }
8790            return true;
8791        } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8792            if (!mInjector.userManagerIsSplitSystemUser()) {
8793                // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8794                return false;
8795            }
8796            return isDeviceOwnerProvisioningAllowed(callingUserId);
8797        }
8798        throw new IllegalArgumentException("Unknown provisioning action " + action);
8799    }
8800
8801    /*
8802     * The device owner can only be set before the setup phase of the primary user has completed,
8803     * except for adb command if no accounts or additional users are present on the device.
8804     */
8805    private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8806            @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb) {
8807        if (mOwners.hasDeviceOwner()) {
8808            return CODE_HAS_DEVICE_OWNER;
8809        }
8810        if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8811            return CODE_USER_HAS_PROFILE_OWNER;
8812        }
8813        if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8814            return CODE_USER_NOT_RUNNING;
8815        }
8816        if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8817            return CODE_HAS_PAIRED;
8818        }
8819        if (isAdb) {
8820            // if shell command runs after user setup completed check device status. Otherwise, OK.
8821            if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8822                if (!mInjector.userManagerIsSplitSystemUser()) {
8823                    if (mUserManager.getUserCount() > 1) {
8824                        return CODE_NONSYSTEM_USER_EXISTS;
8825                    }
8826                    if (hasIncompatibleAccountsLocked(UserHandle.USER_SYSTEM, owner)) {
8827                        return CODE_ACCOUNTS_NOT_EMPTY;
8828                    }
8829                } else {
8830                    // STOPSHIP Do proper check in split user mode
8831                }
8832            }
8833            return CODE_OK;
8834        } else {
8835            if (!mInjector.userManagerIsSplitSystemUser()) {
8836                // In non-split user mode, DO has to be user 0
8837                if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8838                    return CODE_NOT_SYSTEM_USER;
8839                }
8840                // In non-split user mode, only provision DO before setup wizard completes
8841                if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8842                    return CODE_USER_SETUP_COMPLETED;
8843                }
8844            } else {
8845                // STOPSHIP Do proper check in split user mode
8846            }
8847            return CODE_OK;
8848        }
8849    }
8850
8851    private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8852        synchronized (this) {
8853            return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8854                    /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false);
8855        }
8856    }
8857
8858    private boolean hasFeatureManagedUsers() {
8859        try {
8860            return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8861        } catch (RemoteException e) {
8862            return false;
8863        }
8864    }
8865
8866    @Override
8867    public String getWifiMacAddress(ComponentName admin) {
8868        // Make sure caller has DO.
8869        synchronized (this) {
8870            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8871        }
8872
8873        final long ident = mInjector.binderClearCallingIdentity();
8874        try {
8875            final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8876            if (wifiInfo == null) {
8877                return null;
8878            }
8879            return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8880        } finally {
8881            mInjector.binderRestoreCallingIdentity(ident);
8882        }
8883    }
8884
8885    /**
8886     * Returns the target sdk version number that the given packageName was built for
8887     * in the given user.
8888     */
8889    private int getTargetSdk(String packageName, int userId) {
8890        final ApplicationInfo ai;
8891        try {
8892            ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8893            final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8894            return targetSdkVersion;
8895        } catch (RemoteException e) {
8896            // Shouldn't happen
8897            return 0;
8898        }
8899    }
8900
8901    @Override
8902    public boolean isManagedProfile(ComponentName admin) {
8903        synchronized (this) {
8904            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8905        }
8906        final int callingUserId = mInjector.userHandleGetCallingUserId();
8907        final UserInfo user = getUserInfo(callingUserId);
8908        return user != null && user.isManagedProfile();
8909    }
8910
8911    @Override
8912    public boolean isSystemOnlyUser(ComponentName admin) {
8913        synchronized (this) {
8914            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8915        }
8916        final int callingUserId = mInjector.userHandleGetCallingUserId();
8917        return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8918    }
8919
8920    @Override
8921    public void reboot(ComponentName admin) {
8922        Preconditions.checkNotNull(admin);
8923        // Make sure caller has DO.
8924        synchronized (this) {
8925            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8926        }
8927        long ident = mInjector.binderClearCallingIdentity();
8928        try {
8929            // Make sure there are no ongoing calls on the device.
8930            if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8931                throw new IllegalStateException("Cannot be called with ongoing call on the device");
8932            }
8933            mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8934        } finally {
8935            mInjector.binderRestoreCallingIdentity(ident);
8936        }
8937    }
8938
8939    @Override
8940    public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8941        if (!mHasFeature) {
8942            return;
8943        }
8944        Preconditions.checkNotNull(who, "ComponentName is null");
8945        final int userHandle = mInjector.userHandleGetCallingUserId();
8946        synchronized (this) {
8947            ActiveAdmin admin = getActiveAdminForUidLocked(who,
8948                    mInjector.binderGetCallingUid());
8949            if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8950                admin.shortSupportMessage = message;
8951                saveSettingsLocked(userHandle);
8952            }
8953        }
8954    }
8955
8956    @Override
8957    public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8958        if (!mHasFeature) {
8959            return null;
8960        }
8961        Preconditions.checkNotNull(who, "ComponentName is null");
8962        synchronized (this) {
8963            ActiveAdmin admin = getActiveAdminForUidLocked(who,
8964                    mInjector.binderGetCallingUid());
8965            return admin.shortSupportMessage;
8966        }
8967    }
8968
8969    @Override
8970    public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8971        if (!mHasFeature) {
8972            return;
8973        }
8974        Preconditions.checkNotNull(who, "ComponentName is null");
8975        final int userHandle = mInjector.userHandleGetCallingUserId();
8976        synchronized (this) {
8977            ActiveAdmin admin = getActiveAdminForUidLocked(who,
8978                    mInjector.binderGetCallingUid());
8979            if (!TextUtils.equals(admin.longSupportMessage, message)) {
8980                admin.longSupportMessage = message;
8981                saveSettingsLocked(userHandle);
8982            }
8983        }
8984    }
8985
8986    @Override
8987    public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8988        if (!mHasFeature) {
8989            return null;
8990        }
8991        Preconditions.checkNotNull(who, "ComponentName is null");
8992        synchronized (this) {
8993            ActiveAdmin admin = getActiveAdminForUidLocked(who,
8994                    mInjector.binderGetCallingUid());
8995            return admin.longSupportMessage;
8996        }
8997    }
8998
8999    @Override
9000    public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
9001        if (!mHasFeature) {
9002            return null;
9003        }
9004        Preconditions.checkNotNull(who, "ComponentName is null");
9005        if (!isCallerWithSystemUid()) {
9006            throw new SecurityException("Only the system can query support message for user");
9007        }
9008        synchronized (this) {
9009            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9010            if (admin != null) {
9011                return admin.shortSupportMessage;
9012            }
9013        }
9014        return null;
9015    }
9016
9017    @Override
9018    public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
9019        if (!mHasFeature) {
9020            return null;
9021        }
9022        Preconditions.checkNotNull(who, "ComponentName is null");
9023        if (!isCallerWithSystemUid()) {
9024            throw new SecurityException("Only the system can query support message for user");
9025        }
9026        synchronized (this) {
9027            ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
9028            if (admin != null) {
9029                return admin.longSupportMessage;
9030            }
9031        }
9032        return null;
9033    }
9034
9035    @Override
9036    public void setOrganizationColor(@NonNull ComponentName who, int color) {
9037        if (!mHasFeature) {
9038            return;
9039        }
9040        Preconditions.checkNotNull(who, "ComponentName is null");
9041        final int userHandle = mInjector.userHandleGetCallingUserId();
9042        enforceManagedProfile(userHandle, "set organization color");
9043        synchronized (this) {
9044            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9045                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9046            admin.organizationColor = color;
9047            saveSettingsLocked(userHandle);
9048        }
9049    }
9050
9051    @Override
9052    public void setOrganizationColorForUser(int color, int userId) {
9053        if (!mHasFeature) {
9054            return;
9055        }
9056        enforceFullCrossUsersPermission(userId);
9057        enforceManageUsers();
9058        enforceManagedProfile(userId, "set organization color");
9059        synchronized (this) {
9060            ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9061            admin.organizationColor = color;
9062            saveSettingsLocked(userId);
9063        }
9064    }
9065
9066    @Override
9067    public int getOrganizationColor(@NonNull ComponentName who) {
9068        if (!mHasFeature) {
9069            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9070        }
9071        Preconditions.checkNotNull(who, "ComponentName is null");
9072        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
9073        synchronized (this) {
9074            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9075                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9076            return admin.organizationColor;
9077        }
9078    }
9079
9080    @Override
9081    public int getOrganizationColorForUser(int userHandle) {
9082        if (!mHasFeature) {
9083            return ActiveAdmin.DEF_ORGANIZATION_COLOR;
9084        }
9085        enforceFullCrossUsersPermission(userHandle);
9086        enforceManagedProfile(userHandle, "get organization color");
9087        synchronized (this) {
9088            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9089            return (profileOwner != null)
9090                    ? profileOwner.organizationColor
9091                    : ActiveAdmin.DEF_ORGANIZATION_COLOR;
9092        }
9093    }
9094
9095    @Override
9096    public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
9097        if (!mHasFeature) {
9098            return;
9099        }
9100        Preconditions.checkNotNull(who, "ComponentName is null");
9101        final int userHandle = mInjector.userHandleGetCallingUserId();
9102        enforceManagedProfile(userHandle, "set organization name");
9103        synchronized (this) {
9104            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9105                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9106            if (!TextUtils.equals(admin.organizationName, text)) {
9107                admin.organizationName = (text == null || text.length() == 0)
9108                        ? null : text.toString();
9109                saveSettingsLocked(userHandle);
9110            }
9111        }
9112    }
9113
9114    @Override
9115    public CharSequence getOrganizationName(@NonNull ComponentName who) {
9116        if (!mHasFeature) {
9117            return null;
9118        }
9119        Preconditions.checkNotNull(who, "ComponentName is null");
9120        enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
9121        synchronized(this) {
9122            ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9123                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9124            return admin.organizationName;
9125        }
9126    }
9127
9128    @Override
9129    public CharSequence getOrganizationNameForUser(int userHandle) {
9130        if (!mHasFeature) {
9131            return null;
9132        }
9133        enforceFullCrossUsersPermission(userHandle);
9134        enforceManagedProfile(userHandle, "get organization name");
9135        synchronized (this) {
9136            ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9137            return (profileOwner != null)
9138                    ? profileOwner.organizationName
9139                    : null;
9140        }
9141    }
9142
9143    @Override
9144    public void setAffiliationIds(ComponentName admin, List<String> ids) {
9145        final Set<String> affiliationIds = new ArraySet<String>(ids);
9146        final int callingUserId = mInjector.userHandleGetCallingUserId();
9147
9148        synchronized (this) {
9149            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9150            getUserData(callingUserId).mAffiliationIds = affiliationIds;
9151            saveSettingsLocked(callingUserId);
9152            if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
9153                // Affiliation ids specified by the device owner are additionally stored in
9154                // UserHandle.USER_SYSTEM's DevicePolicyData.
9155                getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
9156                saveSettingsLocked(UserHandle.USER_SYSTEM);
9157            }
9158        }
9159    }
9160
9161    @Override
9162    public boolean isAffiliatedUser() {
9163        final int callingUserId = mInjector.userHandleGetCallingUserId();
9164
9165        synchronized (this) {
9166            if (mOwners.getDeviceOwnerUserId() == callingUserId) {
9167                // The user that the DO is installed on is always affiliated.
9168                return true;
9169            }
9170            final ComponentName profileOwner = getProfileOwner(callingUserId);
9171            if (profileOwner == null
9172                    || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
9173                return false;
9174            }
9175            final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
9176            final Set<String> deviceAffiliationIds =
9177                    getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9178            for (String id : userAffiliationIds) {
9179                if (deviceAffiliationIds.contains(id)) {
9180                    return true;
9181                }
9182            }
9183        }
9184        return false;
9185    }
9186
9187    private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
9188        final boolean isSingleUserManagedDevice = isDeviceOwnerManagedSingleUserDevice();
9189
9190        // disable security logging if needed
9191        if (!isSingleUserManagedDevice) {
9192            mInjector.securityLogSetLoggingEnabledProperty(false);
9193            Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user managed"
9194                    + " device.");
9195        }
9196
9197        // disable backup service if needed
9198        // note: when clearing DO, the backup service shouldn't be disabled if it was enabled by
9199        // the device owner
9200        if (mOwners.hasDeviceOwner() && !isSingleUserManagedDevice) {
9201            setBackupServiceEnabledInternal(false);
9202            Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
9203        }
9204
9205        // disable network logging if needed
9206        if (!isSingleUserManagedDevice) {
9207            setNetworkLoggingActiveInternal(false);
9208            Slog.w(LOG_TAG, "Network logging turned off as it's no longer a single user managed"
9209                    + " device.");
9210            // if there still is a device owner, disable logging policy, otherwise the admin
9211            // has been nuked
9212            if (mOwners.hasDeviceOwner()) {
9213                getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = false;
9214                saveSettingsLocked(mOwners.getDeviceOwnerUserId());
9215            }
9216        }
9217    }
9218
9219    @Override
9220    public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9221        Preconditions.checkNotNull(admin);
9222        ensureDeviceOwnerManagingSingleUser(admin);
9223
9224        synchronized (this) {
9225            if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9226                return;
9227            }
9228            mInjector.securityLogSetLoggingEnabledProperty(enabled);
9229            if (enabled) {
9230                mSecurityLogMonitor.start();
9231            } else {
9232                mSecurityLogMonitor.stop();
9233            }
9234        }
9235    }
9236
9237    @Override
9238    public boolean isSecurityLoggingEnabled(ComponentName admin) {
9239        Preconditions.checkNotNull(admin);
9240        synchronized (this) {
9241            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9242            return mInjector.securityLogGetLoggingEnabledProperty();
9243        }
9244    }
9245
9246    private synchronized void recordSecurityLogRetrievalTime() {
9247        final long currentTime = System.currentTimeMillis();
9248        DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
9249        if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
9250            policyData.mLastSecurityLogRetrievalTime = currentTime;
9251            saveSettingsLocked(UserHandle.USER_SYSTEM);
9252        }
9253    }
9254
9255    @Override
9256    public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9257        Preconditions.checkNotNull(admin);
9258        ensureDeviceOwnerManagingSingleUser(admin);
9259
9260        if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
9261            return null;
9262        }
9263
9264        recordSecurityLogRetrievalTime();
9265
9266        ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9267        try {
9268            SecurityLog.readPreviousEvents(output);
9269            return new ParceledListSlice<SecurityEvent>(output);
9270        } catch (IOException e) {
9271            Slog.w(LOG_TAG, "Fail to read previous events" , e);
9272            return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9273        }
9274    }
9275
9276    @Override
9277    public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9278        Preconditions.checkNotNull(admin);
9279        ensureDeviceOwnerManagingSingleUser(admin);
9280
9281        recordSecurityLogRetrievalTime();
9282
9283        List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
9284        return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
9285    }
9286
9287    private void enforceCanManageDeviceAdmin() {
9288        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
9289                null);
9290    }
9291
9292    private void enforceCanManageProfileAndDeviceOwners() {
9293        mContext.enforceCallingOrSelfPermission(
9294                android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
9295    }
9296
9297    private void enforceCallerSystemUserHandle() {
9298        final int callingUid = mInjector.binderGetCallingUid();
9299        final int userId = UserHandle.getUserId(callingUid);
9300        if (userId != UserHandle.USER_SYSTEM) {
9301            throw new SecurityException("Caller has to be in user 0");
9302        }
9303    }
9304
9305    @Override
9306    public boolean isUninstallInQueue(final String packageName) {
9307        enforceCanManageDeviceAdmin();
9308        final int userId = mInjector.userHandleGetCallingUserId();
9309        Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9310        synchronized (this) {
9311            return mPackagesToRemove.contains(packageUserPair);
9312        }
9313    }
9314
9315    @Override
9316    public void uninstallPackageWithActiveAdmins(final String packageName) {
9317        enforceCanManageDeviceAdmin();
9318        Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
9319
9320        final int userId = mInjector.userHandleGetCallingUserId();
9321
9322        enforceUserUnlocked(userId);
9323
9324        final ComponentName profileOwner = getProfileOwner(userId);
9325        if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9326            throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9327        }
9328
9329        final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9330        if (getDeviceOwnerUserId() == userId && deviceOwner != null
9331                && packageName.equals(deviceOwner.getPackageName())) {
9332            throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9333        }
9334
9335        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9336        synchronized (this) {
9337            mPackagesToRemove.add(packageUserPair);
9338        }
9339
9340        // All active admins on the user.
9341        final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9342
9343        // Active admins in the target package.
9344        final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9345        if (allActiveAdmins != null) {
9346            for (ComponentName activeAdmin : allActiveAdmins) {
9347                if (packageName.equals(activeAdmin.getPackageName())) {
9348                    packageActiveAdmins.add(activeAdmin);
9349                    removeActiveAdmin(activeAdmin, userId);
9350                }
9351            }
9352        }
9353        if (packageActiveAdmins.size() == 0) {
9354            startUninstallIntent(packageName, userId);
9355        } else {
9356            mHandler.postDelayed(new Runnable() {
9357                @Override
9358                public void run() {
9359                    for (ComponentName activeAdmin : packageActiveAdmins) {
9360                        removeAdminArtifacts(activeAdmin, userId);
9361                    }
9362                    startUninstallIntent(packageName, userId);
9363                }
9364            }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9365        }
9366    }
9367
9368    @Override
9369    public boolean isDeviceProvisioned() {
9370        return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9371    }
9372
9373    private void removePackageIfRequired(final String packageName, final int userId) {
9374        if (!packageHasActiveAdmins(packageName, userId)) {
9375            // Will not do anything if uninstall was not requested or was already started.
9376            startUninstallIntent(packageName, userId);
9377        }
9378    }
9379
9380    private void startUninstallIntent(final String packageName, final int userId) {
9381        final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9382        synchronized (this) {
9383            if (!mPackagesToRemove.contains(packageUserPair)) {
9384                // Do nothing if uninstall was not requested or was already started.
9385                return;
9386            }
9387            mPackagesToRemove.remove(packageUserPair);
9388        }
9389        try {
9390            if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9391                // Package does not exist. Nothing to do.
9392                return;
9393            }
9394        } catch (RemoteException re) {
9395            Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9396        }
9397
9398        try { // force stop the package before uninstalling
9399            mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9400        } catch (RemoteException re) {
9401            Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9402        }
9403        final Uri packageURI = Uri.parse("package:" + packageName);
9404        final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9405        uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9406        mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9407    }
9408
9409    /**
9410     * Removes the admin from the policy. Ideally called after the admin's
9411     * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9412     *
9413     * @param adminReceiver The admin to remove
9414     * @param userHandle The user for which this admin has to be removed.
9415     */
9416    private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9417        synchronized (this) {
9418            final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9419            if (admin == null) {
9420                return;
9421            }
9422            final DevicePolicyData policy = getUserData(userHandle);
9423            final boolean doProxyCleanup = admin.info.usesPolicy(
9424                    DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9425            policy.mAdminList.remove(admin);
9426            policy.mAdminMap.remove(adminReceiver);
9427            validatePasswordOwnerLocked(policy);
9428            if (doProxyCleanup) {
9429                resetGlobalProxyLocked(policy);
9430            }
9431            saveSettingsLocked(userHandle);
9432            updateMaximumTimeToLockLocked(userHandle);
9433            policy.mRemovingAdmins.remove(adminReceiver);
9434
9435            Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9436        }
9437        // The removed admin might have disabled camera, so update user
9438        // restrictions.
9439        pushUserRestrictions(userHandle);
9440    }
9441
9442    @Override
9443    public void setDeviceProvisioningConfigApplied() {
9444        enforceManageUsers();
9445        synchronized (this) {
9446            DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9447            policy.mDeviceProvisioningConfigApplied = true;
9448            saveSettingsLocked(UserHandle.USER_SYSTEM);
9449        }
9450    }
9451
9452    @Override
9453    public boolean isDeviceProvisioningConfigApplied() {
9454        enforceManageUsers();
9455        synchronized (this) {
9456            final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9457            return policy.mDeviceProvisioningConfigApplied;
9458        }
9459    }
9460
9461    /**
9462     * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
9463     *
9464     * It's added for testing only. Please use this API carefully if it's used by other system app
9465     * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
9466     * apps.
9467     */
9468    @Override
9469    public void forceUpdateUserSetupComplete() {
9470        enforceCanManageProfileAndDeviceOwners();
9471        enforceCallerSystemUserHandle();
9472        // no effect if it's called from user build
9473        if (!mInjector.isBuildDebuggable()) {
9474            return;
9475        }
9476        final int userId = UserHandle.USER_SYSTEM;
9477        boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
9478                Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
9479        DevicePolicyData policy = getUserData(userId);
9480        policy.mUserSetupComplete = isUserCompleted;
9481        synchronized (this) {
9482            saveSettingsLocked(userId);
9483        }
9484    }
9485
9486    @Override
9487    public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
9488        Preconditions.checkNotNull(admin);
9489        if (!mHasFeature) {
9490            return;
9491        }
9492        ensureDeviceOwnerManagingSingleUser(admin);
9493        setBackupServiceEnabledInternal(enabled);
9494    }
9495
9496    private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
9497        long ident = mInjector.binderClearCallingIdentity();
9498        try {
9499            IBackupManager ibm = mInjector.getIBackupManager();
9500            if (ibm != null) {
9501                ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
9502            }
9503        } catch (RemoteException e) {
9504            throw new IllegalStateException(
9505                "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
9506        } finally {
9507            mInjector.binderRestoreCallingIdentity(ident);
9508        }
9509    }
9510
9511    @Override
9512    public boolean isBackupServiceEnabled(ComponentName admin) {
9513        Preconditions.checkNotNull(admin);
9514        if (!mHasFeature) {
9515            return true;
9516        }
9517        synchronized (this) {
9518            try {
9519                getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9520                IBackupManager ibm = mInjector.getIBackupManager();
9521                return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
9522            } catch (RemoteException e) {
9523                throw new IllegalStateException("Failed requesting backup service state.", e);
9524            }
9525        }
9526    }
9527
9528    @Override
9529    public boolean bindDeviceAdminServiceAsUser(
9530            @NonNull ComponentName admin, @NonNull IApplicationThread caller,
9531            @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
9532            @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
9533        if (!mHasFeature) {
9534            return false;
9535        }
9536        Preconditions.checkNotNull(admin);
9537        Preconditions.checkNotNull(caller);
9538        Preconditions.checkNotNull(serviceIntent);
9539        Preconditions.checkNotNull(connection);
9540        final int callingUserId = mInjector.userHandleGetCallingUserId();
9541        Preconditions.checkArgument(callingUserId != targetUserId,
9542                "target user id must be different from the calling user id");
9543
9544        synchronized (this) {
9545            final ActiveAdmin callingAdmin = getActiveAdminForCallerLocked(admin,
9546                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9547            // Ensure the target user is valid.
9548            if (isDeviceOwner(callingAdmin)) {
9549                enforceManagedProfile(targetUserId, "Target user must be a managed profile");
9550            } else {
9551                // Further lock down to profile owner in managed profile.
9552                enforceManagedProfile(callingUserId,
9553                        "Only support profile owner in managed profile.");
9554                if (mOwners.getDeviceOwnerUserId() != targetUserId) {
9555                    throw new SecurityException("Target user must be a device owner.");
9556                }
9557            }
9558        }
9559        final long callingIdentity = mInjector.binderClearCallingIdentity();
9560        try {
9561            if (!mUserManager.isSameProfileGroup(callingUserId, targetUserId)) {
9562                throw new SecurityException(
9563                        "Can only bind service across users under the same profile group");
9564            }
9565            final String targetPackage;
9566            synchronized (this) {
9567                targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
9568            }
9569            // STOPSHIP(b/31952368): Add policy to control which packages can talk.
9570            if (TextUtils.isEmpty(targetPackage) || !targetPackage.equals(admin.getPackageName())) {
9571                throw new SecurityException("Device owner and profile owner must be the same " +
9572                        "package in order to communicate.");
9573            }
9574            // Validate and sanitize the incoming service intent.
9575            final Intent sanitizedIntent =
9576                    createCrossUserServiceIntent(serviceIntent, targetPackage);
9577            if (sanitizedIntent == null) {
9578                // Fail, cannot lookup the target service.
9579                throw new SecurityException("Invalid intent or failed to look up the service");
9580            }
9581            // Ask ActivityManager to bind it. Notice that we are binding the service with the
9582            // caller app instead of DevicePolicyManagerService.
9583            try {
9584                return mInjector.getIActivityManager().bindService(
9585                        caller, activtiyToken, serviceIntent,
9586                        serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
9587                        connection, flags, mContext.getOpPackageName(),
9588                        targetUserId) != 0;
9589            } catch (RemoteException ex) {
9590                // Same process, should not happen.
9591            }
9592        } finally {
9593            mInjector.binderRestoreCallingIdentity(callingIdentity);
9594        }
9595        // Fail to bind.
9596        return false;
9597    }
9598
9599    /**
9600     * Return true if a given user has any accounts that'll prevent installing a device or profile
9601     * owner {@code owner}.
9602     * - If the user has no accounts, then return false.
9603     * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9604     * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9605     *   ..._DISALLOWED, return true.
9606     * - Otherwise return false.
9607     */
9608    private boolean hasIncompatibleAccountsLocked(int userId, @Nullable ComponentName owner) {
9609        final long token = mInjector.binderClearCallingIdentity();
9610        try {
9611            final AccountManager am = AccountManager.get(mContext);
9612            final Account accounts[] = am.getAccountsAsUser(userId);
9613            if (accounts.length == 0) {
9614                return false;
9615            }
9616            final String[] feature_allow =
9617                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9618            final String[] feature_disallow =
9619                    { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9620
9621            // Even if we find incompatible accounts along the way, we still check all accounts
9622            // for logging.
9623            boolean compatible = true;
9624            for (Account account : accounts) {
9625                if (hasAccountFeatures(am, account, feature_disallow)) {
9626                    Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9627                    compatible = false;
9628                }
9629                if (!hasAccountFeatures(am, account, feature_allow)) {
9630                    Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9631                    compatible = false;
9632                }
9633            }
9634            if (compatible) {
9635                Log.w(LOG_TAG, "All accounts are compatible");
9636            } else {
9637                Log.e(LOG_TAG, "Found incompatible accounts");
9638            }
9639
9640            // Then check if the owner is test-only.
9641            String log;
9642            if (owner == null) {
9643                // Owner is unknown.  Suppose it's not test-only
9644                compatible = false;
9645                log = "Only test-only device/profile owner can be installed with accounts";
9646            } else if (isAdminTestOnlyLocked(owner, userId)) {
9647                if (compatible) {
9648                    log = "Installing test-only owner " + owner;
9649                } else {
9650                    log = "Can't install test-only owner " + owner + " with incompatible accounts";
9651                }
9652            } else {
9653                compatible = false;
9654                log = "Can't install non test-only owner " + owner + " with accounts";
9655            }
9656            if (compatible) {
9657                Log.w(LOG_TAG, log);
9658            } else {
9659                Log.e(LOG_TAG, log);
9660            }
9661            return !compatible;
9662        } finally {
9663            mInjector.binderRestoreCallingIdentity(token);
9664        }
9665    }
9666
9667    private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9668        try {
9669            return am.hasFeatures(account, features, null, null).getResult();
9670        } catch (Exception e) {
9671            Log.w(LOG_TAG, "Failed to get account feature", e);
9672            return false;
9673        }
9674    }
9675
9676    private boolean isAdb() {
9677        final int callingUid = mInjector.binderGetCallingUid();
9678        return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
9679    }
9680
9681    @Override
9682    public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
9683        if (!mHasFeature) {
9684            return;
9685        }
9686        Preconditions.checkNotNull(admin);
9687        ensureDeviceOwnerManagingSingleUser(admin);
9688
9689        if (enabled == isNetworkLoggingEnabledInternalLocked()) {
9690            // already in the requested state
9691            return;
9692        }
9693        getDeviceOwnerAdminLocked().isNetworkLoggingEnabled = enabled;
9694        saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9695
9696        setNetworkLoggingActiveInternal(enabled);
9697    }
9698
9699    private synchronized void setNetworkLoggingActiveInternal(boolean active) {
9700        final long callingIdentity = mInjector.binderClearCallingIdentity();
9701        try {
9702            if (active) {
9703                mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
9704                if (!mNetworkLogger.startNetworkLogging()) {
9705                    mNetworkLogger = null;
9706                    Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
9707                            + " service not being available yet.");
9708                }
9709            } else {
9710                if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
9711                    mNetworkLogger = null;
9712                    Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
9713                            + " service not being available yet.");
9714                }
9715                mNetworkLogger = null;
9716            }
9717        } finally {
9718            mInjector.binderRestoreCallingIdentity(callingIdentity);
9719        }
9720    }
9721
9722    @Override
9723    public boolean isNetworkLoggingEnabled(ComponentName admin) {
9724        if (!mHasFeature) {
9725            return false;
9726        }
9727        Preconditions.checkNotNull(admin);
9728        synchronized (this) {
9729            getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9730            return isNetworkLoggingEnabledInternalLocked();
9731        }
9732    }
9733
9734    private boolean isNetworkLoggingEnabledInternalLocked() {
9735        ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9736        return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
9737    }
9738
9739    /*
9740     * A maximum of 1200 events are returned, and the total marshalled size is in the order of
9741     * 100kB, so returning a List instead of ParceledListSlice is acceptable.
9742     * Ideally this would be done with ParceledList, however it only supports homogeneous types.
9743     *
9744     * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
9745     */
9746    @Override
9747    public synchronized List<NetworkEvent> retrieveNetworkLogs(ComponentName admin,
9748            long batchToken) {
9749        if (!mHasFeature) {
9750            return null;
9751        }
9752        Preconditions.checkNotNull(admin);
9753        ensureDeviceOwnerManagingSingleUser(admin);
9754
9755        if (mNetworkLogger == null) {
9756            return null;
9757        }
9758
9759        if (!isNetworkLoggingEnabledInternalLocked()) {
9760            return null;
9761        }
9762
9763        final long currentTime = System.currentTimeMillis();
9764        synchronized (this) {
9765            DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
9766            if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
9767                policyData.mLastNetworkLogsRetrievalTime = currentTime;
9768                saveSettingsLocked(UserHandle.USER_SYSTEM);
9769            }
9770        }
9771
9772        return mNetworkLogger.retrieveLogs(batchToken);
9773    }
9774
9775    /**
9776     * Return the package name of owner in a given user.
9777     */
9778    private String getOwnerPackageNameForUserLocked(int userId) {
9779        return getDeviceOwnerUserId() == userId
9780                ? mOwners.getDeviceOwnerPackageName()
9781                : mOwners.getProfileOwnerPackage(userId);
9782    }
9783
9784    /**
9785     * @param rawIntent Original service intent specified by caller.
9786     * @param expectedPackageName The expected package name in the incoming intent.
9787     * @return Intent that have component explicitly set. {@code null} if the incoming intent
9788     *         or target service is invalid.
9789     */
9790    private Intent createCrossUserServiceIntent (
9791            @NonNull Intent rawIntent, @NonNull String expectedPackageName) {
9792        if (rawIntent.getComponent() == null && rawIntent.getPackage() == null) {
9793            Log.e(LOG_TAG, "Service intent must be explicit (with a package name or component): "
9794                    + rawIntent);
9795            return null;
9796        }
9797        ResolveInfo info = mInjector.getPackageManager().resolveService(rawIntent, 0);
9798        if (info == null || info.serviceInfo == null) {
9799            Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent);
9800            return null;
9801        }
9802        if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
9803            Log.e(LOG_TAG, "Only allow to bind service in " + expectedPackageName);
9804            return null;
9805        }
9806        if (info.serviceInfo.exported) {
9807            Log.e(LOG_TAG, "The service must be unexported.");
9808            return null;
9809        }
9810        // It is the system server to bind the service, it would be extremely dangerous if it
9811        // can be exploited to bind any service. Set the component explicitly to make sure we
9812        // do not bind anything accidentally.
9813        rawIntent.setComponent(info.serviceInfo.getComponentName());
9814        return rawIntent;
9815    }
9816
9817    @Override
9818    public long getLastSecurityLogRetrievalTime() {
9819        enforceSystemUid();
9820        return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
9821     }
9822
9823    @Override
9824    public long getLastBugReportRequestTime() {
9825        enforceSystemUid();
9826        return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
9827     }
9828
9829    @Override
9830    public long getLastNetworkLogRetrievalTime() {
9831        enforceSystemUid();
9832        return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
9833    }
9834}
9835