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