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