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