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